id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,313
|
processexecutor.cpp
|
danmar_cppcheck/cli/processexecutor.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "processexecutor.h"
#if !defined(WIN32) && !defined(__MINGW32__)
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "settings.h"
#include "suppressions.h"
#include "timer.h"
#include <algorithm>
#include <numeric>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <sstream>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <utility>
#include <fcntl.h>
#ifdef __SVR4 // Solaris
#include <sys/loadavg.h>
#endif
#if defined(__linux__)
#include <sys/prctl.h>
#endif
enum class Color : std::uint8_t;
// NOLINTNEXTLINE(misc-unused-using-decls) - required for FD_ZERO
using std::memset;
ProcessExecutor::ProcessExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand)
: Executor(files, fileSettings, settings, suppressions, errorLogger)
, mExecuteCommand(std::move(executeCommand))
{
assert(mSettings.jobs > 1);
}
namespace {
class PipeWriter : public ErrorLogger {
public:
enum PipeSignal : std::uint8_t {REPORT_OUT='1',REPORT_ERROR='2', CHILD_END='5'};
explicit PipeWriter(int pipe) : mWpipe(pipe) {}
void reportOut(const std::string &outmsg, Color c) override {
writeToPipe(REPORT_OUT, static_cast<char>(c) + outmsg);
}
void reportErr(const ErrorMessage &msg) override {
writeToPipe(REPORT_ERROR, msg.serialize());
}
void writeEnd(const std::string& str) const {
writeToPipe(CHILD_END, str);
}
private:
// TODO: how to log file name in error?
void writeToPipeInternal(PipeSignal type, const void* data, std::size_t to_write) const
{
const ssize_t bytes_written = write(mWpipe, data, to_write);
if (bytes_written <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::writeToPipeInternal() error for type " << type << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
// TODO: write until everything is written
if (bytes_written != to_write) {
std::cerr << "#### ThreadExecutor::writeToPipeInternal() error for type " << type << ": insufficient data written (expected: " << to_write << " / got: " << bytes_written << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
}
void writeToPipe(PipeSignal type, const std::string &data) const
{
{
const auto t = static_cast<char>(type);
writeToPipeInternal(type, &t, 1);
}
const auto len = static_cast<unsigned int>(data.length());
{
static constexpr std::size_t l_size = sizeof(unsigned int);
writeToPipeInternal(type, &len, l_size);
}
writeToPipeInternal(type, data.c_str(), len);
}
const int mWpipe;
};
}
bool ProcessExecutor::handleRead(int rpipe, unsigned int &result, const std::string& filename)
{
std::size_t bytes_to_read;
ssize_t bytes_read;
char type = 0;
bytes_to_read = sizeof(char);
bytes_read = read(rpipe, &type, bytes_to_read);
if (bytes_read <= 0) {
if (errno == EAGAIN)
return true;
// TODO: log details about failure
// need to increment so a missing pipe (i.e. premature exit of forked process) results in an error exitcode
++result;
return false;
}
if (bytes_read != bytes_to_read) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (type): insufficient data read (expected: " << bytes_to_read << " / got: " << bytes_read << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
if (type != PipeWriter::REPORT_OUT && type != PipeWriter::REPORT_ERROR && type != PipeWriter::CHILD_END) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") invalid type " << int(type) << std::endl;
std::exit(EXIT_FAILURE);
}
unsigned int len = 0;
bytes_to_read = sizeof(len);
bytes_read = read(rpipe, &len, bytes_to_read);
if (bytes_read <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (len) for type " << int(type) << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
if (bytes_read != bytes_to_read) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (len) for type" << int(type) << ": insufficient data read (expected: " << bytes_to_read << " / got: " << bytes_read << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
std::string buf(len, '\0');
char *data_start = &buf[0];
bytes_to_read = len;
do {
bytes_read = read(rpipe, data_start, bytes_to_read);
if (bytes_read <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (buf) for type" << int(type) << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
bytes_to_read -= bytes_read;
data_start += bytes_read;
} while (bytes_to_read != 0);
bool res = true;
if (type == PipeWriter::REPORT_OUT) {
// the first character is the color
const auto c = static_cast<Color>(buf[0]);
// TODO: avoid string copy
mErrorLogger.reportOut(buf.substr(1), c);
} else if (type == PipeWriter::REPORT_ERROR) {
ErrorMessage msg;
try {
msg.deserialize(buf);
} catch (const InternalError& e) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") internal error: " << e.errorMessage << std::endl;
std::exit(EXIT_FAILURE);
}
if (hasToLog(msg))
mErrorLogger.reportErr(msg);
} else if (type == PipeWriter::CHILD_END) {
result += std::stoi(buf);
res = false;
}
return res;
}
bool ProcessExecutor::checkLoadAverage(size_t nchildren)
{
#if defined(__QNX__) || defined(__HAIKU__) // getloadavg() is unsupported on Qnx, Haiku.
(void)nchildren;
return true;
#else
if (!nchildren || !mSettings.loadAverage) {
return true;
}
double sample(0);
if (getloadavg(&sample, 1) != 1) {
// disable load average checking on getloadavg error
return true;
}
if (sample < mSettings.loadAverage) {
return true;
}
return false;
#endif
}
unsigned int ProcessExecutor::check()
{
unsigned int fileCount = 0;
unsigned int result = 0;
const std::size_t totalfilesize = std::accumulate(mFiles.cbegin(), mFiles.cend(), std::size_t(0), [](std::size_t v, const FileWithDetails& p) {
return v + p.size();
});
std::list<int> rpipes;
std::map<pid_t, std::string> childFile;
std::map<int, std::string> pipeFile;
std::size_t processedsize = 0;
std::list<FileWithDetails>::const_iterator iFile = mFiles.cbegin();
std::list<FileSettings>::const_iterator iFileSettings = mFileSettings.cbegin();
for (;;) {
// Start a new child
const size_t nchildren = childFile.size();
if ((iFile != mFiles.cend() || iFileSettings != mFileSettings.cend()) && nchildren < mSettings.jobs && checkLoadAverage(nchildren)) {
int pipes[2];
if (pipe(pipes) == -1) {
std::cerr << "#### ThreadExecutor::check, pipe() failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
}
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);
}
if (fcntl(pipes[0], F_SETFL, flags) < 0) {
std::cerr << "#### ThreadExecutor::check, fcntl(F_SETFL) failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
}
const pid_t pid = fork();
if (pid < 0) {
// Error
std::cerr << "#### ThreadExecutor::check, Failed to create child process: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
} else if (pid == 0) {
#if defined(__linux__)
prctl(PR_SET_PDEATHSIG, SIGHUP);
#endif
close(pipes[0]);
PipeWriter pipewriter(pipes[1]);
CppCheck fileChecker(pipewriter, false, mExecuteCommand);
fileChecker.settings() = mSettings;
unsigned int resultOfCheck = 0;
if (iFileSettings != mFileSettings.end()) {
resultOfCheck = fileChecker.check(*iFileSettings);
if (fileChecker.settings().clangTidy)
fileChecker.analyseClangTidy(*iFileSettings);
} else {
// Read file from a file
resultOfCheck = fileChecker.check(*iFile);
// TODO: call analyseClangTidy()?
}
pipewriter.writeEnd(std::to_string(resultOfCheck));
std::exit(EXIT_SUCCESS);
}
close(pipes[1]);
rpipes.push_back(pipes[0]);
if (iFileSettings != mFileSettings.end()) {
childFile[pid] = iFileSettings->filename() + ' ' + iFileSettings->cfg;
pipeFile[pipes[0]] = iFileSettings->filename() + ' ' + iFileSettings->cfg;
++iFileSettings;
} else {
childFile[pid] = iFile->path();
pipeFile[pipes[0]] = iFile->path();
++iFile;
}
}
if (!rpipes.empty()) {
fd_set rfds;
FD_ZERO(&rfds);
for (std::list<int>::const_iterator rp = rpipes.cbegin(); rp != rpipes.cend(); ++rp)
FD_SET(*rp, &rfds);
timeval tv; // for every second polling of load average condition
tv.tv_sec = 1;
tv.tv_usec = 0;
const int r = select(*std::max_element(rpipes.cbegin(), rpipes.cend()) + 1, &rfds, nullptr, nullptr, &tv);
if (r > 0) {
std::list<int>::const_iterator rp = rpipes.cbegin();
while (rp != rpipes.cend()) {
if (FD_ISSET(*rp, &rfds)) {
std::string name;
const std::map<int, std::string>::const_iterator p = pipeFile.find(*rp);
if (p != pipeFile.cend()) {
name = p->second;
}
const bool readRes = handleRead(*rp, result, name);
if (!readRes) {
std::size_t size = 0;
if (p != pipeFile.cend()) {
pipeFile.erase(p);
const auto fs = std::find_if(mFiles.cbegin(), mFiles.cend(), [&name](const FileWithDetails& entry) {
return entry.path() == name;
});
if (fs != mFiles.end()) {
size = fs->size();
}
}
fileCount++;
processedsize += size;
if (!mSettings.quiet)
Executor::reportStatus(fileCount, mFiles.size() + mFileSettings.size(), processedsize, totalfilesize);
close(*rp);
rp = rpipes.erase(rp);
} else
++rp;
} else
++rp;
}
}
}
if (!childFile.empty()) {
int stat = 0;
const pid_t child = waitpid(0, &stat, WNOHANG);
if (child > 0) {
std::string childname;
const std::map<pid_t, std::string>::const_iterator c = childFile.find(child);
if (c != childFile.cend()) {
childname = c->second;
childFile.erase(c);
}
if (WIFEXITED(stat)) {
const int exitstatus = WEXITSTATUS(stat);
if (exitstatus != EXIT_SUCCESS) {
std::ostringstream oss;
oss << "Child process exited with " << exitstatus;
reportInternalChildErr(childname, oss.str());
}
} else if (WIFSIGNALED(stat)) {
std::ostringstream oss;
oss << "Child process crashed with signal " << WTERMSIG(stat);
reportInternalChildErr(childname, oss.str());
}
}
}
if (iFile == mFiles.end() && iFileSettings == mFileSettings.end() && rpipes.empty() && childFile.empty()) {
// All done
break;
}
}
// TODO: wee need to get the timing information from the subprocess
if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_SUMMARY || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY)
CppCheck::printTimerResults(mSettings.showtime);
return result;
}
void ProcessExecutor::reportInternalChildErr(const std::string &childname, const std::string &msg)
{
std::list<ErrorMessage::FileLocation> locations;
locations.emplace_back(childname, 0, 0);
const ErrorMessage errmsg(std::move(locations),
emptyString,
Severity::error,
"Internal error: " + msg,
"cppcheckError",
Certainty::normal);
if (!mSuppressions.isSuppressed(errmsg, {}))
mErrorLogger.reportErr(errmsg);
}
#endif // !WIN32
| 15,194
|
C++
|
.cpp
| 357
| 31.728291
| 240
| 0.547447
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,314
|
executor.cpp
|
danmar_cppcheck/cli/executor.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "executor.h"
#include "color.h"
#include "errorlogger.h"
#include "library.h"
#include "settings.h"
#include "suppressions.h"
#include <cassert>
#include <sstream>
#include <utility>
struct FileSettings;
Executor::Executor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger)
: mFiles(files), mFileSettings(fileSettings), mSettings(settings), mSuppressions(suppressions), mErrorLogger(errorLogger)
{
// the two inputs may only be used exclusively
assert(!(!files.empty() && !fileSettings.empty()));
}
// TODO: this logic is duplicated in CppCheck::reportErr()
bool Executor::hasToLog(const ErrorMessage &msg)
{
if (!mSettings.library.reportErrors(msg.file0))
return false;
if (!mSuppressions.isSuppressed(msg, {}))
{
// TODO: there should be no need for verbose and default messages here
std::string errmsg = msg.toString(mSettings.verbose);
if (errmsg.empty())
return false;
std::lock_guard<std::mutex> lg(mErrorListSync);
if (mErrorList.emplace(std::move(errmsg)).second) {
return true;
}
}
return false;
}
void Executor::reportStatus(std::size_t fileindex, std::size_t filecount, std::size_t sizedone, std::size_t sizetotal)
{
if (filecount > 1) {
std::ostringstream oss;
const unsigned long percentDone = (sizetotal > 0) ? (100 * sizedone) / sizetotal : 0;
oss << fileindex << '/' << filecount
<< " files checked " << percentDone
<< "% done";
mErrorLogger.reportOut(oss.str(), Color::FgBlue);
}
}
| 2,462
|
C++
|
.cpp
| 62
| 35.451613
| 187
| 0.703347
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,315
|
signalhandler.cpp
|
danmar_cppcheck/cli/signalhandler.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "signalhandler.h"
#if defined(USE_UNIX_SIGNAL_HANDLING)
#ifdef USE_UNIX_BACKTRACE_SUPPORT
#include "stacktrace.h"
#endif
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
//#include <features.h> // __USE_DYNAMIC_STACK_SIZE
#include <map>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#if defined(__linux__) && defined(REG_ERR)
#include <sys/syscall.h>
#endif
#if defined(__APPLE__)
# define _XOPEN_SOURCE // ucontext.h APIs can only be used on Mac OSX >= 10.7 if _XOPEN_SOURCE is defined
# include <ucontext.h>
# undef _XOPEN_SOURCE
#elif !defined(__OpenBSD__) && !defined(__HAIKU__)
# include <ucontext.h>
#endif
// TODO: __USE_DYNAMIC_STACK_SIZE is dependent on the features.h include and not a built-in compiler define, so it might be problematic to depend on it
#ifdef __USE_DYNAMIC_STACK_SIZE
static constexpr size_t MYSTACKSIZE = (16*1024)+32768; // wild guess about a reasonable buffer
#else
static constexpr size_t MYSTACKSIZE = 16*1024+SIGSTKSZ; // wild guess about a reasonable buffer
#endif
static char mytstack[MYSTACKSIZE]= {0}; // alternative stack for signal handler
static bool bStackBelowHeap=false; // lame attempt to locate heap vs. stack address space. See CppCheckExecutor::check_wrapper()
static FILE* signalOutput = stdout; // TODO: get rid of this
/**
* \param[in] ptr address to be examined.
* \return true if address is supposed to be on stack (contrary to heap). If ptr is 0 false will be returned.
* If unknown better return false.
*/
static bool IsAddressOnStack(const void* ptr)
{
if (nullptr==ptr)
return false;
char a;
if (bStackBelowHeap)
return ptr < &a;
return ptr > &a;
}
/* (declare this list here, so it may be used in signal handlers in addition to main())
* A list of signals available in ISO C
* Check out http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html
* For now we only want to detect abnormal behaviour for a few selected signals:
*/
#define DECLARE_SIGNAL(x) std::make_pair(x, #x)
using Signalmap_t = std::map<int, std::string>;
static const Signalmap_t listofsignals = {
DECLARE_SIGNAL(SIGABRT),
DECLARE_SIGNAL(SIGBUS),
DECLARE_SIGNAL(SIGFPE),
DECLARE_SIGNAL(SIGILL),
DECLARE_SIGNAL(SIGINT),
DECLARE_SIGNAL(SIGQUIT),
DECLARE_SIGNAL(SIGSEGV),
DECLARE_SIGNAL(SIGSYS),
// don't care: SIGTERM
DECLARE_SIGNAL(SIGUSR1),
//DECLARE_SIGNAL(SIGUSR2) no usage currently
};
#undef DECLARE_SIGNAL
/*
* Entry pointer for signal handlers
* It uses functions which are not safe to be called from a signal handler,
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04 has a whitelist)
* but when ending up here something went terribly wrong anyway.
* And all which is left is just printing some information and terminate.
*/
// cppcheck-suppress constParameterCallback
static void CppcheckSignalHandler(int signo, siginfo_t * info, void * context)
{
int type = -1;
pid_t killid;
// TODO: separate these two defines
#if defined(__linux__) && defined(REG_ERR)
const auto* const uc = reinterpret_cast<const ucontext_t*>(context);
killid = (pid_t) syscall(SYS_gettid);
if (uc) {
type = (int)uc->uc_mcontext.gregs[REG_ERR] & 2;
}
#else
(void)context;
killid = getpid();
#endif
const Signalmap_t::const_iterator it=listofsignals.find(signo);
const char * const signame = (it==listofsignals.end()) ? "unknown" : it->second.c_str();
bool unexpectedSignal=true; // unexpected indicates program failure
bool terminate=true; // exit process/thread
const bool isAddressOnStack = IsAddressOnStack(info->si_addr);
FILE * const output = signalOutput;
switch (signo) {
case SIGABRT:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
fputs(
#ifdef NDEBUG
" - abort\n",
#else
" - abort or assertion\n",
#endif
output);
break;
case SIGBUS:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case BUS_ADRALN: // invalid address alignment
fputs(" - BUS_ADRALN", output);
break;
case BUS_ADRERR: // nonexistent physical address
fputs(" - BUS_ADRERR", output);
break;
case BUS_OBJERR: // object-specific hardware error
fputs(" - BUS_OBJERR", output);
break;
#ifdef BUS_MCEERR_AR
case BUS_MCEERR_AR: // Hardware memory error consumed on a machine check;
fputs(" - BUS_MCEERR_AR", output);
break;
#endif
#ifdef BUS_MCEERR_AO
case BUS_MCEERR_AO: // Hardware memory error detected in process but not consumed
fputs(" - BUS_MCEERR_AO", output);
break;
#endif
default:
break;
}
fprintf(output, " (at 0x%lx).\n",
(unsigned long)info->si_addr);
break;
case SIGFPE:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case FPE_INTDIV: // integer divide by zero
fputs(" - FPE_INTDIV", output);
break;
case FPE_INTOVF: // integer overflow
fputs(" - FPE_INTOVF", output);
break;
case FPE_FLTDIV: // floating-point divide by zero
fputs(" - FPE_FLTDIV", output);
break;
case FPE_FLTOVF: // floating-point overflow
fputs(" - FPE_FLTOVF", output);
break;
case FPE_FLTUND: // floating-point underflow
fputs(" - FPE_FLTUND", output);
break;
case FPE_FLTRES: // floating-point inexact result
fputs(" - FPE_FLTRES", output);
break;
case FPE_FLTINV: // floating-point invalid operation
fputs(" - FPE_FLTINV", output);
break;
case FPE_FLTSUB: // subscript out of range
fputs(" - FPE_FLTSUB", output);
break;
default:
break;
}
fprintf(output, " (at 0x%lx).\n",
(unsigned long)info->si_addr);
break;
case SIGILL:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case ILL_ILLOPC: // illegal opcode
fputs(" - ILL_ILLOPC", output);
break;
case ILL_ILLOPN: // illegal operand
fputs(" - ILL_ILLOPN", output);
break;
case ILL_ILLADR: // illegal addressing mode
fputs(" - ILL_ILLADR", output);
break;
case ILL_ILLTRP: // illegal trap
fputs(" - ILL_ILLTRP", output);
break;
case ILL_PRVOPC: // privileged opcode
fputs(" - ILL_PRVOPC", output);
break;
case ILL_PRVREG: // privileged register
fputs(" - ILL_PRVREG", output);
break;
case ILL_COPROC: // coprocessor error
fputs(" - ILL_COPROC", output);
break;
case ILL_BADSTK: // internal stack error
fputs(" - ILL_BADSTK", output);
break;
default:
break;
}
fprintf(output, " (at 0x%lx).%s\n",
(unsigned long)info->si_addr,
(isAddressOnStack)?" Stackoverflow?":"");
break;
case SIGINT:
unexpectedSignal=false; // legal usage: interrupt application via CTRL-C
fputs("cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
break;
case SIGSEGV:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case SEGV_MAPERR: // address not mapped to object
fputs(" - SEGV_MAPERR", output);
break;
case SEGV_ACCERR: // invalid permissions for mapped object
fputs(" - SEGV_ACCERR", output);
break;
default:
break;
}
fprintf(output, " (%sat 0x%lx).%s\n",
// cppcheck-suppress knownConditionTrueFalse ; FP
(type==-1)? "" :
(type==0) ? "reading " : "writing ",
(unsigned long)info->si_addr,
(isAddressOnStack)?" Stackoverflow?":""
);
break;
case SIGUSR1:
fputs("cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
terminate=false;
break;
default:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
break;
}
#ifdef USE_UNIX_BACKTRACE_SUPPORT
// flush otherwise the trace might be printed earlier
fflush(output);
print_stacktrace(output, 1, true, -1, true);
#endif
if (unexpectedSignal) {
fputs("\nPlease report this to the cppcheck developers!\n", output);
}
fflush(output);
if (terminate) {
// now let things proceed, shutdown and hopefully dump core for post-mortem analysis
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler=SIG_DFL;
sigaction(signo, &act, nullptr);
kill(killid, signo);
}
}
void register_signal_handler(FILE * const output)
{
signalOutput = output;
// determine stack vs. heap
char stackVariable;
char *heapVariable=static_cast<char*>(malloc(1));
bStackBelowHeap = &stackVariable < heapVariable;
free(heapVariable);
// set up alternative stack for signal handler
stack_t segv_stack;
segv_stack.ss_sp = mytstack;
segv_stack.ss_flags = 0;
segv_stack.ss_size = MYSTACKSIZE;
if (sigaltstack(&segv_stack, nullptr) != 0) {
// TODO: log errno
fputs("could not set alternate signal stack context.\n", output);
std::exit(EXIT_FAILURE);
}
// install signal handler
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_flags=SA_SIGINFO|SA_ONSTACK;
act.sa_sigaction=CppcheckSignalHandler;
for (std::map<int, std::string>::const_iterator sig=listofsignals.cbegin(); sig!=listofsignals.cend(); ++sig) {
sigaction(sig->first, &act, nullptr);
}
}
#endif
| 11,467
|
C++
|
.cpp
| 310
| 30.248387
| 151
| 0.617739
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,317
|
simplecpp.cpp
|
danmar_cppcheck/externals/simplecpp/simplecpp.cpp
|
/*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2023 simplecpp team
*/
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
#define SIMPLECPP_WINDOWS
#define NOMINMAX
#endif
#include "simplecpp.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstddef> // IWYU pragma: keep
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <istream>
#include <limits>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#if __cplusplus >= 201103L
#ifdef SIMPLECPP_WINDOWS
#include <mutex>
#endif
#include <unordered_map>
#endif
#include <utility>
#include <vector>
#ifdef SIMPLECPP_WINDOWS
#include <windows.h>
#undef ERROR
#endif
#if __cplusplus >= 201103L
#define OVERRIDE override
#define EXPLICIT explicit
#else
#define OVERRIDE
#define EXPLICIT
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
static bool isHex(const std::string &s)
{
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
}
static bool isOct(const std::string &s)
{
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isStringLiteral_(const std::string &s)
{
return s.size() > 1 && (s[0]=='\"') && (*s.rbegin()=='\"');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isCharLiteral_(const std::string &s)
{
// char literal patterns can include 'a', '\t', '\000', '\xff', 'abcd', and maybe ''
// This only checks for the surrounding '' but doesn't parse the content.
return s.size() > 1 && (s[0]=='\'') && (*s.rbegin()=='\'');
}
static const simplecpp::TokenString DEFINE("define");
static const simplecpp::TokenString UNDEF("undef");
static const simplecpp::TokenString INCLUDE("include");
static const simplecpp::TokenString ERROR("error");
static const simplecpp::TokenString WARNING("warning");
static const simplecpp::TokenString IF("if");
static const simplecpp::TokenString IFDEF("ifdef");
static const simplecpp::TokenString IFNDEF("ifndef");
static const simplecpp::TokenString DEFINED("defined");
static const simplecpp::TokenString ELSE("else");
static const simplecpp::TokenString ELIF("elif");
static const simplecpp::TokenString ENDIF("endif");
static const simplecpp::TokenString PRAGMA("pragma");
static const simplecpp::TokenString ONCE("once");
static const simplecpp::TokenString HAS_INCLUDE("__has_include");
static const simplecpp::TokenString INNER_COMMA(",,");
template<class T> static std::string toString(T t)
{
// NOLINTNEXTLINE(misc-const-correctness) - false positive
std::ostringstream ostr;
ostr << t;
return ostr.str();
}
static long long stringToLL(const std::string &s)
{
long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static unsigned long long stringToULL(const std::string &s)
{
unsigned long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static bool endsWith(const std::string &s, const std::string &e)
{
return (s.size() >= e.size()) && std::equal(e.rbegin(), e.rend(), s.rbegin());
}
static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2)
{
return tok1 && tok2 && tok1->location.sameline(tok2->location);
}
static bool isAlternativeBinaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return (tok->name &&
tok->str() == alt &&
tok->previous &&
tok->next &&
(tok->previous->number || tok->previous->name || tok->previous->op == ')') &&
(tok->next->number || tok->next->name || tok->next->op == '('));
}
static bool isAlternativeUnaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return ((tok->name && tok->str() == alt) &&
(!tok->previous || tok->previous->op == '(') &&
(tok->next && (tok->next->name || tok->next->number)));
}
static std::string replaceAll(std::string s, const std::string& from, const std::string& to)
{
for (size_t pos = s.find(from); pos != std::string::npos; pos = s.find(from, pos + to.size()))
s.replace(pos, from.size(), to);
return s;
}
const std::string simplecpp::Location::emptyFileName;
void simplecpp::Location::adjust(const std::string &str)
{
if (strpbrk(str.c_str(), "\r\n") == nullptr) {
col += str.size();
return;
}
for (std::size_t i = 0U; i < str.size(); ++i) {
col++;
if (str[i] == '\n' || str[i] == '\r') {
col = 1;
line++;
if (str[i] == '\r' && (i+1)<str.size() && str[i+1]=='\n')
++i;
}
}
}
bool simplecpp::Token::isOneOf(const char ops[]) const
{
return (op != '\0') && (std::strchr(ops, op) != nullptr);
}
bool simplecpp::Token::startsWithOneOf(const char c[]) const
{
return std::strchr(c, string[0]) != nullptr;
}
bool simplecpp::Token::endsWithOneOf(const char c[]) const
{
return std::strchr(c, string[string.size() - 1U]) != nullptr;
}
void simplecpp::Token::printAll() const
{
const Token *tok = this;
while (tok->previous)
tok = tok->previous;
for (; tok; tok = tok->next) {
if (tok->previous) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
void simplecpp::Token::printOut() const
{
for (const Token *tok = this; tok; tok = tok->next) {
if (tok != this) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
// cppcheck-suppress noConstructor - we call init() in the inherited to initialize the private members
class simplecpp::TokenList::Stream {
public:
virtual ~Stream() {}
virtual int get() = 0;
virtual int peek() = 0;
virtual void unget() = 0;
virtual bool good() = 0;
unsigned char readChar()
{
unsigned char ch = static_cast<unsigned char>(get());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
const unsigned char ch2 = static_cast<unsigned char>(get());
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r') {
ch = '\n';
int ch2 = get();
if (isUtf16) {
const int c2 = get();
ch2 = makeUtf16Char(ch2, c2);
}
if (ch2 != '\n')
ungetChar();
}
return ch;
}
unsigned char peekChar()
{
unsigned char ch = static_cast<unsigned char>(peek());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
(void)get();
const unsigned char ch2 = static_cast<unsigned char>(peek());
unget();
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r')
ch = '\n';
return ch;
}
void ungetChar()
{
unget();
if (isUtf16)
unget();
}
protected:
void init() {
// initialize since we use peek() in getAndSkipBOM()
isUtf16 = false;
bom = getAndSkipBOM();
isUtf16 = (bom == 0xfeff || bom == 0xfffe);
}
private:
inline int makeUtf16Char(const unsigned char ch, const unsigned char ch2) const
{
return (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
}
unsigned short getAndSkipBOM()
{
const int ch1 = peek();
// The UTF-16 BOM is 0xfffe or 0xfeff.
if (ch1 >= 0xfe) {
(void)get();
const unsigned short byte = (static_cast<unsigned char>(ch1) << 8);
if (peek() >= 0xfe)
return byte | static_cast<unsigned char>(get());
unget();
return 0;
}
// Skip UTF-8 BOM 0xefbbbf
if (ch1 == 0xef) {
(void)get();
if (peek() == 0xbb) {
(void)get();
if (peek() == 0xbf) {
(void)get();
return 0;
}
unget();
}
unget();
}
return 0;
}
unsigned short bom;
protected:
bool isUtf16;
};
class StdIStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT StdIStream(std::istream &istr)
: istr(istr)
{
assert(istr.good());
init();
}
virtual int get() OVERRIDE {
return istr.get();
}
virtual int peek() OVERRIDE {
return istr.peek();
}
virtual void unget() OVERRIDE {
istr.unget();
}
virtual bool good() OVERRIDE {
return istr.good();
}
private:
std::istream &istr;
};
class StdCharBufStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
StdCharBufStream(const unsigned char* str, std::size_t size)
: str(str)
, size(size)
, pos(0)
, lastStatus(0)
{
init();
}
virtual int get() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos++];
}
virtual int peek() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos];
}
virtual void unget() OVERRIDE {
--pos;
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
const unsigned char *str;
const std::size_t size;
std::size_t pos;
int lastStatus;
};
class FileStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT FileStream(const std::string &filename, std::vector<std::string> &files)
: file(fopen(filename.c_str(), "rb"))
, lastCh(0)
, lastStatus(0)
{
if (!file) {
files.push_back(filename);
throw simplecpp::Output(files, simplecpp::Output::FILE_NOT_FOUND, "File is missing: " + filename);
}
init();
}
~FileStream() OVERRIDE {
fclose(file);
file = nullptr;
}
virtual int get() OVERRIDE {
lastStatus = lastCh = fgetc(file);
return lastCh;
}
virtual int peek() OVERRIDE{
// keep lastCh intact
const int ch = fgetc(file);
unget_internal(ch);
return ch;
}
virtual void unget() OVERRIDE {
unget_internal(lastCh);
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
void unget_internal(int ch) {
if (isUtf16) {
// TODO: use ungetc() as well
// UTF-16 has subsequent unget() calls
fseek(file, -1, SEEK_CUR);
}
else
ungetc(ch, file);
}
FileStream(const FileStream&);
FileStream &operator=(const FileStream&);
FILE *file;
int lastCh;
int lastStatus;
};
simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(nullptr), backToken(nullptr), files(filenames) {}
simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdIStream stream(istr);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const unsigned char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(data, size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(data), size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const std::string &filename, std::vector<std::string> &filenames, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
try
{
FileStream stream(filename, filenames);
readfile(stream,filename,outputList);
}
catch(const simplecpp::Output & e) // TODO handle extra type of errors
{
outputList->push_back(e);
}
}
simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = other;
}
#if __cplusplus >= 201103L
simplecpp::TokenList::TokenList(TokenList &&other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = std::move(other);
}
#endif
simplecpp::TokenList::~TokenList()
{
clear();
}
simplecpp::TokenList &simplecpp::TokenList::operator=(const TokenList &other)
{
if (this != &other) {
clear();
files = other.files;
for (const Token *tok = other.cfront(); tok; tok = tok->next)
push_back(new Token(*tok));
sizeOfType = other.sizeOfType;
}
return *this;
}
#if __cplusplus >= 201103L
simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
{
if (this != &other) {
clear();
frontToken = other.frontToken;
other.frontToken = nullptr;
backToken = other.backToken;
other.backToken = nullptr;
files = other.files;
sizeOfType = std::move(other.sizeOfType);
}
return *this;
}
#endif
void simplecpp::TokenList::clear()
{
backToken = nullptr;
while (frontToken) {
Token * const next = frontToken->next;
delete frontToken;
frontToken = next;
}
sizeOfType.clear();
}
void simplecpp::TokenList::push_back(Token *tok)
{
if (!frontToken)
frontToken = tok;
else
backToken->next = tok;
tok->previous = backToken;
backToken = tok;
}
void simplecpp::TokenList::dump() const
{
std::cout << stringify() << std::endl;
}
std::string simplecpp::TokenList::stringify() const
{
std::ostringstream ret;
Location loc(files);
for (const Token *tok = cfront(); tok; tok = tok->next) {
if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) {
ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n";
loc = tok->location;
}
while (tok->location.line > loc.line) {
ret << '\n';
loc.line++;
}
if (sameline(tok->previous, tok))
ret << ' ';
ret << tok->str();
loc.adjust(tok->str());
}
return ret.str();
}
static bool isNameChar(unsigned char ch)
{
return std::isalnum(ch) || ch == '_' || ch == '$';
}
static std::string escapeString(const std::string &str)
{
std::ostringstream ostr;
ostr << '\"';
for (std::size_t i = 1U; i < str.size() - 1; ++i) {
const char c = str[i];
if (c == '\\' || c == '\"' || c == '\'')
ostr << '\\';
ostr << c;
}
ostr << '\"';
return ostr.str();
}
static void portabilityBackslash(simplecpp::OutputList *outputList, const std::vector<std::string> &files, const simplecpp::Location &location)
{
if (!outputList)
return;
simplecpp::Output err(files);
err.type = simplecpp::Output::PORTABILITY_BACKSLASH;
err.location = location;
err.msg = "Combination 'backslash space newline' is not portable.";
outputList->push_back(err);
}
static bool isStringLiteralPrefix(const std::string &str)
{
return str == "u" || str == "U" || str == "L" || str == "u8" ||
str == "R" || str == "uR" || str == "UR" || str == "LR" || str == "u8R";
}
void simplecpp::TokenList::lineDirective(unsigned int fileIndex, unsigned int line, Location *location)
{
if (fileIndex != location->fileIndex || line >= location->line) {
location->fileIndex = fileIndex;
location->line = line;
return;
}
if (line + 2 >= location->line) {
location->line = line;
while (cback()->op != '#')
deleteToken(back());
deleteToken(back());
return;
}
}
static const std::string COMMENT_END("*/");
void simplecpp::TokenList::readfile(Stream &stream, const std::string &filename, OutputList *outputList)
{
std::stack<simplecpp::Location> loc;
unsigned int multiline = 0U;
const Token *oldLastToken = nullptr;
Location location(files);
location.fileIndex = fileIndex(filename);
location.line = 1U;
location.col = 1U;
while (stream.good()) {
unsigned char ch = stream.readChar();
if (!stream.good())
break;
if (ch >= 0x80) {
if (outputList) {
simplecpp::Output err(files);
err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR;
err.location = location;
std::ostringstream s;
s << static_cast<int>(ch);
err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported.";
outputList->push_back(err);
}
clear();
return;
}
if (ch == '\n') {
if (cback() && cback()->op == '\\') {
if (location.col > cback()->location.col + 1U)
portabilityBackslash(outputList, files, cback()->location);
++multiline;
deleteToken(back());
} else {
location.line += multiline + 1;
multiline = 0U;
}
if (!multiline)
location.col = 1;
if (oldLastToken != cback()) {
oldLastToken = cback();
if (!isLastLinePreprocessor())
continue;
const std::string lastline(lastLine());
if (lastline == "# file %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
loc.push(location);
location.fileIndex = fileIndex(strtok->str().substr(1U, strtok->str().size() - 2U));
location.line = 1U;
} else if (lastline == "# line %num%") {
const Token *numtok = cback();
while (numtok->comment)
numtok = numtok->previous;
lineDirective(location.fileIndex, std::atol(numtok->str().c_str()), &location);
} else if (lastline == "# %num% %str%" || lastline == "# line %num% %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
const Token *numtok = strtok->previous;
while (numtok->comment)
numtok = numtok->previous;
lineDirective(fileIndex(replaceAll(strtok->str().substr(1U, strtok->str().size() - 2U),"\\\\","\\")),
std::atol(numtok->str().c_str()), &location);
}
// #endfile
else if (lastline == "# endfile" && !loc.empty()) {
location = loc.top();
loc.pop();
}
}
continue;
}
if (ch <= ' ') {
location.col++;
continue;
}
TokenString currentToken;
if (cback() && cback()->location.line == location.line && cback()->previous && cback()->previous->op == '#') {
const Token* const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && (llTok->next->str() == "error" || llTok->next->str() == "warning")) {
char prev = ' ';
while (stream.good() && (prev == '\\' || (ch != '\r' && ch != '\n'))) {
currentToken += ch;
prev = ch;
ch = stream.readChar();
}
stream.ungetChar();
push_back(new Token(currentToken, location));
location.adjust(currentToken);
continue;
}
}
// number or name
if (isNameChar(ch)) {
const bool num = std::isdigit(ch);
while (stream.good() && isNameChar(ch)) {
currentToken += ch;
ch = stream.readChar();
if (num && ch=='\'' && isNameChar(stream.peekChar()))
ch = stream.readChar();
}
stream.ungetChar();
}
// comment
else if (ch == '/' && stream.peekChar() == '/') {
while (stream.good() && ch != '\r' && ch != '\n') {
currentToken += ch;
ch = stream.readChar();
}
const std::string::size_type pos = currentToken.find_last_not_of(" \t");
if (pos < currentToken.size() - 1U && currentToken[pos] == '\\')
portabilityBackslash(outputList, files, location);
if (currentToken[currentToken.size() - 1U] == '\\') {
++multiline;
currentToken.erase(currentToken.size() - 1U);
} else {
stream.ungetChar();
}
}
// comment
else if (ch == '/' && stream.peekChar() == '*') {
currentToken = "/*";
(void)stream.readChar();
ch = stream.readChar();
while (stream.good()) {
currentToken += ch;
if (currentToken.size() >= 4U && endsWith(currentToken, COMMENT_END))
break;
ch = stream.readChar();
}
// multiline..
std::string::size_type pos = 0;
while ((pos = currentToken.find("\\\n",pos)) != std::string::npos) {
currentToken.erase(pos,2);
++multiline;
}
if (multiline || isLastLinePreprocessor()) {
pos = 0;
while ((pos = currentToken.find('\n',pos)) != std::string::npos) {
currentToken.erase(pos,1);
++multiline;
}
}
}
// string / char literal
else if (ch == '\"' || ch == '\'') {
std::string prefix;
if (cback() && cback()->name && isStringLiteralPrefix(cback()->str()) &&
((cback()->location.col + cback()->str().size()) == location.col) &&
(cback()->location.line == location.line)) {
prefix = cback()->str();
}
// C++11 raw string literal
if (ch == '\"' && !prefix.empty() && *cback()->str().rbegin() == 'R') {
std::string delim;
currentToken = ch;
prefix.resize(prefix.size() - 1);
ch = stream.readChar();
while (stream.good() && ch != '(' && ch != '\n') {
delim += ch;
ch = stream.readChar();
}
if (!stream.good() || ch == '\n') {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Invalid newline in raw string delimiter.";
outputList->push_back(err);
}
return;
}
const std::string endOfRawString(')' + delim + currentToken);
while (stream.good() && !(endsWith(currentToken, endOfRawString) && currentToken.size() > 1))
currentToken += stream.readChar();
if (!endsWith(currentToken, endOfRawString)) {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Raw string missing terminating delimiter.";
outputList->push_back(err);
}
return;
}
currentToken.erase(currentToken.size() - endOfRawString.size(), endOfRawString.size() - 1U);
currentToken = escapeString(currentToken);
currentToken.insert(0, prefix);
back()->setstr(currentToken);
location.adjust(currentToken);
if (currentToken.find_first_of("\r\n") == std::string::npos)
location.col += 2 + 2 * delim.size();
else
location.col += 1 + delim.size();
continue;
}
currentToken = readUntil(stream,location,ch,ch,outputList);
if (currentToken.size() < 2U)
// Error is reported by readUntil()
return;
std::string s = currentToken;
std::string::size_type pos;
int newlines = 0;
while ((pos = s.find_first_of("\r\n")) != std::string::npos) {
s.erase(pos,1);
newlines++;
}
if (prefix.empty())
push_back(new Token(s, location)); // push string without newlines
else
back()->setstr(prefix + s);
if (newlines > 0 ) {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && llTok->next->str() == "define" && llTok->next->next) {
multiline += newlines;
location.adjust(s);
continue;
}
}
location.adjust(currentToken);
continue;
}
else {
currentToken += ch;
}
if (*currentToken.begin() == '<') {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && llTok->next->str() == "include") {
currentToken = readUntil(stream, location, '<', '>', outputList);
if (currentToken.size() < 2U)
return;
}
}
push_back(new Token(currentToken, location));
if (multiline)
location.col += currentToken.size();
else
location.adjust(currentToken);
}
combineOperators();
}
void simplecpp::TokenList::constFold()
{
while (cfront()) {
// goto last '('
Token *tok = back();
while (tok && tok->op != '(')
tok = tok->previous;
// no '(', goto first token
if (!tok)
tok = front();
// Constant fold expression
constFoldUnaryNotPosNeg(tok);
constFoldMulDivRem(tok);
constFoldAddSub(tok);
constFoldShift(tok);
constFoldComparison(tok);
constFoldBitwise(tok);
constFoldLogicalOp(tok);
constFoldQuestionOp(&tok);
// If there is no '(' we are done with the constant folding
if (tok->op != '(')
break;
if (!tok->next || !tok->next->next || tok->next->next->op != ')')
break;
tok = tok->next;
deleteToken(tok->previous);
deleteToken(tok->next);
}
}
static bool isFloatSuffix(const simplecpp::Token *tok)
{
if (!tok || tok->str().size() != 1U)
return false;
const char c = std::tolower(tok->str()[0]);
return c == 'f' || c == 'l';
}
void simplecpp::TokenList::combineOperators()
{
std::stack<bool> executableScope;
executableScope.push(false);
for (Token *tok = front(); tok; tok = tok->next) {
if (tok->op == '{') {
if (executableScope.top()) {
executableScope.push(true);
continue;
}
const Token *prev = tok->previous;
while (prev && prev->isOneOf(";{}()"))
prev = prev->previous;
executableScope.push(prev && prev->op == ')');
continue;
}
if (tok->op == '}') {
if (executableScope.size() > 1)
executableScope.pop();
continue;
}
if (tok->op == '.') {
// ellipsis ...
if (tok->next && tok->next->op == '.' && tok->next->location.col == (tok->location.col + 1) &&
tok->next->next && tok->next->next->op == '.' && tok->next->next->location.col == (tok->location.col + 2)) {
tok->setstr("...");
deleteToken(tok->next);
deleteToken(tok->next);
continue;
}
// float literals..
if (tok->previous && tok->previous->number && sameline(tok->previous, tok)) {
tok->setstr(tok->previous->str() + '.');
deleteToken(tok->previous);
if (sameline(tok, tok->next) && (isFloatSuffix(tok->next) || (tok->next && tok->next->startsWithOneOf("AaBbCcDdEeFfPp")))) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
if (tok->next && tok->next->number) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
// match: [0-9.]+E [+-] [0-9]+
const char lastChar = tok->str()[tok->str().size() - 1];
if (tok->number && !isOct(tok->str()) &&
((!isHex(tok->str()) && (lastChar == 'E' || lastChar == 'e')) ||
(isHex(tok->str()) && (lastChar == 'P' || lastChar == 'p'))) &&
tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
tok->setstr(tok->str() + tok->next->op + tok->next->next->str());
deleteToken(tok->next);
deleteToken(tok->next);
}
if (tok->op == '\0' || !tok->next || tok->next->op == '\0')
continue;
if (!sameline(tok,tok->next))
continue;
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->next->op == '=' && tok->isOneOf("=!<>+-*/%&|^")) {
if (tok->op == '&' && !executableScope.top()) {
// don't combine &= if it is a anonymous reference parameter with default value:
// void f(x&=2)
int indentlevel = 0;
const Token *start = tok;
while (indentlevel >= 0 && start) {
if (start->op == ')')
++indentlevel;
else if (start->op == '(')
--indentlevel;
else if (start->isOneOf(";{}"))
break;
start = start->previous;
}
if (indentlevel == -1 && start) {
const Token * const ftok = start;
bool isFuncDecl = ftok->name;
while (isFuncDecl) {
if (!start->name && start->str() != "::" && start->op != '*' && start->op != '&')
isFuncDecl = false;
if (!start->previous)
break;
if (start->previous->isOneOf(";{}:"))
break;
start = start->previous;
}
isFuncDecl &= start != ftok && start->name;
if (isFuncDecl) {
// TODO: we could loop through the parameters here and check if they are correct.
continue;
}
}
}
tok->setstr(tok->str() + "=");
deleteToken(tok->next);
} else if ((tok->op == '|' || tok->op == '&') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == ':' && tok->next->op == ':') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == '-' && tok->next->op == '>') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if ((tok->op == '<' || tok->op == '>') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
if (tok->next && tok->next->op == '=' && tok->next->next && tok->next->next->op != '=') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
} else if ((tok->op == '+' || tok->op == '-') && tok->op == tok->next->op) {
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->previous && tok->previous->number)
continue;
if (tok->next->next && tok->next->next->number)
continue;
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
}
static const std::string COMPL("compl");
static const std::string NOT("not");
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
// "not" might be !
if (isAlternativeUnaryOp(tok, NOT))
tok->op = '!';
// "compl" might be ~
else if (isAlternativeUnaryOp(tok, COMPL))
tok->op = '~';
if (tok->op == '!' && tok->next && tok->next->number) {
tok->setstr(tok->next->str() == "0" ? "1" : "0");
deleteToken(tok->next);
} else if (tok->op == '~' && tok->next && tok->next->number) {
tok->setstr(toString(~stringToLL(tok->next->str())));
deleteToken(tok->next);
} else {
if (tok->previous && (tok->previous->number || tok->previous->name))
continue;
if (!tok->next || !tok->next->number)
continue;
switch (tok->op) {
case '+':
tok->setstr(tok->next->str());
deleteToken(tok->next);
break;
case '-':
tok->setstr(tok->op + tok->next->str());
deleteToken(tok->next);
break;
}
}
}
}
void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '*')
result = (stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
else if (tok->op == '/' || tok->op == '%') {
const long long rhs = stringToLL(tok->next->str());
if (rhs == 0)
throw std::overflow_error("division/modulo by zero");
const long long lhs = stringToLL(tok->previous->str());
if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
throw std::overflow_error("division overflow");
if (tok->op == '/')
result = (lhs / rhs);
else
result = (lhs % rhs);
} else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldAddSub(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '+')
result = stringToLL(tok->previous->str()) + stringToLL(tok->next->str());
else if (tok->op == '-')
result = stringToLL(tok->previous->str()) - stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldShift(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->str() == "<<")
result = stringToLL(tok->previous->str()) << stringToLL(tok->next->str());
else if (tok->str() == ">>")
result = stringToLL(tok->previous->str()) >> stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string NOTEQ("not_eq");
void simplecpp::TokenList::constFoldComparison(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (isAlternativeBinaryOp(tok,NOTEQ))
tok->setstr("!=");
if (!tok->startsWithOneOf("<>=!"))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "==")
result = (stringToLL(tok->previous->str()) == stringToLL(tok->next->str()));
else if (tok->str() == "!=")
result = (stringToLL(tok->previous->str()) != stringToLL(tok->next->str()));
else if (tok->str() == ">")
result = (stringToLL(tok->previous->str()) > stringToLL(tok->next->str()));
else if (tok->str() == ">=")
result = (stringToLL(tok->previous->str()) >= stringToLL(tok->next->str()));
else if (tok->str() == "<")
result = (stringToLL(tok->previous->str()) < stringToLL(tok->next->str()));
else if (tok->str() == "<=")
result = (stringToLL(tok->previous->str()) <= stringToLL(tok->next->str()));
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string BITAND("bitand");
static const std::string BITOR("bitor");
static const std::string XOR("xor");
void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
const std::string* alternativeOp;
if (*op == '&')
alternativeOp = &BITAND;
else if (*op == '|')
alternativeOp = &BITOR;
else
alternativeOp = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (*op == '&')
result = (stringToLL(tok->previous->str()) & stringToLL(tok->next->str()));
else if (*op == '^')
result = (stringToLL(tok->previous->str()) ^ stringToLL(tok->next->str()));
else /*if (*op == '|')*/
result = (stringToLL(tok->previous->str()) | stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
}
static const std::string AND("and");
static const std::string OR("or");
void simplecpp::TokenList::constFoldLogicalOp(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (tok->name) {
if (isAlternativeBinaryOp(tok,AND))
tok->setstr("&&");
else if (isAlternativeBinaryOp(tok,OR))
tok->setstr("||");
}
if (tok->str() != "&&" && tok->str() != "||")
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "||")
result = (stringToLL(tok->previous->str()) || stringToLL(tok->next->str()));
else /*if (tok->str() == "&&")*/
result = (stringToLL(tok->previous->str()) && stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldQuestionOp(Token **tok1)
{
bool gotoTok1 = false;
for (Token *tok = *tok1; tok && tok->op != ')'; tok = gotoTok1 ? *tok1 : tok->next) {
gotoTok1 = false;
if (tok->str() != "?")
continue;
if (!tok->previous || !tok->next || !tok->next->next)
throw std::runtime_error("invalid expression");
if (!tok->previous->number)
continue;
if (tok->next->next->op != ':')
continue;
Token * const condTok = tok->previous;
Token * const trueTok = tok->next;
Token * const falseTok = trueTok->next->next;
if (!falseTok)
throw std::runtime_error("invalid expression");
if (condTok == *tok1)
*tok1 = (condTok->str() != "0" ? trueTok : falseTok);
deleteToken(condTok->next); // ?
deleteToken(trueTok->next); // :
deleteToken(condTok->str() == "0" ? trueTok : falseTok);
deleteToken(condTok);
gotoTok1 = true;
}
}
void simplecpp::TokenList::removeComments()
{
Token *tok = frontToken;
while (tok) {
Token * const tok1 = tok;
tok = tok->next;
if (tok1->comment)
deleteToken(tok1);
}
}
std::string simplecpp::TokenList::readUntil(Stream &stream, const Location &location, const char start, const char end, OutputList *outputList)
{
std::string ret;
ret += start;
bool backslash = false;
char ch = 0;
while (ch != end && ch != '\r' && ch != '\n' && stream.good()) {
ch = stream.readChar();
if (backslash && ch == '\n') {
ch = 0;
backslash = false;
continue;
}
backslash = false;
ret += ch;
if (ch == '\\') {
bool update_ch = false;
char next = 0;
do {
next = stream.readChar();
if (next == '\r' || next == '\n') {
ret.erase(ret.size()-1U);
backslash = (next == '\r');
update_ch = false;
} else if (next == '\\')
update_ch = !update_ch;
ret += next;
} while (next == '\\');
if (update_ch)
ch = next;
}
}
if (!stream.good() || ch != end) {
clear();
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = std::string("No pair for character (") + start + "). Can't process file. File is either invalid or unicode, which is currently not supported.";
outputList->push_back(err);
}
return "";
}
return ret;
}
std::string simplecpp::TokenList::lastLine(int maxsize) const
{
std::string ret;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback())) {
break;
}
if (tok->comment)
continue;
if (++count > maxsize)
return "";
if (!ret.empty())
ret += ' ';
// add tokens in reverse for performance reasons
if (tok->str()[0] == '\"')
ret += "%rts%"; // %str%
else if (tok->number)
ret += "%mun%"; // %num%
else {
ret += tok->str();
std::reverse(ret.end() - tok->str().length(), ret.end());
}
}
std::reverse(ret.begin(), ret.end());
return ret;
}
const simplecpp::Token* simplecpp::TokenList::lastLineTok(int maxsize) const
{
const Token* prevTok = nullptr;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback()))
break;
if (tok->comment)
continue;
if (++count > maxsize)
return nullptr;
prevTok = tok;
}
return prevTok;
}
bool simplecpp::TokenList::isLastLinePreprocessor(int maxsize) const
{
const Token * const prevTok = lastLineTok(maxsize);
return prevTok && prevTok->op == '#';
}
unsigned int simplecpp::TokenList::fileIndex(const std::string &filename)
{
for (unsigned int i = 0; i < files.size(); ++i) {
if (files[i] == filename)
return i;
}
files.push_back(filename);
return files.size() - 1U;
}
namespace simplecpp {
class Macro;
#if __cplusplus >= 201103L
using MacroMap = std::unordered_map<TokenString,Macro>;
#else
typedef std::map<TokenString,Macro> MacroMap;
#endif
class Macro {
public:
explicit Macro(std::vector<std::string> &f) : nameTokDef(nullptr), valueToken(nullptr), endToken(nullptr), files(f), tokenListDefine(f), variadic(false), valueDefinedInCode_(false) {}
Macro(const Token *tok, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(true) {
if (sameline(tok->previousSkipComments(), tok))
throw std::runtime_error("bad macro syntax");
if (tok->op != '#')
throw std::runtime_error("bad macro syntax");
const Token * const hashtok = tok;
tok = tok->next;
if (!tok || tok->str() != DEFINE)
throw std::runtime_error("bad macro syntax");
tok = tok->next;
if (!tok || !tok->name || !sameline(hashtok,tok))
throw std::runtime_error("bad macro syntax");
if (!parseDefine(tok))
throw std::runtime_error("bad macro syntax");
}
Macro(const std::string &name, const std::string &value, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(false) {
const std::string def(name + ' ' + value);
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(def.data()), def.size());
tokenListDefine.readfile(stream);
if (!parseDefine(tokenListDefine.cfront()))
throw std::runtime_error("bad macro syntax. macroname=" + name + " value=" + value);
}
Macro(const Macro &other) : nameTokDef(nullptr), files(other.files), tokenListDefine(other.files), valueDefinedInCode_(other.valueDefinedInCode_) {
*this = other;
}
Macro &operator=(const Macro &other) {
if (this != &other) {
files = other.files;
valueDefinedInCode_ = other.valueDefinedInCode_;
if (other.tokenListDefine.empty())
parseDefine(other.nameTokDef);
else {
tokenListDefine = other.tokenListDefine;
parseDefine(tokenListDefine.cfront());
}
usageList = other.usageList;
}
return *this;
}
bool valueDefinedInCode() const {
return valueDefinedInCode_;
}
/**
* Expand macro. This will recursively expand inner macros.
* @param output destination tokenlist
* @param rawtok macro token
* @param macros list of macros
* @param inputFiles the input files
* @return token after macro
* @throw Can throw wrongNumberOfParameters or invalidHashHash
*/
const Token * expand(TokenList * const output,
const Token * rawtok,
const MacroMap ¯os,
std::vector<std::string> &inputFiles) const {
std::set<TokenString> expandedmacros;
TokenList output2(inputFiles);
if (functionLike() && rawtok->next && rawtok->next->op == '(') {
// Copy macro call to a new tokenlist with no linebreaks
const Token * const rawtok1 = rawtok;
TokenList rawtokens2(inputFiles);
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location));
rawtok = rawtok->next;
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location));
rawtok = rawtok->next;
int par = 1;
while (rawtok && par > 0) {
if (rawtok->op == '(')
++par;
else if (rawtok->op == ')')
--par;
else if (rawtok->op == '#' && !sameline(rawtok->previous, rawtok))
throw Error(rawtok->location, "it is invalid to use a preprocessor directive as macro parameter");
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location));
rawtok = rawtok->next;
}
bool first = true;
if (valueToken && valueToken->str() == rawtok1->str())
first = false;
if (expand(&output2, rawtok1->location, rawtokens2.cfront(), macros, expandedmacros, first))
rawtok = rawtok1->next;
} else {
rawtok = expand(&output2, rawtok->location, rawtok, macros, expandedmacros);
}
while (output2.cback() && rawtok) {
unsigned int par = 0;
Token* macro2tok = output2.back();
while (macro2tok) {
if (macro2tok->op == '(') {
if (par==0)
break;
--par;
} else if (macro2tok->op == ')')
++par;
macro2tok = macro2tok->previous;
}
if (macro2tok) { // macro2tok->op == '('
macro2tok = macro2tok->previous;
expandedmacros.insert(name());
} else if (rawtok->op == '(')
macro2tok = output2.back();
if (!macro2tok || !macro2tok->name)
break;
if (output2.cfront() != output2.cback() && macro2tok->str() == this->name())
break;
const MacroMap::const_iterator macro = macros.find(macro2tok->str());
if (macro == macros.end() || !macro->second.functionLike())
break;
TokenList rawtokens2(inputFiles);
const Location loc(macro2tok->location);
while (macro2tok) {
Token * const next = macro2tok->next;
rawtokens2.push_back(new Token(macro2tok->str(), loc));
output2.deleteToken(macro2tok);
macro2tok = next;
}
par = (rawtokens2.cfront() != rawtokens2.cback()) ? 1U : 0U;
const Token *rawtok2 = rawtok;
for (; rawtok2; rawtok2 = rawtok2->next) {
rawtokens2.push_back(new Token(rawtok2->str(), loc));
if (rawtok2->op == '(')
++par;
else if (rawtok2->op == ')') {
if (par <= 1U)
break;
--par;
}
}
if (!rawtok2 || par != 1U)
break;
if (macro->second.expand(&output2, rawtok->location, rawtokens2.cfront(), macros, expandedmacros) != nullptr)
break;
rawtok = rawtok2->next;
}
output->takeTokens(output2);
for (Token* tok = output->front(); tok; tok = tok->next) {
if (tok->str() == INNER_COMMA)
tok->setstr(",");
}
return rawtok;
}
/** macro name */
const TokenString &name() const {
return nameTokDef->str();
}
/** location for macro definition */
const Location &defineLocation() const {
return nameTokDef->location;
}
/** how has this macro been used so far */
const std::list<Location> &usage() const {
return usageList;
}
/** is this a function like macro */
bool functionLike() const {
return nameTokDef->next &&
nameTokDef->next->op == '(' &&
sameline(nameTokDef, nameTokDef->next) &&
nameTokDef->next->location.col == nameTokDef->location.col + nameTokDef->str().size();
}
/** base class for errors */
struct Error {
Error(const Location &loc, const std::string &s) : location(loc), what(s) {}
const Location location;
const std::string what;
};
/** Struct that is thrown when macro is expanded with wrong number of parameters */
struct wrongNumberOfParameters : public Error {
wrongNumberOfParameters(const Location &loc, const std::string ¯oName) : Error(loc, "Wrong number of parameters for macro \'" + macroName + "\'.") {}
};
/** Struct that is thrown when there is invalid ## usage */
struct invalidHashHash : public Error {
static inline std::string format(const std::string ¯oName, const std::string &message) {
return "Invalid ## usage when expanding \'" + macroName + "\': " + message;
}
invalidHashHash(const Location &loc, const std::string ¯oName, const std::string &message)
: Error(loc, format(macroName, message)) { }
static inline invalidHashHash unexpectedToken(const Location &loc, const std::string ¯oName, const Token *tokenA) {
return invalidHashHash(loc, macroName, "Unexpected token '"+ tokenA->str()+"'");
}
static inline invalidHashHash cannotCombine(const Location &loc, const std::string ¯oName, const Token *tokenA, const Token *tokenB) {
return invalidHashHash(loc, macroName, "Combining '"+ tokenA->str()+ "' and '"+ tokenB->str() + "' yields an invalid token.");
}
static inline invalidHashHash unexpectedNewline(const Location &loc, const std::string ¯oName) {
return invalidHashHash(loc, macroName, "Unexpected newline");
}
static inline invalidHashHash universalCharacterUB(const Location &loc, const std::string ¯oName, const Token* tokenA, const std::string& strAB) {
return invalidHashHash(loc, macroName, "Combining '\\"+ tokenA->str()+ "' and '"+ strAB.substr(tokenA->str().size()) + "' yields universal character '\\" + strAB + "'. This is undefined behavior according to C standard chapter 5.1.1.2, paragraph 4.");
}
};
private:
/** Create new token where Token::macro is set for replaced tokens */
Token *newMacroToken(const TokenString &str, const Location &loc, bool replaced, const Token *expandedFromToken=nullptr) const {
Token *tok = new Token(str,loc);
if (replaced)
tok->macro = nameTokDef->str();
if (expandedFromToken)
tok->setExpandedFrom(expandedFromToken, this);
return tok;
}
bool parseDefine(const Token *nametoken) {
nameTokDef = nametoken;
variadic = false;
if (!nameTokDef) {
valueToken = endToken = nullptr;
args.clear();
return false;
}
// function like macro..
if (functionLike()) {
args.clear();
const Token *argtok = nameTokDef->next->next;
while (sameline(nametoken, argtok) && argtok->op != ')') {
if (argtok->str() == "..." &&
argtok->next && argtok->next->op == ')') {
variadic = true;
if (!argtok->previous->name)
args.push_back("__VA_ARGS__");
argtok = argtok->next; // goto ')'
break;
}
if (argtok->op != ',')
args.push_back(argtok->str());
argtok = argtok->next;
}
if (!sameline(nametoken, argtok)) {
endToken = argtok ? argtok->previous : argtok;
valueToken = nullptr;
return false;
}
valueToken = argtok ? argtok->next : nullptr;
} else {
args.clear();
valueToken = nameTokDef->next;
}
if (!sameline(valueToken, nameTokDef))
valueToken = nullptr;
endToken = valueToken;
while (sameline(endToken, nameTokDef))
endToken = endToken->next;
return true;
}
unsigned int getArgNum(const TokenString &str) const {
unsigned int par = 0;
while (par < args.size()) {
if (str == args[par])
return par;
par++;
}
return ~0U;
}
std::vector<const Token *> getMacroParameters(const Token *nameTokInst, bool calledInDefine) const {
if (!nameTokInst->next || nameTokInst->next->op != '(' || !functionLike())
return std::vector<const Token *>();
std::vector<const Token *> parametertokens;
parametertokens.push_back(nameTokInst->next);
unsigned int par = 0U;
for (const Token *tok = nameTokInst->next->next; calledInDefine ? sameline(tok, nameTokInst) : (tok != nullptr); tok = tok->next) {
if (tok->op == '(')
++par;
else if (tok->op == ')') {
if (par == 0U) {
parametertokens.push_back(tok);
break;
}
--par;
} else if (par == 0U && tok->op == ',' && (!variadic || parametertokens.size() < args.size()))
parametertokens.push_back(tok);
}
return parametertokens;
}
const Token *appendTokens(TokenList *tokens,
const Location &rawloc,
const Token * const lpar,
const MacroMap ¯os,
const std::set<TokenString> &expandedmacros,
const std::vector<const Token*> ¶metertokens) const {
if (!lpar || lpar->op != '(')
return nullptr;
unsigned int par = 0;
const Token *tok = lpar;
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
tok = expandHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else {
if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
bool expanded = false;
const MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
const Macro &m = it->second;
if (!m.functionLike()) {
Token* mtok = tokens->back();
m.expand(tokens, rawloc, tok, macros, expandedmacros);
for (mtok = mtok->next; mtok; mtok = mtok->next) {
if (mtok->op == ',')
mtok->setstr(INNER_COMMA);
}
expanded = true;
}
}
if (!expanded) {
tokens->push_back(new Token(*tok));
if (tok->macro.empty() && (par > 0 || tok->str() != "("))
tokens->back()->macro = name();
}
}
if (tok->op == '(')
++par;
else if (tok->op == ')') {
--par;
if (par == 0U)
break;
}
tok = tok->next;
}
}
for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next)
tok2->location = lpar->location;
return sameline(lpar,tok) ? tok : nullptr;
}
const Token * expand(TokenList * const output, const Location &loc, const Token * const nameTokInst, const MacroMap ¯os, std::set<TokenString> expandedmacros, bool first=false) const {
if (!first)
expandedmacros.insert(nameTokInst->str());
usageList.push_back(loc);
if (nameTokInst->str() == "__FILE__") {
output->push_back(new Token('\"'+loc.file()+'\"', loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__LINE__") {
output->push_back(new Token(toString(loc.line), loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__COUNTER__") {
output->push_back(new Token(toString(usageList.size()-1U), loc));
return nameTokInst->next;
}
const bool calledInDefine = (loc.fileIndex != nameTokInst->location.fileIndex ||
loc.line < nameTokInst->location.line);
std::vector<const Token*> parametertokens1(getMacroParameters(nameTokInst, calledInDefine));
if (functionLike()) {
// No arguments => not macro expansion
if (nameTokInst->next && nameTokInst->next->op != '(') {
output->push_back(new Token(nameTokInst->str(), loc));
return nameTokInst->next;
}
// Parse macro-call
if (variadic) {
if (parametertokens1.size() < args.size()) {
throw wrongNumberOfParameters(nameTokInst->location, name());
}
} else {
if (parametertokens1.size() != args.size() + (args.empty() ? 2U : 1U))
throw wrongNumberOfParameters(nameTokInst->location, name());
}
}
// If macro call uses __COUNTER__ then expand that first
TokenList tokensparams(files);
std::vector<const Token *> parametertokens2;
if (!parametertokens1.empty()) {
bool counter = false;
for (const Token *tok = parametertokens1[0]; tok != parametertokens1.back(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
counter = true;
break;
}
}
const MacroMap::const_iterator m = macros.find("__COUNTER__");
if (!counter || m == macros.end())
parametertokens2.swap(parametertokens1);
else {
const Macro &counterMacro = m->second;
unsigned int par = 0;
for (const Token *tok = parametertokens1[0]; tok && par < parametertokens1.size(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
tokensparams.push_back(new Token(toString(counterMacro.usageList.size()), tok->location));
counterMacro.usageList.push_back(tok->location);
} else {
tokensparams.push_back(new Token(*tok));
if (tok == parametertokens1[par]) {
parametertokens2.push_back(tokensparams.cback());
par++;
}
}
}
}
}
Token * const output_end_1 = output->back();
// expand
for (const Token *tok = valueToken; tok != endToken;) {
if (tok->op != '#') {
// A##B => AB
if (sameline(tok, tok->next) && tok->next && tok->next->op == '#' && tok->next->next && tok->next->next->op == '#') {
if (!sameline(tok, tok->next->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
TokenList new_output(files);
if (!expandArg(&new_output, tok, parametertokens2))
output->push_back(newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok));
else if (new_output.empty()) // placemarker token
output->push_back(newMacroToken("", loc, isReplaced(expandedmacros)));
else
for (const Token *tok2 = new_output.cfront(); tok2; tok2 = tok2->next)
output->push_back(newMacroToken(tok2->str(), loc, isReplaced(expandedmacros), tok2));
tok = tok->next;
} else {
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens2);
}
continue;
}
int numberOfHash = 1;
const Token *hashToken = tok->next;
while (sameline(tok,hashToken) && hashToken->op == '#') {
hashToken = hashToken->next;
++numberOfHash;
}
if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
output->push_back(new Token(*tok));
tok = tok->next;
continue;
}
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
break;
}
if (tok->op == '#') {
// A##B => AB
tok = expandHashHash(output, loc, tok->previous, macros, expandedmacros, parametertokens2);
} else {
// #123 => "123"
tok = expandHash(output, loc, tok->previous, macros, expandedmacros, parametertokens2);
}
}
if (!functionLike()) {
for (Token *tok = output_end_1 ? output_end_1->next : output->front(); tok; tok = tok->next) {
tok->macro = nameTokInst->str();
}
}
if (!parametertokens1.empty())
parametertokens1.swap(parametertokens2);
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
output->takeTokens(temp);
return tok->next;
}
if (!sameline(tok, tok->next)) {
output->takeTokens(temp);
return tok->next;
}
const MacroMap::const_iterator it = macros.find(temp.cback()->str());
if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
output->takeTokens(temp);
return tok->next;
}
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
output->takeTokens(temp);
return tok->next;
}
TokenList temp2(files);
temp2.push_back(new Token(temp.cback()->str(), tok->location));
const Token * const tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2)
return tok->next;
output->takeTokens(temp);
output->deleteToken(output->back());
calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
return tok2->next;
}
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
// Not name..
if (!tok->name) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
// Macro parameter..
{
TokenList temp(files);
if (tok->str() == "__VA_OPT__") {
if (sameline(tok, tok->next) && tok->next->str() == "(") {
tok = tok->next;
int paren = 1;
while (sameline(tok, tok->next)) {
if (tok->next->str() == "(")
++paren;
else if (tok->next->str() == ")")
--paren;
if (paren == 0)
return tok->next->next;
tok = tok->next;
if (parametertokens.size() > args.size() && parametertokens.front()->next->str() != ")")
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens)->previous;
}
}
throw Error(tok->location, "Missing parenthesis for __VA_OPT__(content)");
}
if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
if (tok->str() == "__VA_ARGS__" && temp.empty() && output->cback() && output->cback()->str() == "," &&
tok->nextSkipComments() && tok->nextSkipComments()->str() == ")")
output->deleteToken(output->back());
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
}
}
// Macro..
const MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
std::set<std::string> expandedmacros2(expandedmacros);
expandedmacros2.insert(tok->str());
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
TokenList temp(files);
calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
}
if (!sameline(tok, tok->next) || tok->next->op != '(') {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
const Token * const tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList temp(files);
calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros2, parametertokens);
}
if (tok->str() == DEFINED) {
const Token * const tok2 = tok->next;
const Token * const tok3 = tok2 ? tok2->next : nullptr;
const Token * const tok4 = tok3 ? tok3->next : nullptr;
const Token *defToken = nullptr;
const Token *lastToken = nullptr;
if (sameline(tok, tok4) && tok2->op == '(' && tok3->name && tok4->op == ')') {
defToken = tok3;
lastToken = tok4;
} else if (sameline(tok,tok2) && tok2->name) {
defToken = lastToken = tok2;
}
if (defToken) {
std::string macroName = defToken->str();
if (defToken->next && defToken->next->op == '#' && defToken->next->next && defToken->next->next->op == '#' && defToken->next->next->next && defToken->next->next->next->name && sameline(defToken,defToken->next->next->next)) {
TokenList temp(files);
if (expandArg(&temp, defToken, parametertokens))
macroName = temp.cback()->str();
if (expandArg(&temp, defToken->next->next->next, parametertokens))
macroName += temp.cback()->str();
else
macroName += defToken->next->next->next->str();
lastToken = defToken->next->next->next;
}
const bool def = (macros.find(macroName) != macros.end());
output->push_back(newMacroToken(def ? "1" : "0", loc, true));
return lastToken->next;
}
}
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
bool expandArg(TokenList *output, const Token *tok, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
// empty variadic parameter
if (variadic && argnr + 1U >= parametertokens.size())
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U]; partok = partok->next)
output->push_back(new Token(*partok));
return true;
}
bool expandArg(TokenList *output, const Token *tok, const Location &loc, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
if (variadic && argnr + 1U >= parametertokens.size()) // empty variadic parameter
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U];) {
const MacroMap::const_iterator it = macros.find(partok->str());
if (it != macros.end() && !partok->isExpandedFrom(&it->second) && (partok->str() == name() || expandedmacros.find(partok->str()) == expandedmacros.end()))
partok = it->second.expand(output, loc, partok, macros, expandedmacros);
else {
output->push_back(newMacroToken(partok->str(), loc, isReplaced(expandedmacros), partok));
output->back()->macro = partok->macro;
partok = partok->next;
}
}
return true;
}
/**
* Expand #X => "X"
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok The # token
* @param macros all macros
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @return token after the X
*/
const Token *expandHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
TokenList tokenListHash(files);
tok = expandToken(&tokenListHash, loc, tok->next, macros, expandedmacros, parametertokens);
std::ostringstream ostr;
ostr << '\"';
for (const Token *hashtok = tokenListHash.cfront(); hashtok; hashtok = hashtok->next)
ostr << hashtok->str();
ostr << '\"';
output->push_back(newMacroToken(escapeString(ostr.str()), loc, isReplaced(expandedmacros)));
return tok;
}
/**
* Expand A##B => AB
* The A should already be expanded. Call this when you reach the first # token
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok first # token
* @param macros all macros
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @return token after B
*/
const Token *expandHashHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
Token *A = output->back();
if (!A)
throw invalidHashHash(tok->location, name(), "Missing first argument");
if (!sameline(tok, tok->next) || !sameline(tok, tok->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
const bool canBeConcatenatedWithEqual = A->isOneOf("+-*/%&|^") || A->str() == "<<" || A->str() == ">>";
const bool canBeConcatenatedStringOrChar = isStringLiteral_(A->str()) || isCharLiteral_(A->str());
if (!A->name && !A->number && A->op != ',' && !A->str().empty() && !canBeConcatenatedWithEqual && !canBeConcatenatedStringOrChar)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
Token * const B = tok->next->next;
if (!B->name && !B->number && B->op && !B->isOneOf("#="))
throw invalidHashHash::unexpectedToken(tok->location, name(), B);
if ((canBeConcatenatedWithEqual && B->op != '=') ||
(!canBeConcatenatedWithEqual && B->op == '='))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
// Superficial check; more in-depth would in theory be possible _after_ expandArg
if (canBeConcatenatedStringOrChar && (B->number || !B->name))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
TokenList tokensB(files);
const Token *nextTok = B->next;
if (canBeConcatenatedStringOrChar) {
// It seems clearer to handle this case separately even though the code is similar-ish, but we don't want to merge here.
// TODO The question is whether the ## or varargs may still apply, and how to provoke?
if (expandArg(&tokensB, B, parametertokens)) {
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
} else {
tokensB.push_back(new Token(*B));
tokensB.back()->location = loc;
}
output->takeTokens(tokensB);
} else {
std::string strAB;
const bool varargs = variadic && !args.empty() && B->str() == args[args.size()-1U];
if (expandArg(&tokensB, B, parametertokens)) {
if (tokensB.empty())
strAB = A->str();
else if (varargs && A->op == ',') {
strAB = ",";
} else {
strAB = A->str() + tokensB.cfront()->str();
tokensB.deleteToken(tokensB.front());
}
} else {
strAB = A->str() + B->str();
}
// producing universal character is undefined behavior
if (A->previous && A->previous->str() == "\\") {
if (strAB[0] == 'u' && strAB.size() == 5)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
if (strAB[0] == 'U' && strAB.size() == 9)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
}
if (varargs && tokensB.empty() && tok->previous->str() == ",")
output->deleteToken(A);
else if (strAB != "," && macros.find(strAB) == macros.end()) {
A->setstr(strAB);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} else if (sameline(B, nextTok) && sameline(B, nextTok->next) && nextTok->op == '#' && nextTok->next->op == '#') {
TokenList output2(files);
output2.push_back(new Token(strAB, tok->location));
nextTok = expandHashHash(&output2, loc, nextTok, macros, expandedmacros, parametertokens);
output->deleteToken(A);
output->takeTokens(output2);
} else {
output->deleteToken(A);
TokenList tokens(files);
tokens.push_back(new Token(strAB, tok->location));
// for function like macros, push the (...)
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const MacroMap::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
const Token * const tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
}
expandToken(output, loc, tokens.cfront(), macros, expandedmacros, parametertokens);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
}
}
return nextTok;
}
static bool isReplaced(const std::set<std::string> &expandedmacros) {
// return true if size > 1
std::set<std::string>::const_iterator it = expandedmacros.begin();
if (it == expandedmacros.end())
return false;
++it;
return (it != expandedmacros.end());
}
/** name token in definition */
const Token *nameTokDef;
/** arguments for macro */
std::vector<TokenString> args;
/** first token in replacement string */
const Token *valueToken;
/** token after replacement string */
const Token *endToken;
/** files */
std::vector<std::string> &files;
/** this is used for -D where the definition is not seen anywhere in code */
TokenList tokenListDefine;
/** usage of this macro */
mutable std::list<Location> usageList;
/** is macro variadic? */
bool variadic;
/** was the value of this macro actually defined in the code? */
bool valueDefinedInCode_;
};
}
namespace simplecpp {
#ifdef __CYGWIN__
bool startsWith(const std::string &str, const std::string &s)
{
return (str.size() >= s.size() && str.compare(0, s.size(), s) == 0);
}
std::string convertCygwinToWindowsPath(const std::string &cygwinPath)
{
std::string windowsPath;
std::string::size_type pos = 0;
if (cygwinPath.size() >= 11 && startsWith(cygwinPath, "/cygdrive/")) {
const unsigned char driveLetter = cygwinPath[10];
if (std::isalpha(driveLetter)) {
if (cygwinPath.size() == 11) {
windowsPath = toupper(driveLetter);
windowsPath += ":\\"; // volume root directory
pos = 11;
} else if (cygwinPath[11] == '/') {
windowsPath = toupper(driveLetter);
windowsPath += ":";
pos = 11;
}
}
}
for (; pos < cygwinPath.size(); ++pos) {
unsigned char c = cygwinPath[pos];
if (c == '/')
c = '\\';
windowsPath += c;
}
return windowsPath;
}
#endif
}
#ifdef SIMPLECPP_WINDOWS
#if __cplusplus >= 201103L
using MyMutex = std::mutex;
template<class T>
using MyLock = std::lock_guard<T>;
#else
class MyMutex {
public:
MyMutex() {
InitializeCriticalSection(&m_criticalSection);
}
~MyMutex() {
DeleteCriticalSection(&m_criticalSection);
}
CRITICAL_SECTION* lock() {
return &m_criticalSection;
}
private:
CRITICAL_SECTION m_criticalSection;
};
template<typename T>
class MyLock {
public:
explicit MyLock(T& m)
: m_mutex(m) {
EnterCriticalSection(m_mutex.lock());
}
~MyLock() {
LeaveCriticalSection(m_mutex.lock());
}
private:
MyLock& operator=(const MyLock&);
MyLock(const MyLock&);
T& m_mutex;
};
#endif
class RealFileNameMap {
public:
RealFileNameMap() {}
bool getCacheEntry(const std::string& path, std::string& returnPath) {
MyLock<MyMutex> lock(m_mutex);
const std::map<std::string, std::string>::iterator it = m_fileMap.find(path);
if (it != m_fileMap.end()) {
returnPath = it->second;
return true;
}
return false;
}
void addToCache(const std::string& path, const std::string& actualPath) {
MyLock<MyMutex> lock(m_mutex);
m_fileMap[path] = actualPath;
}
private:
std::map<std::string, std::string> m_fileMap;
MyMutex m_mutex;
};
static RealFileNameMap realFileNameMap;
static bool realFileName(const std::string &f, std::string &result)
{
// are there alpha characters in last subpath?
bool alpha = false;
for (std::string::size_type pos = 1; pos <= f.size(); ++pos) {
const unsigned char c = f[f.size() - pos];
if (c == '/' || c == '\\')
break;
if (std::isalpha(c)) {
alpha = true;
break;
}
}
// do not convert this path if there are no alpha characters (either pointless or cause wrong results for . and ..)
if (!alpha)
return false;
// Lookup filename or foldername on file system
if (!realFileNameMap.getCacheEntry(f, result)) {
WIN32_FIND_DATAA FindFileData;
#ifdef __CYGWIN__
const std::string fConverted = simplecpp::convertCygwinToWindowsPath(f);
const HANDLE hFind = FindFirstFileExA(fConverted.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#else
HANDLE hFind = FindFirstFileExA(f.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#endif
if (INVALID_HANDLE_VALUE == hFind)
return false;
result = FindFileData.cFileName;
realFileNameMap.addToCache(f, result);
FindClose(hFind);
}
return true;
}
static RealFileNameMap realFilePathMap;
/** Change case in given path to match filesystem */
static std::string realFilename(const std::string &f)
{
std::string ret;
ret.reserve(f.size()); // this will be the final size
if (realFilePathMap.getCacheEntry(f, ret))
return ret;
// Current subpath
std::string subpath;
for (std::string::size_type pos = 0; pos < f.size(); ++pos) {
const unsigned char c = f[pos];
// Separator.. add subpath and separator
if (c == '/' || c == '\\') {
// if subpath is empty just add separator
if (subpath.empty()) {
ret += c;
continue;
}
const bool isDriveSpecification =
(pos == 2 && subpath.size() == 2 && std::isalpha(subpath[0]) && subpath[1] == ':');
// Append real filename (proper case)
std::string f2;
if (!isDriveSpecification && realFileName(f.substr(0, pos), f2))
ret += f2;
else
ret += subpath;
subpath.clear();
// Append separator
ret += c;
} else {
subpath += c;
}
}
if (!subpath.empty()) {
std::string f2;
if (realFileName(f,f2))
ret += f2;
else
ret += subpath;
}
realFilePathMap.addToCache(f, ret);
return ret;
}
static bool isAbsolutePath(const std::string &path)
{
if (path.length() >= 3 && path[0] > 0 && std::isalpha(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
return true;
return path.length() > 1U && (path[0] == '/' || path[0] == '\\');
}
#else
#define realFilename(f) f
static bool isAbsolutePath(const std::string &path)
{
return path.length() > 1U && path[0] == '/';
}
#endif
namespace simplecpp {
/**
* perform path simplifications for . and ..
*/
std::string simplifyPath(std::string path)
{
if (path.empty())
return path;
std::string::size_type pos;
// replace backslash separators
std::replace(path.begin(), path.end(), '\\', '/');
const bool unc(path.compare(0,2,"//") == 0);
// replace "//" with "/"
pos = 0;
while ((pos = path.find("//",pos)) != std::string::npos) {
path.erase(pos,1);
}
// remove "./"
pos = 0;
while ((pos = path.find("./",pos)) != std::string::npos) {
if (pos == 0 || path[pos - 1U] == '/')
path.erase(pos,2);
else
pos += 2;
}
// remove trailing dot if path ends with "/."
if (endsWith(path,"/."))
path.erase(path.size()-1);
// simplify ".."
pos = 1; // don't simplify ".." if path starts with that
while ((pos = path.find("/..", pos)) != std::string::npos) {
// not end of path, then string must be "/../"
if (pos + 3 < path.size() && path[pos + 3] != '/') {
++pos;
continue;
}
// get previous subpath
std::string::size_type pos1 = path.rfind('/', pos - 1U);
if (pos1 == std::string::npos) {
pos1 = 0;
} else {
pos1 += 1U;
}
const std::string previousSubPath = path.substr(pos1, pos - pos1);
if (previousSubPath == "..") {
// don't simplify
++pos;
} else {
// remove previous subpath and ".."
path.erase(pos1, pos - pos1 + 4);
if (path.empty())
path = ".";
// update pos
pos = (pos1 == 0) ? 1 : (pos1 - 1);
}
}
// Remove trailing '/'?
//if (path.size() > 1 && endsWith(path, "/"))
// path.erase(path.size()-1);
if (unc)
path = '/' + path;
// cppcheck-suppress duplicateExpressionTernary - platform-dependent implementation
return strpbrk(path.c_str(), "*?") == nullptr ? realFilename(path) : path;
}
}
/** Evaluate sizeof(type) */
static void simplifySizeof(simplecpp::TokenList &expr, const std::map<std::string, std::size_t> &sizeOfType)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != "sizeof")
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing sizeof argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing sizeof argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid sizeof expression");
}
}
}
std::string type;
for (simplecpp::Token *typeToken = tok1; typeToken != tok2; typeToken = typeToken->next) {
if ((typeToken->str() == "unsigned" || typeToken->str() == "signed") && typeToken->next->name)
continue;
if (typeToken->str() == "*" && type.find('*') != std::string::npos)
continue;
if (!type.empty())
type += ' ';
type += typeToken->str();
}
const std::map<std::string, std::size_t>::const_iterator it = sizeOfType.find(type);
if (it != sizeOfType.end())
tok->setstr(toString(it->second));
else
continue;
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
/** Evaluate __has_include(file) */
static bool isCpp17OrLater(const simplecpp::DUI &dui)
{
const std::string std_ver = simplecpp::getCppStdString(dui.std);
return !std_ver.empty() && (std_ver >= "201703L");
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader);
static void simplifyHasInclude(simplecpp::TokenList &expr, const simplecpp::DUI &dui)
{
if (!isCpp17OrLater(dui))
return;
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != HAS_INCLUDE)
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing __has_include argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing __has_include argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid __has_include expression");
}
}
}
const std::string &sourcefile = tok->location.file();
const bool systemheader = (tok1 && tok1->op == '<');
std::string header;
if (systemheader) {
simplecpp::Token *tok3 = tok1->next;
if (!tok3) {
throw std::runtime_error("missing __has_include closing angular bracket");
}
while (tok3->op != '>') {
tok3 = tok3->next;
if (!tok3) {
throw std::runtime_error("invalid __has_include expression");
}
}
for (simplecpp::Token *headerToken = tok1->next; headerToken != tok3; headerToken = headerToken->next)
header += headerToken->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
}
else {
header = realFilename(tok1->str().substr(1U, tok1->str().size() - 2U));
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
tok->setstr(header2.empty() ? "0" : "1");
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
static const char * const altopData[] = {"and","or","bitand","bitor","compl","not","not_eq","xor"};
static const std::set<std::string> altop(&altopData[0], &altopData[8]);
static void simplifyName(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->name) {
if (altop.find(tok->str()) != altop.end()) {
bool alt;
if (tok->str() == "not" || tok->str() == "compl") {
alt = isAlternativeUnaryOp(tok,tok->str());
} else {
alt = isAlternativeBinaryOp(tok,tok->str());
}
if (alt)
continue;
}
tok->setstr("0");
}
}
}
/*
* Reads at least minlen and at most maxlen digits (inc. prefix) in base base
* from s starting at position pos and converts them to a
* unsigned long long value, updating pos to point to the first
* unused element of s.
* Returns ULLONG_MAX if the result is not representable and
* throws if the above requirements were not possible to satisfy.
*/
static unsigned long long stringToULLbounded(
const std::string& s,
std::size_t& pos,
int base = 0,
std::ptrdiff_t minlen = 1,
std::size_t maxlen = std::string::npos
)
{
const std::string sub = s.substr(pos, maxlen);
const char * const start = sub.c_str();
char* end;
const unsigned long long value = std::strtoull(start, &end, base);
pos += end - start;
if (end - start < minlen)
throw std::runtime_error("expected digit");
return value;
}
/* Converts character literal (including prefix, but not ud-suffix)
* to long long value.
*
* Assumes ASCII-compatible single-byte encoded str for narrow literals
* and UTF-8 otherwise.
*
* For target assumes
* - execution character set encoding matching str
* - UTF-32 execution wide-character set encoding
* - requirements for __STDC_UTF_16__, __STDC_UTF_32__ and __STDC_ISO_10646__ satisfied
* - char16_t is 16bit wide
* - char32_t is 32bit wide
* - wchar_t is 32bit wide and unsigned
* - matching char signedness to host
* - matching sizeof(int) to host
*
* For host assumes
* - ASCII-compatible execution character set
*
* For host and target assumes
* - CHAR_BIT == 8
* - two's complement
*
* Implements multi-character narrow literals according to GCC's behavior,
* except multi code unit universal character names are not supported.
* Multi-character wide literals are not supported.
* Limited support of universal character names for non-UTF-8 execution character set encodings.
*/
long long simplecpp::characterLiteralToLL(const std::string& str)
{
// default is wide/utf32
bool narrow = false;
bool utf8 = false;
bool utf16 = false;
std::size_t pos;
if (!str.empty() && str[0] == '\'') {
narrow = true;
pos = 1;
} else if (str.size() >= 2 && str[0] == 'u' && str[1] == '\'') {
utf16 = true;
pos = 2;
} else if (str.size() >= 3 && str[0] == 'u' && str[1] == '8' && str[2] == '\'') {
utf8 = true;
pos = 3;
} else if (str.size() >= 2 && (str[0] == 'L' || str[0] == 'U') && str[1] == '\'') {
pos = 2;
} else
throw std::runtime_error("expected a character literal");
unsigned long long multivalue = 0;
std::size_t nbytes = 0;
while (pos + 1 < str.size()) {
if (str[pos] == '\'' || str[pos] == '\n')
throw std::runtime_error("raw single quotes and newlines not allowed in character literals");
if (nbytes >= 1 && !narrow)
throw std::runtime_error("multiple characters only supported in narrow character literals");
unsigned long long value;
if (str[pos] == '\\') {
pos++;
const char escape = str[pos++];
if (pos >= str.size())
throw std::runtime_error("unexpected end of character literal");
switch (escape) {
// obscure GCC extensions
case '%':
case '(':
case '[':
case '{':
// standard escape sequences
case '\'':
case '"':
case '?':
case '\\':
value = static_cast<unsigned char>(escape);
break;
case 'a':
value = static_cast<unsigned char>('\a');
break;
case 'b':
value = static_cast<unsigned char>('\b');
break;
case 'f':
value = static_cast<unsigned char>('\f');
break;
case 'n':
value = static_cast<unsigned char>('\n');
break;
case 'r':
value = static_cast<unsigned char>('\r');
break;
case 't':
value = static_cast<unsigned char>('\t');
break;
case 'v':
value = static_cast<unsigned char>('\v');
break;
// GCC extension for ESC character
case 'e':
case 'E':
value = static_cast<unsigned char>('\x1b');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
// octal escape sequences consist of 1 to 3 digits
value = stringToULLbounded(str, --pos, 8, 1, 3);
break;
case 'x':
// hexadecimal escape sequences consist of at least 1 digit
value = stringToULLbounded(str, pos, 16);
break;
case 'u':
case 'U': {
// universal character names have exactly 4 or 8 digits
const std::size_t ndigits = (escape == 'u' ? 4 : 8);
value = stringToULLbounded(str, pos, 16, ndigits, ndigits);
// UTF-8 encodes code points above 0x7f in multiple code units
// code points above 0x10ffff are not allowed
if (((narrow || utf8) && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("surrogate code points not allowed in universal character names");
break;
}
default:
throw std::runtime_error("invalid escape sequence");
}
} else {
value = static_cast<unsigned char>(str[pos++]);
if (!narrow && value >= 0x80) {
// Assuming this is a UTF-8 encoded code point.
// This decoder may not completely validate the input.
// Noncharacters are neither rejected nor replaced.
int additional_bytes;
if (value >= 0xf5) // higher values would result in code points above 0x10ffff
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if (value >= 0xf0)
additional_bytes = 3;
else if (value >= 0xe0)
additional_bytes = 2;
else if (value >= 0xc2) // 0xc0 and 0xc1 are always overlong 2-bytes encodings
additional_bytes = 1;
else
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value &= (1 << (6 - additional_bytes)) - 1;
while (additional_bytes--) {
if (pos + 1 >= str.size())
throw std::runtime_error("assumed UTF-8 encoded source, but character literal ends unexpectedly");
const unsigned char c = str[pos++];
if (((c >> 6) != 2) // ensure c has form 0xb10xxxxxx
|| (!value && additional_bytes == 1 && c < 0xa0) // overlong 3-bytes encoding
|| (!value && additional_bytes == 2 && c < 0x90)) // overlong 4-bytes encoding
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value = (value << 6) | (c & ((1 << 7) - 1));
}
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if ((utf8 && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
}
}
if (((narrow || utf8) && value > std::numeric_limits<unsigned char>::max()) || (utf16 && value >> 16) || value >> 32)
throw std::runtime_error("numeric escape sequence too large");
multivalue <<= CHAR_BIT;
multivalue |= value;
nbytes++;
}
if (pos + 1 != str.size() || str[pos] != '\'')
throw std::runtime_error("missing closing quote in character literal");
if (!nbytes)
throw std::runtime_error("empty character literal");
// ordinary narrow character literal's value is determined by (possibly signed) char
if (narrow && nbytes == 1)
return static_cast<char>(multivalue);
// while multi-character literal's value is determined by (signed) int
if (narrow)
return static_cast<int>(multivalue);
// All other cases are unsigned. Since long long is at least 64bit wide,
// while the literals at most 32bit wide, the conversion preserves all values.
return multivalue;
}
static void simplifyNumbers(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str().size() == 1U)
continue;
if (tok->str().compare(0,2,"0x") == 0)
tok->setstr(toString(stringToULL(tok->str())));
else if (!tok->number && tok->str().find('\'') != std::string::npos)
tok->setstr(toString(simplecpp::characterLiteralToLL(tok->str())));
}
}
static void simplifyComments(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok;) {
simplecpp::Token * const d = tok;
tok = tok->next;
if (d->comment)
expr.deleteToken(d);
}
}
static long long evaluate(simplecpp::TokenList &expr, const simplecpp::DUI &dui, const std::map<std::string, std::size_t> &sizeOfType)
{
simplifyComments(expr);
simplifySizeof(expr, sizeOfType);
simplifyHasInclude(expr, dui);
simplifyName(expr);
simplifyNumbers(expr);
expr.constFold();
// TODO: handle invalid expressions
return expr.cfront() && expr.cfront() == expr.cback() && expr.cfront()->number ? stringToLL(expr.cfront()->str()) : 0LL;
}
static const simplecpp::Token *gotoNextLine(const simplecpp::Token *tok)
{
const unsigned int line = tok->location.line;
const unsigned int file = tok->location.fileIndex;
while (tok && tok->location.line == line && tok->location.fileIndex == file)
tok = tok->next;
return tok;
}
#ifdef SIMPLECPP_WINDOWS
class NonExistingFilesCache {
public:
NonExistingFilesCache() {}
bool contains(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
return (m_pathSet.find(path) != m_pathSet.end());
}
void add(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.insert(path);
}
void clear() {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.clear();
}
private:
std::set<std::string> m_pathSet;
MyMutex m_mutex;
};
static NonExistingFilesCache nonExistingFilesCache;
#endif
static std::string openHeader(std::ifstream &f, const std::string &path)
{
std::string simplePath = simplecpp::simplifyPath(path);
#ifdef SIMPLECPP_WINDOWS
if (nonExistingFilesCache.contains(simplePath))
return ""; // file is known not to exist, skip expensive file open call
#endif
f.open(simplePath.c_str());
if (f.is_open())
return simplePath;
#ifdef SIMPLECPP_WINDOWS
nonExistingFilesCache.add(simplePath);
#endif
return "";
}
static std::string getRelativeFileName(const std::string &sourcefile, const std::string &header)
{
if (sourcefile.find_first_of("\\/") != std::string::npos)
return simplecpp::simplifyPath(sourcefile.substr(0, sourcefile.find_last_of("\\/") + 1U) + header);
return simplecpp::simplifyPath(header);
}
static std::string openHeaderRelative(std::ifstream &f, const std::string &sourcefile, const std::string &header)
{
return openHeader(f, getRelativeFileName(sourcefile, header));
}
static std::string getIncludePathFileName(const std::string &includePath, const std::string &header)
{
std::string path = includePath;
if (!path.empty() && path[path.size()-1U]!='/' && path[path.size()-1U]!='\\')
path += '/';
return path + header;
}
static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI &dui, const std::string &header)
{
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string simplePath = openHeader(f, getIncludePathFileName(*it, header));
if (!simplePath.empty())
return simplePath;
}
return "";
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader)
{
if (isAbsolutePath(header))
return openHeader(f, header);
std::string ret;
if (systemheader) {
ret = openHeaderIncludePath(f, dui, header);
return ret;
}
ret = openHeaderRelative(f, sourcefile, header);
if (ret.empty())
return openHeaderIncludePath(f, dui, header);
return ret;
}
static std::string getFileName(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
if (filedata.empty()) {
return "";
}
if (isAbsolutePath(header)) {
return (filedata.find(header) != filedata.end()) ? simplecpp::simplifyPath(header) : "";
}
if (!systemheader) {
const std::string relativeFilename = getRelativeFileName(sourcefile, header);
if (filedata.find(relativeFilename) != filedata.end())
return relativeFilename;
}
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string s = simplecpp::simplifyPath(getIncludePathFileName(*it, header));
if (filedata.find(s) != filedata.end())
return s;
}
if (systemheader && filedata.find(header) != filedata.end())
return header;
return "";
}
static bool hasFile(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
return !getFileName(filedata, sourcefile, header, dui, systemheader).empty();
}
std::map<std::string, simplecpp::TokenList*> simplecpp::load(const simplecpp::TokenList &rawtokens, std::vector<std::string> &filenames, const simplecpp::DUI &dui, simplecpp::OutputList *outputList)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, simplecpp::TokenList*> ret;
std::list<const Token *> filelist;
// -include files
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::string &filename = realFilename(*it);
if (ret.find(filename) != ret.end())
continue;
std::ifstream fin(filename.c_str());
if (!fin.is_open()) {
if (outputList) {
simplecpp::Output err(filenames);
err.type = simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND;
err.location = Location(filenames);
err.msg = "Can not open include file '" + filename + "' that is explicitly included.";
outputList->push_back(err);
}
continue;
}
fin.close();
TokenList *tokenlist = new TokenList(filename, filenames, outputList);
if (!tokenlist->front()) {
delete tokenlist;
continue;
}
if (dui.removeComments)
tokenlist->removeComments();
ret[filename] = tokenlist;
filelist.push_back(tokenlist->front());
}
for (const Token *rawtok = rawtokens.cfront(); rawtok || !filelist.empty(); rawtok = rawtok ? rawtok->next : nullptr) {
if (rawtok == nullptr) {
rawtok = filelist.back();
filelist.pop_back();
}
if (rawtok->op != '#' || sameline(rawtok->previousSkipComments(), rawtok))
continue;
rawtok = rawtok->nextSkipComments();
if (!rawtok || rawtok->str() != INCLUDE)
continue;
const std::string &sourcefile = rawtok->location.file();
const Token * const htok = rawtok->nextSkipComments();
if (!sameline(rawtok, htok))
continue;
const bool systemheader = (htok->str()[0] == '<');
const std::string header(realFilename(htok->str().substr(1U, htok->str().size() - 2U)));
if (hasFile(ret, sourcefile, header, dui, systemheader))
continue;
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
if (!f.is_open())
continue;
f.close();
TokenList *tokens = new TokenList(header2, filenames, outputList);
if (dui.removeComments)
tokens->removeComments();
ret[header2] = tokens;
if (tokens->front())
filelist.push_back(tokens->front());
}
return ret;
}
static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token **tok1, simplecpp::MacroMap ¯os, std::vector<std::string> &files, simplecpp::OutputList *outputList)
{
const simplecpp::Token * const tok = *tok1;
const simplecpp::MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end()) {
simplecpp::TokenList value(files);
try {
*tok1 = it->second.expand(&value, tok, macros, files);
} catch (simplecpp::Macro::Error &err) {
if (outputList) {
simplecpp::Output out(files);
out.type = simplecpp::Output::SYNTAX_ERROR;
out.location = err.location;
out.msg = "failed to expand \'" + tok->str() + "\', " + err.what;
outputList->push_back(out);
}
return false;
}
output.takeTokens(value);
} else {
if (!tok->comment)
output.push_back(new simplecpp::Token(*tok));
*tok1 = tok->next;
}
return true;
}
static void getLocaltime(struct tm <ime)
{
time_t t;
time(&t);
#ifndef _WIN32
// NOLINTNEXTLINE(misc-include-cleaner) - false positive
localtime_r(&t, <ime);
#else
localtime_s(<ime, &t);
#endif
}
static std::string getDateDefine(const struct tm *timep)
{
char buf[] = "??? ?? ????";
strftime(buf, sizeof(buf), "%b %d %Y", timep);
return std::string("\"").append(buf).append("\"");
}
static std::string getTimeDefine(const struct tm *timep)
{
char buf[] = "??:??:??";
strftime(buf, sizeof(buf), "%T", timep);
return std::string("\"").append(buf).append("\"");
}
void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, simplecpp::TokenList *> &filedata, const simplecpp::DUI &dui, simplecpp::OutputList *outputList, std::list<simplecpp::MacroUsage> *macroUsage, std::list<simplecpp::IfCond> *ifCond)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, std::size_t> sizeOfType(rawtokens.sizeOfType);
sizeOfType.insert(std::make_pair("char", sizeof(char)));
sizeOfType.insert(std::make_pair("short", sizeof(short)));
sizeOfType.insert(std::make_pair("short int", sizeOfType["short"]));
sizeOfType.insert(std::make_pair("int", sizeof(int)));
sizeOfType.insert(std::make_pair("long", sizeof(long)));
sizeOfType.insert(std::make_pair("long int", sizeOfType["long"]));
sizeOfType.insert(std::make_pair("long long", sizeof(long long)));
sizeOfType.insert(std::make_pair("float", sizeof(float)));
sizeOfType.insert(std::make_pair("double", sizeof(double)));
sizeOfType.insert(std::make_pair("long double", sizeof(long double)));
sizeOfType.insert(std::make_pair("char *", sizeof(char *)));
sizeOfType.insert(std::make_pair("short *", sizeof(short *)));
sizeOfType.insert(std::make_pair("short int *", sizeOfType["short *"]));
sizeOfType.insert(std::make_pair("int *", sizeof(int *)));
sizeOfType.insert(std::make_pair("long *", sizeof(long *)));
sizeOfType.insert(std::make_pair("long int *", sizeOfType["long *"]));
sizeOfType.insert(std::make_pair("long long *", sizeof(long long *)));
sizeOfType.insert(std::make_pair("float *", sizeof(float *)));
sizeOfType.insert(std::make_pair("double *", sizeof(double *)));
sizeOfType.insert(std::make_pair("long double *", sizeof(long double *)));
// use a dummy vector for the macros because as this is not part of the file and would add an empty entry - e.g. /usr/include/poll.h
std::vector<std::string> dummy;
const bool hasInclude = isCpp17OrLater(dui);
MacroMap macros;
for (std::list<std::string>::const_iterator it = dui.defines.begin(); it != dui.defines.end(); ++it) {
const std::string ¯ostr = *it;
const std::string::size_type eq = macrostr.find('=');
const std::string::size_type par = macrostr.find('(');
const std::string macroname = macrostr.substr(0, std::min(eq,par));
if (dui.undefined.find(macroname) != dui.undefined.end())
continue;
const std::string lhs(macrostr.substr(0,eq));
const std::string rhs(eq==std::string::npos ? std::string("1") : macrostr.substr(eq+1));
const Macro macro(lhs, rhs, dummy);
macros.insert(std::pair<TokenString,Macro>(macro.name(), macro));
}
macros.insert(std::make_pair("__FILE__", Macro("__FILE__", "__FILE__", dummy)));
macros.insert(std::make_pair("__LINE__", Macro("__LINE__", "__LINE__", dummy)));
macros.insert(std::make_pair("__COUNTER__", Macro("__COUNTER__", "__COUNTER__", dummy)));
struct tm ltime = {};
getLocaltime(ltime);
macros.insert(std::make_pair("__DATE__", Macro("__DATE__", getDateDefine(<ime), dummy)));
macros.insert(std::make_pair("__TIME__", Macro("__TIME__", getTimeDefine(<ime), dummy)));
if (!dui.std.empty()) {
const cstd_t c_std = simplecpp::getCStd(dui.std);
if (c_std != CUnknown) {
const std::string std_def = simplecpp::getCStdString(c_std);
if (!std_def.empty())
macros.insert(std::make_pair("__STDC_VERSION__", Macro("__STDC_VERSION__", std_def, dummy)));
} else {
const cppstd_t cpp_std = simplecpp::getCppStd(dui.std);
if (cpp_std == CPPUnknown) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::DUI_ERROR;
err.msg = "unknown standard specified: '" + dui.std + "'";
outputList->push_back(err);
}
output.clear();
return;
}
const std::string std_def = simplecpp::getCppStdString(cpp_std);
if (!std_def.empty())
macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", std_def, dummy)));
}
}
// True => code in current #if block should be kept
// ElseIsTrue => code in current #if block should be dropped. the code in the #else should be kept.
// AlwaysFalse => drop all code in #if and #else
enum IfState { True, ElseIsTrue, AlwaysFalse };
std::stack<int> ifstates;
ifstates.push(True);
std::stack<const Token *> includetokenstack;
std::set<std::string> pragmaOnce;
includetokenstack.push(rawtokens.cfront());
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::map<std::string, TokenList*>::const_iterator f = filedata.find(*it);
if (f != filedata.end())
includetokenstack.push(f->second->cfront());
}
std::map<std::string, std::list<Location> > maybeUsedMacros;
for (const Token *rawtok = nullptr; rawtok || !includetokenstack.empty();) {
if (rawtok == nullptr) {
rawtok = includetokenstack.top();
includetokenstack.pop();
continue;
}
if (rawtok->op == '#' && !sameline(rawtok->previousSkipComments(), rawtok)) {
if (!sameline(rawtok, rawtok->next)) {
rawtok = rawtok->next;
continue;
}
rawtok = rawtok->next;
if (!rawtok->name) {
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.size() <= 1U && (rawtok->str() == ELIF || rawtok->str() == ELSE || rawtok->str() == ENDIF)) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "#" + rawtok->str() + " without #if";
outputList->push_back(err);
}
output.clear();
return;
}
if (ifstates.top() == True && (rawtok->str() == ERROR || rawtok->str() == WARNING)) {
if (outputList) {
simplecpp::Output err(rawtok->location.files);
err.type = rawtok->str() == ERROR ? Output::ERROR : Output::WARNING;
err.location = rawtok->location;
for (const Token *tok = rawtok->next; tok && sameline(rawtok,tok); tok = tok->next) {
if (!err.msg.empty() && isNameChar(tok->str()[0]))
err.msg += ' ';
err.msg += tok->str();
}
err.msg = '#' + rawtok->str() + ' ' + err.msg;
outputList->push_back(err);
}
if (rawtok->str() == ERROR) {
output.clear();
return;
}
}
if (rawtok->str() == DEFINE) {
if (ifstates.top() != True)
continue;
try {
const Macro ¯o = Macro(rawtok->previous, files);
if (dui.undefined.find(macro.name()) == dui.undefined.end()) {
const MacroMap::iterator it = macros.find(macro.name());
if (it == macros.end())
macros.insert(std::pair<TokenString, Macro>(macro.name(), macro));
else
it->second = macro;
}
} catch (const std::runtime_error &) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "Failed to parse #define";
outputList->push_back(err);
}
output.clear();
return;
}
} else if (ifstates.top() == True && rawtok->str() == INCLUDE) {
TokenList inc1(files);
for (const Token *inctok = rawtok->next; sameline(rawtok,inctok); inctok = inctok->next) {
if (!inctok->comment)
inc1.push_back(new Token(*inctok));
}
TokenList inc2(files);
if (!inc1.empty() && inc1.cfront()->name) {
const Token *inctok = inc1.cfront();
if (!preprocessToken(inc2, &inctok, macros, files, outputList)) {
output.clear();
return;
}
} else {
inc2.takeTokens(inc1);
}
if (!inc2.empty() && inc2.cfront()->op == '<' && inc2.cback()->op == '>') {
TokenString hdr;
// TODO: Sometimes spaces must be added in the string
// Somehow preprocessToken etc must be told that the location should be source location not destination location
for (const Token *tok = inc2.cfront(); tok; tok = tok->next) {
hdr += tok->str();
}
inc2.clear();
inc2.push_back(new Token(hdr, inc1.cfront()->location));
inc2.front()->op = '<';
}
if (inc2.empty() || inc2.cfront()->str().size() <= 2U) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "No header in #include";
outputList->push_back(err);
}
output.clear();
return;
}
const Token * const inctok = inc2.cfront();
const bool systemheader = (inctok->str()[0] == '<');
const std::string header(realFilename(inctok->str().substr(1U, inctok->str().size() - 2U)));
std::string header2 = getFileName(filedata, rawtok->location.file(), header, dui, systemheader);
if (header2.empty()) {
// try to load file..
std::ifstream f;
header2 = openHeader(f, dui, rawtok->location.file(), header, systemheader);
if (f.is_open()) {
f.close();
TokenList * const tokens = new TokenList(header2, files, outputList);
if (dui.removeComments)
tokens->removeComments();
filedata[header2] = tokens;
}
}
if (header2.empty()) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::MISSING_HEADER;
out.location = rawtok->location;
out.msg = "Header not found: " + inctok->str();
outputList->push_back(out);
}
} else if (includetokenstack.size() >= 400) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::INCLUDE_NESTED_TOO_DEEPLY;
out.location = rawtok->location;
out.msg = "#include nested too deeply";
outputList->push_back(out);
}
} else if (pragmaOnce.find(header2) == pragmaOnce.end()) {
includetokenstack.push(gotoNextLine(rawtok));
const TokenList * const includetokens = filedata.find(header2)->second;
rawtok = includetokens ? includetokens->cfront() : nullptr;
continue;
}
} else if (rawtok->str() == IF || rawtok->str() == IFDEF || rawtok->str() == IFNDEF || rawtok->str() == ELIF) {
if (!sameline(rawtok,rawtok->next)) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "Syntax error in #" + rawtok->str();
outputList->push_back(out);
}
output.clear();
return;
}
bool conditionIsTrue;
if (ifstates.top() == AlwaysFalse || (ifstates.top() == ElseIsTrue && rawtok->str() != ELIF))
conditionIsTrue = false;
else if (rawtok->str() == IFDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) != macros.end() || (hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else if (rawtok->str() == IFNDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) == macros.end() && !(hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else { /*if (rawtok->str() == IF || rawtok->str() == ELIF)*/
TokenList expr(files);
for (const Token *tok = rawtok->next; tok && tok->location.sameline(rawtok->location); tok = tok->next) {
if (!tok->name) {
expr.push_back(new Token(*tok));
continue;
}
if (tok->str() == DEFINED) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
if (tok) {
if (macros.find(tok->str()) != macros.end())
expr.push_back(new Token("1", tok->location));
else if (hasInclude && tok->str() == HAS_INCLUDE)
expr.push_back(new Token("1", tok->location));
else
expr.push_back(new Token("0", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
if (hasInclude && tok->str() == HAS_INCLUDE) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
bool closingAngularBracket = false;
if (tok) {
const std::string &sourcefile = rawtok->location.file();
const bool systemheader = (tok && tok->op == '<');
std::string header;
if (systemheader) {
while ((tok = tok->next) && tok->op != '>')
header += tok->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
if (tok && tok->op == '>')
closingAngularBracket = true;
}
else {
header = realFilename(tok->str().substr(1U, tok->str().size() - 2U));
closingAngularBracket = true;
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
expr.push_back(new Token(header2.empty() ? "0" : "1", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')') || (!closingAngularBracket)) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
const Token *tmp = tok;
if (!preprocessToken(expr, &tmp, macros, files, outputList)) {
output.clear();
return;
}
if (!tmp)
break;
tok = tmp->previous;
}
try {
if (ifCond) {
std::string E;
for (const simplecpp::Token *tok = expr.cfront(); tok; tok = tok->next)
E += (E.empty() ? "" : " ") + tok->str();
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
ifCond->push_back(IfCond(rawtok->location, E, result));
} else {
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
}
} catch (const std::exception &e) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
if (e.what() && *e.what())
out.msg += std::string(", ") + e.what();
outputList->push_back(out);
}
output.clear();
return;
}
}
if (rawtok->str() != ELIF) {
// push a new ifstate..
if (ifstates.top() != True)
ifstates.push(AlwaysFalse);
else
ifstates.push(conditionIsTrue ? True : ElseIsTrue);
} else if (ifstates.top() == True) {
ifstates.top() = AlwaysFalse;
} else if (ifstates.top() == ElseIsTrue && conditionIsTrue) {
ifstates.top() = True;
}
} else if (rawtok->str() == ELSE) {
ifstates.top() = (ifstates.top() == ElseIsTrue) ? True : AlwaysFalse;
} else if (rawtok->str() == ENDIF) {
ifstates.pop();
} else if (rawtok->str() == UNDEF) {
if (ifstates.top() == True) {
const Token *tok = rawtok->next;
while (sameline(rawtok,tok) && tok->comment)
tok = tok->next;
if (sameline(rawtok, tok))
macros.erase(tok->str());
}
} else if (ifstates.top() == True && rawtok->str() == PRAGMA && rawtok->next && rawtok->next->str() == ONCE && sameline(rawtok,rawtok->next)) {
pragmaOnce.insert(rawtok->location.file());
}
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.top() != True) {
// drop code
rawtok = gotoNextLine(rawtok);
continue;
}
bool hash=false, hashhash=false;
if (rawtok->op == '#' && sameline(rawtok,rawtok->next)) {
if (rawtok->next->op != '#') {
hash = true;
rawtok = rawtok->next; // skip '#'
} else if (sameline(rawtok,rawtok->next->next)) {
hashhash = true;
rawtok = rawtok->next->next; // skip '#' '#'
}
}
const Location loc(rawtok->location);
TokenList tokens(files);
if (!preprocessToken(tokens, &rawtok, macros, files, outputList)) {
output.clear();
return;
}
if (hash || hashhash) {
std::string s;
for (const Token *hashtok = tokens.cfront(); hashtok; hashtok = hashtok->next)
s += hashtok->str();
if (hash)
output.push_back(new Token('\"' + s + '\"', loc));
else if (output.back())
output.back()->setstr(output.cback()->str() + s);
else
output.push_back(new Token(s, loc));
} else {
output.takeTokens(tokens);
}
}
if (macroUsage) {
for (simplecpp::MacroMap::const_iterator macroIt = macros.begin(); macroIt != macros.end(); ++macroIt) {
const Macro ¯o = macroIt->second;
std::list<Location> usage = macro.usage();
const std::list<Location>& temp = maybeUsedMacros[macro.name()];
usage.insert(usage.end(), temp.begin(), temp.end());
for (std::list<Location>::const_iterator usageIt = usage.begin(); usageIt != usage.end(); ++usageIt) {
MacroUsage mu(usageIt->files, macro.valueDefinedInCode());
mu.macroName = macro.name();
mu.macroLocation = macro.defineLocation();
mu.useLocation = *usageIt;
macroUsage->push_back(mu);
}
}
}
}
void simplecpp::cleanup(std::map<std::string, TokenList*> &filedata)
{
for (std::map<std::string, TokenList*>::iterator it = filedata.begin(); it != filedata.end(); ++it)
delete it->second;
filedata.clear();
}
simplecpp::cstd_t simplecpp::getCStd(const std::string &std)
{
if (std == "c90" || std == "c89" || std == "iso9899:1990" || std == "iso9899:199409" || std == "gnu90" || std == "gnu89")
return C89;
if (std == "c99" || std == "c9x" || std == "iso9899:1999" || std == "iso9899:199x" || std == "gnu99"|| std == "gnu9x")
return C99;
if (std == "c11" || std == "c1x" || std == "iso9899:2011" || std == "gnu11" || std == "gnu1x")
return C11;
if (std == "c17" || std == "c18" || std == "iso9899:2017" || std == "iso9899:2018" || std == "gnu17"|| std == "gnu18")
return C17;
if (std == "c23" || std == "gnu23" || std == "c2x" || std == "gnu2x")
return C23;
return CUnknown;
}
std::string simplecpp::getCStdString(cstd_t std)
{
switch (std)
{
case C89:
// __STDC_VERSION__ is not set for C90 although the macro was added in the 1994 amendments
return "";
case C99:
return "199901L";
case C11:
return "201112L";
case C17:
return "201710L";
case C23:
// supported by GCC 9+ and Clang 9+
// Clang 9, 10, 11, 12, 13 return "201710L"
// Clang 14, 15, 16, 17 return "202000L"
// Clang 9, 10, 11, 12, 13, 14, 15, 16, 17 do not support "c23" and "gnu23"
return "202311L";
case CUnknown:
return "";
}
return "";
}
std::string simplecpp::getCStdString(const std::string &std)
{
return getCStdString(getCStd(std));
}
simplecpp::cppstd_t simplecpp::getCppStd(const std::string &std)
{
if (std == "c++98" || std == "c++03" || std == "gnu++98" || std == "gnu++03")
return CPP03;
if (std == "c++11" || std == "gnu++11" || std == "c++0x" || std == "gnu++0x")
return CPP11;
if (std == "c++14" || std == "c++1y" || std == "gnu++14" || std == "gnu++1y")
return CPP14;
if (std == "c++17" || std == "c++1z" || std == "gnu++17" || std == "gnu++1z")
return CPP17;
if (std == "c++20" || std == "c++2a" || std == "gnu++20" || std == "gnu++2a")
return CPP20;
if (std == "c++23" || std == "c++2b" || std == "gnu++23" || std == "gnu++2b")
return CPP23;
if (std == "c++26" || std == "c++2c" || std == "gnu++26" || std == "gnu++2c")
return CPP26;
return CPPUnknown;
}
std::string simplecpp::getCppStdString(cppstd_t std)
{
switch (std)
{
case CPP03:
return "199711L";
case CPP11:
return "201103L";
case CPP14:
return "201402L";
case CPP17:
return "201703L";
case CPP20:
// GCC 10 returns "201703L" - correct in 11+
return "202002L";
case CPP23:
// supported by GCC 11+ and Clang 12+
// GCC 11, 12, 13 return "202100L"
// Clang 12, 13, 14, 15, 16 do not support "c++23" and "gnu++23" and return "202101L"
// Clang 17, 18 return "202302L"
return "202302L";
case CPP26:
// supported by Clang 17+
return "202400L";
case CPPUnknown:
return "";
}
return "";
}
std::string simplecpp::getCppStdString(const std::string &std)
{
return getCppStdString(getCppStd(std));
}
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif
| 147,010
|
C++
|
.cpp
| 3,457
| 30.381545
| 331
| 0.511152
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,318
|
codeeditstylecontrols.cpp
|
danmar_cppcheck/gui/codeeditstylecontrols.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "codeeditstylecontrols.h"
#include <QColorDialog>
#include <QDialog>
#include <QObject>
#include <QString>
#include <QVariant>
class QWidget;
SelectColorButton::SelectColorButton(QWidget* parent) :
QPushButton(parent),
mColor(QColor(255, 255, 255))
{
updateColor();
connect(this, SIGNAL(clicked()), this, SLOT(changeColor()));
}
void SelectColorButton::updateColor()
{
QString btnColorStyle = QString(
"background-color:rgb(%1,%2,%3);"
"border-style:outset;"
"border-width: 1px;")
.arg(mColor.red())
.arg(mColor.green())
.arg(mColor.blue());
setObjectName("SelectColorButton");
setStyleSheet(btnColorStyle);
}
void SelectColorButton::changeColor()
{
QColorDialog pDlg(mColor);
pDlg.setModal(true);
const int nResult = pDlg.exec();
if (nResult == QDialog::Accepted) {
setColor(pDlg.selectedColor());
emit colorChanged(mColor);
}
}
void SelectColorButton::setColor(const QColor& color)
{
mColor = color;
updateColor();
}
// cppcheck-suppress unusedFunction
const QColor& SelectColorButton::getColor()
{
return mColor;
}
SelectFontWeightCombo::SelectFontWeightCombo(QWidget* parent) :
QComboBox(parent)
{
addItem(QObject::tr("Thin"),
QVariant(static_cast<int>(QFont::Thin)));
addItem(QObject::tr("ExtraLight"),
QVariant(static_cast<int>(QFont::ExtraLight)));
addItem(QObject::tr("Light"),
QVariant(static_cast<int>(QFont::Light)));
addItem(QObject::tr("Normal"),
QVariant(static_cast<int>(QFont::Normal)));
addItem(QObject::tr("Medium"),
QVariant(static_cast<int>(QFont::Medium)));
addItem(QObject::tr("DemiBold"),
QVariant(static_cast<int>(QFont::DemiBold)));
addItem(QObject::tr("Bold"),
QVariant(static_cast<int>(QFont::Bold)));
addItem(QObject::tr("ExtraBold"),
QVariant(static_cast<int>(QFont::ExtraBold)));
addItem(QObject::tr("Black"),
QVariant(static_cast<int>(QFont::Black)));
updateWeight();
connect(this, SIGNAL(currentIndexChanged(int)),
this, SLOT(changeWeight(int)));
}
void SelectFontWeightCombo::updateWeight()
{
const int nResult = findData(QVariant(static_cast<int>(mWeight)));
if (nResult != -1) {
setCurrentIndex(nResult);
} else {
setCurrentIndex(findData(static_cast<int>(QFont::Normal)));
}
}
void SelectFontWeightCombo::changeWeight(int index)
{
if (index != -1) {
setWeight(static_cast<QFont::Weight>(itemData(index).toInt()));
emit weightChanged(mWeight);
}
}
void SelectFontWeightCombo::setWeight(QFont::Weight weight)
{
mWeight = weight;
updateWeight();
}
// cppcheck-suppress unusedFunction
const QFont::Weight& SelectFontWeightCombo::getWeight()
{
return mWeight;
}
| 3,686
|
C++
|
.cpp
| 114
| 27.385965
| 72
| 0.680157
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,319
|
scratchpad.cpp
|
danmar_cppcheck/gui/scratchpad.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "scratchpad.h"
#include "codeeditor.h"
#include "mainwindow.h"
#include "ui_scratchpad.h"
#include <QLineEdit>
#include <QPushButton>
#include <QString>
ScratchPad::ScratchPad(MainWindow& mainWindow)
: QDialog(&mainWindow)
, mUI(new Ui::ScratchPad)
, mMainWindow(mainWindow)
{
mUI->setupUi(this);
connect(mUI->mCheckButton, &QPushButton::clicked, this, &ScratchPad::checkButtonClicked);
}
ScratchPad::~ScratchPad()
{
delete mUI;
}
void ScratchPad::translate()
{
mUI->retranslateUi(this);
}
void ScratchPad::checkButtonClicked()
{
QString filename = mUI->lineEdit->text();
if (filename.isEmpty())
filename = "test.cpp";
mMainWindow.analyzeCode(mUI->plainTextEdit->toPlainText(), filename);
}
| 1,507
|
C++
|
.cpp
| 47
| 29.510638
| 93
| 0.743625
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,320
|
resultstree.cpp
|
danmar_cppcheck/gui/resultstree.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resultstree.h"
#include "application.h"
#include "applicationlist.h"
#include "checkers.h"
#include "common.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "projectfile.h"
#include "report.h"
#include "showtypes.h"
#include "suppressions.h"
#include "threadhandler.h"
#include "xmlreportv2.h"
#include <algorithm>
#include <utility>
#include <vector>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QContextMenuEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QFileDialog>
#include <QIcon>
#include <QItemSelectionModel>
#include <QKeyEvent>
#include <QList>
#include <QLocale>
#include <QMap>
#include <QMenu>
#include <QMessageBox>
#include <QModelIndex>
#include <QObject>
#include <QProcess>
#include <QSet>
#include <QSettings>
#include <QSignalMapper>
#include <QStandardItem>
#include <QUrl>
#include <QVariant>
#include <QVariantMap>
#include <Qt>
static constexpr char COLUMN[] = "column";
static constexpr char CWE[] = "cwe";
static constexpr char ERRORID[] = "id";
static constexpr char FILENAME[] = "file";
static constexpr char FILE0[] = "file0";
static constexpr char HASH[] = "hash";
static constexpr char HIDE[] = "hide";
static constexpr char INCONCLUSIVE[] = "inconclusive";
static constexpr char LINE[] = "line";
static constexpr char MESSAGE[] = "message";
static constexpr char REMARK[] = "remark";
static constexpr char SEVERITY[] = "severity";
static constexpr char SINCEDATE[] = "sinceDate";
static constexpr char SYMBOLNAMES[] = "symbolNames";
static constexpr char SUMMARY[] = "summary";
static constexpr char TAGS[] = "tags";
// These must match column headers given in ResultsTree::translate()
static constexpr int COLUMN_FILE = 0;
static constexpr int COLUMN_LINE = 1;
static constexpr int COLUMN_SEVERITY = 2;
static constexpr int COLUMN_MISRA_CLASSIFICATION = 3;
static constexpr int COLUMN_CERT_LEVEL = 4;
static constexpr int COLUMN_INCONCLUSIVE = 5;
static constexpr int COLUMN_SUMMARY = 6;
static constexpr int COLUMN_ID = 7;
static constexpr int COLUMN_MISRA_GUIDELINE = 8;
static constexpr int COLUMN_CERT_RULE = 9;
static constexpr int COLUMN_SINCE_DATE = 10;
static constexpr int COLUMN_TAGS = 11;
static constexpr int COLUMN_CWE = 12;
static QString getGuideline(ReportType reportType, const QMap<QString,QString>& guidelines, const QString& errorId, Severity severity) {
if (reportType == ReportType::autosar) {
if (errorId.startsWith("premium-autosar-"))
return errorId.mid(16);
if (errorId.startsWith("premium-misra-cpp-2008-"))
return "M" + errorId.mid(23);
}
if (reportType == ReportType::certC || reportType == ReportType::certCpp) {
if (errorId.startsWith("premium-cert-"))
return errorId.mid(13).toUpper();
}
if (errorId.startsWith("premium-"))
return getGuideline(reportType, guidelines, errorId.mid(8), severity);
if (reportType == ReportType::misraC && (errorId.startsWith("misra-c20") || errorId.startsWith("misra-c-20")))
return errorId.mid(errorId.lastIndexOf("-") + 1);
if (reportType == ReportType::misraCpp2008 && errorId.startsWith("misra-cpp-2008-"))
return errorId.mid(15);
if (reportType == ReportType::misraCpp2023 && errorId.startsWith("misra-cpp-2023-"))
return errorId.mid(15);
const QString& guideline = guidelines.value(errorId);
if (!guideline.isEmpty())
return guideline;
if (severity == Severity::error || severity == Severity::warning)
return guidelines.value("error");
return QString();
}
static QString getClassification(ReportType reportType, const QString& guideline) {
if (guideline.isEmpty())
return QString();
auto getFromInfo = [](const std::vector<checkers::Info>& info, const QString& guideline) -> QString {
for (const checkers::Info& i: info) {
// cppcheck-suppress useStlAlgorithm
if (guideline.compare(i.guideline, Qt::CaseInsensitive) == 0)
return i.classification;
}
return QString();
};
if (reportType == ReportType::autosar)
return getFromInfo(checkers::autosarInfo, guideline);
if (reportType == ReportType::certC || reportType == ReportType::certCpp) {
if (guideline.endsWith("-CPP"))
return getFromInfo(checkers::certCppInfo, guideline);
if (guideline.endsWith("-C"))
return getFromInfo(checkers::certCInfo, guideline);
}
else if (reportType == ReportType::misraC) {
QStringList list = guideline.split(".");
if (list.size() == 2) {
bool ok = true;
const int a = list[0].toInt(&ok);
if (!ok)
return QString();
const int b = list[1].toInt(&ok);
if (!ok)
return QString();
for (const auto& info: checkers::misraC2012Rules) {
// cppcheck-suppress useStlAlgorithm
if (info.a == a && info.b == b)
return info.str;
}
}
}
else if (reportType == ReportType::misraCpp2008) {
QStringList list = guideline.split("-");
if (list.size() == 3) {
bool ok = true;
const int a = list[0].toInt(&ok);
if (!ok)
return QString();
const int b = list[1].toInt(&ok);
if (!ok)
return QString();
const int c = list[2].toInt(&ok);
if (!ok)
return QString();
for (const auto& info: checkers::misraCpp2008Rules) {
// cppcheck-suppress useStlAlgorithm
if (info.a == a && info.b == b && info.c == c)
return info.classification;
}
}
}
else if (reportType == ReportType::misraCpp2023) {
QStringList list = guideline.split(".");
if (list.size() == 3) {
bool ok = true;
const int a = list[0].toInt(&ok);
if (!ok)
return QString();
const int b = list[1].toInt(&ok);
if (!ok)
return QString();
const int c = list[2].toInt(&ok);
if (!ok)
return QString();
for (const auto& info: checkers::misraCpp2023Rules) {
// cppcheck-suppress useStlAlgorithm
if (info.a == a && info.b == b && info.c == c)
return info.classification;
}
}
}
return QString();
}
static Severity getSeverityFromClassification(const QString &c) {
if (c == checkers::Man)
return Severity::error;
if (c == checkers::Req)
return Severity::warning;
if (c == checkers::Adv)
return Severity::style;
if (c == checkers::Doc)
return Severity::information;
if (c == "L1")
return Severity::error;
if (c == "L2")
return Severity::warning;
if (c == "L3")
return Severity::style;
return Severity::none;
}
static QStringList getLabels() {
return QStringList{
QObject::tr("File"),
QObject::tr("Line"),
QObject::tr("Severity"),
QObject::tr("Classification"),
QObject::tr("Level"),
QObject::tr("Inconclusive"),
QObject::tr("Summary"),
QObject::tr("Id"),
QObject::tr("Guideline"),
QObject::tr("Rule"),
QObject::tr("Since date"),
QObject::tr("Tags"),
QObject::tr("CWE")};
}
ResultsTree::ResultsTree(QWidget * parent) :
QTreeView(parent)
{
setModel(&mModel);
translate(); // Adds columns to grid
clear();
setExpandsOnDoubleClick(false);
setSortingEnabled(true);
connect(this, &ResultsTree::doubleClicked, this, &ResultsTree::quickStartApplication);
}
void ResultsTree::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
quickStartApplication(this->currentIndex());
}
QTreeView::keyPressEvent(event);
}
void ResultsTree::setReportType(ReportType reportType) {
mReportType = reportType;
auto readIdMapping = [this](const std::vector<checkers::IdMapping>& idMapping, const char* ext = "") {
for (const auto& i: idMapping)
for (const QString& cppcheckId: QString(i.cppcheckId).split(","))
mGuideline[cppcheckId] = QString(i.guideline) + ext;
};
if (reportType == ReportType::autosar)
readIdMapping(checkers::idMappingAutosar);
else if (reportType == ReportType::certC)
readIdMapping(checkers::idMappingCertC, "-C");
else if (reportType == ReportType::certCpp) {
readIdMapping(checkers::idMappingCertC, "-C");
readIdMapping(checkers::idMappingCertCpp, "-CPP");
}
else if (reportType == ReportType::misraC)
readIdMapping(checkers::idMappingMisraC);
else if (reportType == ReportType::misraCpp2008)
readIdMapping(checkers::idMappingMisraCpp2008);
else if (reportType == ReportType::misraCpp2023)
readIdMapping(checkers::idMappingMisraCpp2023);
for (int i = 0; i < mModel.rowCount(); ++i) {
const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
if (!fileItem)
continue;
for (int j = 0; j < fileItem->rowCount(); ++j) {
const auto& childdata = fileItem->child(j,0)->data().toMap();
const QString& errorId = childdata[ERRORID].toString();
Severity severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(childdata[SEVERITY]));
const QString& guideline = getGuideline(mReportType, mGuideline, errorId, severity);
const QString& classification = getClassification(mReportType, guideline);
fileItem->child(j, COLUMN_CERT_LEVEL)->setText(classification);
fileItem->child(j, COLUMN_CERT_RULE)->setText(guideline);
fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->setText(classification);
fileItem->child(j, COLUMN_MISRA_GUIDELINE)->setText(guideline);
}
}
if (isAutosarMisraReport()) {
showColumn(COLUMN_MISRA_CLASSIFICATION);
showColumn(COLUMN_MISRA_GUIDELINE);
} else {
hideColumn(COLUMN_MISRA_CLASSIFICATION);
hideColumn(COLUMN_MISRA_GUIDELINE);
}
if (isCertReport()) {
showColumn(COLUMN_CERT_LEVEL);
showColumn(COLUMN_CERT_RULE);
} else {
hideColumn(COLUMN_CERT_LEVEL);
hideColumn(COLUMN_CERT_RULE);
}
if (mReportType == ReportType::normal) {
showColumn(COLUMN_SEVERITY);
} else {
hideColumn(COLUMN_SEVERITY);
}
refreshTree();
}
void ResultsTree::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
mSettings = settings;
mApplications = list;
mThread = checkThreadHandler;
loadSettings();
}
QStandardItem *ResultsTree::createNormalItem(const QString &name)
{
auto *item = new QStandardItem(name);
item->setData(name, Qt::ToolTipRole);
item->setEditable(false);
return item;
}
QStandardItem *ResultsTree::createCheckboxItem(bool checked)
{
auto *item = new QStandardItem;
item->setCheckable(true);
item->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
item->setEnabled(false);
return item;
}
QStandardItem *ResultsTree::createLineNumberItem(const QString &linenumber)
{
auto *item = new QStandardItem();
item->setData(QVariant(linenumber.toInt()), Qt::DisplayRole);
item->setToolTip(linenumber);
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
item->setEditable(false);
return item;
}
bool ResultsTree::addErrorItem(const ErrorItem &item)
{
if (item.errorPath.isEmpty()) {
return false;
}
const QErrorPathItem &loc = item.errorId.startsWith("clang") ? item.errorPath.front() : item.errorPath.back();
QString realfile = stripPath(loc.file, false);
if (realfile.isEmpty()) {
realfile = tr("Undefined file");
}
bool showItem = true;
// Ids that are temporarily hidden..
if (mHiddenMessageId.contains(item.errorId))
showItem = false;
//If specified, filter on summary, message, filename, and id
if (showItem && !mFilter.isEmpty()) {
if (!item.summary.contains(mFilter, Qt::CaseInsensitive) &&
!item.message.contains(mFilter, Qt::CaseInsensitive) &&
!item.errorPath.back().file.contains(mFilter, Qt::CaseInsensitive) &&
!item.errorId.contains(mFilter, Qt::CaseInsensitive)) {
showItem = false;
}
}
if (showItem) {
if (mReportType == ReportType::normal)
showItem = mShowSeverities.isShown(item.severity);
else {
const QString& guideline = getGuideline(mReportType, mGuideline, item.errorId, item.severity);
const QString& classification = getClassification(mReportType, guideline);
showItem = !classification.isEmpty() && mShowSeverities.isShown(getSeverityFromClassification(classification));
}
}
// if there is at least one error that is not hidden, we have a visible error
mVisibleErrors |= showItem;
ErrorLine line;
line.file = realfile;
line.line = loc.line;
line.errorId = item.errorId;
line.cwe = item.cwe;
line.hash = item.hash;
line.inconclusive = item.inconclusive;
line.summary = item.summary;
line.message = item.message;
line.severity = item.severity;
line.sinceDate = item.sinceDate;
if (const ProjectFile *activeProject = ProjectFile::getActiveProject()) {
line.tags = activeProject->getWarningTags(item.hash);
}
line.remark = item.remark;
//Create the base item for the error and ensure it has a proper
//file item as a parent
QStandardItem* fileItem = ensureFileItem(loc.file, item.file0, !showItem);
QStandardItem* stditem = addBacktraceFiles(fileItem,
line,
!showItem,
severityToIcon(line.severity),
false);
if (!stditem)
return false;
//Add user data to that item
QMap<QString, QVariant> itemdata;
itemdata[SEVERITY] = ShowTypes::SeverityToShowType(item.severity);
itemdata[SUMMARY] = item.summary;
itemdata[MESSAGE] = item.message;
itemdata[FILENAME] = loc.file;
itemdata[LINE] = loc.line;
itemdata[COLUMN] = loc.column;
itemdata[ERRORID] = item.errorId;
itemdata[CWE] = item.cwe;
itemdata[HASH] = item.hash;
itemdata[INCONCLUSIVE] = item.inconclusive;
itemdata[FILE0] = stripPath(item.file0, true);
itemdata[SINCEDATE] = item.sinceDate;
itemdata[SYMBOLNAMES] = item.symbolNames;
itemdata[TAGS] = line.tags;
itemdata[REMARK] = line.remark;
itemdata[HIDE] = false;
stditem->setData(QVariant(itemdata));
//Add backtrace files as children
if (item.errorPath.size() > 1) {
for (int i = 0; i < item.errorPath.size(); i++) {
const QErrorPathItem &e = item.errorPath[i];
line.file = e.file;
line.line = e.line;
line.message = line.summary = e.info;
QStandardItem *child_item = addBacktraceFiles(stditem,
line,
false,
":images/go-down.png",
true);
if (!child_item)
continue;
// Add user data to that item
QMap<QString, QVariant> child_data;
child_data[SEVERITY] = ShowTypes::SeverityToShowType(line.severity);
child_data[SUMMARY] = line.summary;
child_data[MESSAGE] = line.message;
child_data[FILENAME] = e.file;
child_data[LINE] = e.line;
child_data[COLUMN] = e.column;
child_data[ERRORID] = line.errorId;
child_data[CWE] = line.cwe;
child_data[HASH] = line.hash;
child_data[INCONCLUSIVE] = line.inconclusive;
child_data[SYMBOLNAMES] = item.symbolNames;
child_item->setData(QVariant(child_data));
}
}
return true;
}
QStandardItem *ResultsTree::addBacktraceFiles(QStandardItem *parent,
const ErrorLine &item,
const bool hide,
const QString &icon,
bool childOfMessage)
{
if (!parent)
return nullptr;
//TODO message has parameter names so we'll need changes to the core
//cppcheck so we can get proper translations
const QString itemSeverity = childOfMessage ? tr("note") : severityToTranslatedString(item.severity);
// Check for duplicate rows and don't add them if found
for (int i = 0; i < parent->rowCount(); i++) {
// The first column is the file name and is always the same
// the third column is the line number so check it first
if (parent->child(i, COLUMN_LINE)->text() == QString::number(item.line)) {
// the second column is the severity so check it next
if (parent->child(i, COLUMN_SEVERITY)->text() == itemSeverity) {
// the sixth column is the summary so check it last
if (parent->child(i, COLUMN_SUMMARY)->text() == item.summary) {
// this row matches so don't add it
return nullptr;
}
}
}
}
QMap<int, QStandardItem*> columns;
const QString guideline = getGuideline(mReportType, mGuideline, item.errorId, item.severity);
const QString classification = getClassification(mReportType, guideline);
columns[COLUMN_CERT_LEVEL] = createNormalItem(classification);
columns[COLUMN_CERT_RULE] = createNormalItem(guideline);
columns[COLUMN_CWE] = createNormalItem(QString::number(item.cwe));
columns[COLUMN_FILE] = createNormalItem(QDir::toNativeSeparators(item.file));
columns[COLUMN_ID] = createNormalItem(childOfMessage ? QString() : item.errorId);
columns[COLUMN_INCONCLUSIVE] = childOfMessage ? createNormalItem(QString()) : createCheckboxItem(item.inconclusive);
columns[COLUMN_LINE] = createLineNumberItem(QString::number(item.line));
columns[COLUMN_MISRA_CLASSIFICATION] = createNormalItem(classification);
columns[COLUMN_MISRA_GUIDELINE] = createNormalItem(guideline);
columns[COLUMN_SEVERITY] = createNormalItem(itemSeverity);
columns[COLUMN_SINCE_DATE] = createNormalItem(item.sinceDate);
columns[COLUMN_SUMMARY] = createNormalItem(item.summary);
columns[COLUMN_TAGS] = createNormalItem(item.tags);
const int numberOfColumns = getLabels().size();
QList<QStandardItem*> list;
for (int i = 0; i < numberOfColumns; ++i)
list << columns[i];
parent->appendRow(list);
setRowHidden(parent->rowCount() - 1, parent->index(), hide);
if (!icon.isEmpty()) {
list[0]->setIcon(QIcon(icon));
}
return list[0];
}
QString ResultsTree::severityToTranslatedString(Severity severity)
{
switch (severity) {
case Severity::style:
return tr("style");
case Severity::error:
return tr("error");
case Severity::warning:
return tr("warning");
case Severity::performance:
return tr("performance");
case Severity::portability:
return tr("portability");
case Severity::information:
return tr("information");
case Severity::debug:
return tr("debug");
case Severity::internal:
return tr("internal");
case Severity::none:
default:
return QString();
}
}
QStandardItem *ResultsTree::findFileItem(const QString &name) const
{
// The first column contains the file name. In Windows we can get filenames
// "header.h" and "Header.h" and must compare them as identical.
for (int i = 0; i < mModel.rowCount(); i++) {
#ifdef _WIN32
if (QString::compare(mModel.item(i, COLUMN_FILE)->text(), name, Qt::CaseInsensitive) == 0)
#else
if (mModel.item(i, COLUMN_FILE)->text() == name)
#endif
return mModel.item(i, COLUMN_FILE);
}
return nullptr;
}
void ResultsTree::clear()
{
mModel.removeRows(0, mModel.rowCount());
if (const ProjectFile *activeProject = ProjectFile::getActiveProject()) {
hideColumn(COLUMN_SINCE_DATE);
if (activeProject->getTags().isEmpty())
hideColumn(COLUMN_TAGS);
else
showColumn(COLUMN_TAGS);
} else {
hideColumn(COLUMN_SINCE_DATE);
hideColumn(COLUMN_TAGS);
}
}
void ResultsTree::clear(const QString &filename)
{
const QString stripped = stripPath(filename, false);
for (int i = 0; i < mModel.rowCount(); ++i) {
const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
if (!fileItem)
continue;
QVariantMap fitemdata = fileItem->data().toMap();
if (stripped == fitemdata[FILENAME].toString() ||
filename == fitemdata[FILE0].toString()) {
mModel.removeRow(i);
break;
}
}
}
void ResultsTree::clearRecheckFile(const QString &filename)
{
for (int i = 0; i < mModel.rowCount(); ++i) {
const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
if (!fileItem)
continue;
QString actualfile((!mCheckPath.isEmpty() && filename.startsWith(mCheckPath)) ? filename.mid(mCheckPath.length() + 1) : filename);
QVariantMap fitemdata = fileItem->data().toMap();
QString storedfile = fitemdata[FILENAME].toString();
storedfile = ((!mCheckPath.isEmpty() && storedfile.startsWith(mCheckPath)) ? storedfile.mid(mCheckPath.length() + 1) : storedfile);
if (actualfile == storedfile) {
mModel.removeRow(i);
break;
}
}
}
void ResultsTree::loadSettings()
{
for (int i = 0; i < mModel.columnCount(); i++) {
QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
setColumnWidth(i, qMax(20, mSettings->value(temp, 800 / mModel.columnCount()).toInt()));
}
mSaveFullPath = mSettings->value(SETTINGS_SAVE_FULL_PATH, false).toBool();
mSaveAllErrors = mSettings->value(SETTINGS_SAVE_ALL_ERRORS, false).toBool();
mShowFullPath = mSettings->value(SETTINGS_SHOW_FULL_PATH, false).toBool();
showIdColumn(mSettings->value(SETTINGS_SHOW_ERROR_ID, true).toBool());
showInconclusiveColumn(mSettings->value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool());
}
void ResultsTree::saveSettings() const
{
for (int i = 0; i < mModel.columnCount(); i++) {
QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
mSettings->setValue(temp, columnWidth(i));
}
}
void ResultsTree::showResults(ShowTypes::ShowType type, bool show)
{
if (type != ShowTypes::ShowNone && mShowSeverities.isShown(type) != show) {
mShowSeverities.show(type, show);
refreshTree();
}
}
void ResultsTree::showCppcheckResults(bool show)
{
mShowCppcheck = show;
refreshTree();
}
void ResultsTree::showClangResults(bool show)
{
mShowClang = show;
refreshTree();
}
void ResultsTree::filterResults(const QString& filter)
{
mFilter = filter;
refreshTree();
}
void ResultsTree::showHiddenResults()
{
//Clear the "hide" flag for each item
mHiddenMessageId.clear();
refreshTree();
emit resultsHidden(false);
}
void ResultsTree::refreshTree()
{
mVisibleErrors = false;
//Get the amount of files in the tree
const int filecount = mModel.rowCount();
for (int i = 0; i < filecount; i++) {
//Get file i
QStandardItem *fileItem = mModel.item(i, 0);
if (!fileItem) {
continue;
}
//Get the amount of errors this file contains
const int errorcount = fileItem->rowCount();
//By default it shouldn't be visible
bool showFile = false;
for (int j = 0; j < errorcount; j++) {
//Get the error itself
QStandardItem *child = fileItem->child(j, 0);
if (!child) {
continue;
}
//Get error's user data and convert it to QVariantMap
QVariantMap userdata = child->data().toMap();
//Check if this error should be hidden
bool hide = userdata[HIDE].toBool() || mHiddenMessageId.contains(userdata[ERRORID].toString());
if (!hide) {
if (mReportType == ReportType::normal)
hide = !mShowSeverities.isShown(ShowTypes::VariantToShowType(userdata[SEVERITY]));
else {
const QString& classification = fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->text();
hide = classification.isEmpty() || !mShowSeverities.isShown(getSeverityFromClassification(classification));
}
}
// If specified, filter on summary, message, filename, and id
if (!hide && !mFilter.isEmpty()) {
if (!userdata[SUMMARY].toString().contains(mFilter, Qt::CaseInsensitive) &&
!userdata[MESSAGE].toString().contains(mFilter, Qt::CaseInsensitive) &&
!userdata[FILENAME].toString().contains(mFilter, Qt::CaseInsensitive) &&
!userdata[ERRORID].toString().contains(mFilter, Qt::CaseInsensitive) &&
!fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->text().contains(mFilter, Qt::CaseInsensitive)) {
hide = true;
}
}
// Tool filter
if (!hide) {
if (userdata[ERRORID].toString().startsWith("clang"))
hide = !mShowClang;
else
hide = !mShowCppcheck;
}
if (!hide) {
showFile = true;
mVisibleErrors = true;
}
//Hide/show accordingly
setRowHidden(j, fileItem->index(), hide);
}
// Show the file if any of it's errors are visible
setRowHidden(i, QModelIndex(), !showFile);
}
}
QStandardItem *ResultsTree::ensureFileItem(const QString &fullpath, const QString &file0, bool hide)
{
QString name = stripPath(fullpath, false);
// Since item has path with native separators we must use path with
// native separators to find it.
QStandardItem *item = findFileItem(QDir::toNativeSeparators(name));
if (item) {
if (!hide)
setRowHidden(item->row(), QModelIndex(), hide);
return item;
}
// Ensure shown path is with native separators
name = QDir::toNativeSeparators(name);
item = createNormalItem(name);
item->setIcon(QIcon(":images/text-x-generic.png"));
//Add user data to that item
QMap<QString, QVariant> itemdata;
itemdata[FILENAME] = fullpath;
itemdata[FILE0] = file0;
item->setData(QVariant(itemdata));
mModel.appendRow(item);
setRowHidden(item->row(), QModelIndex(), hide);
return item;
}
void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
{
QModelIndex index = indexAt(e->pos());
if (index.isValid()) {
bool multipleSelection = false;
mSelectionModel = selectionModel();
if (mSelectionModel->selectedRows().count() > 1)
multipleSelection = true;
mContextItem = mModel.itemFromIndex(index);
//Create a new context menu
QMenu menu(this);
//Create a signal mapper so we don't have to store data to class
//member variables
QSignalMapper signalMapper;
if (mContextItem && mApplications->getApplicationCount() > 0 && mContextItem->parent()) {
//Create an action for the application
int defaultApplicationIndex = mApplications->getDefaultApplication();
defaultApplicationIndex = std::max(defaultApplicationIndex, 0);
const Application& app = mApplications->getApplication(defaultApplicationIndex);
auto *start = new QAction(app.getName(), &menu);
if (multipleSelection)
start->setDisabled(true);
//Add it to context menu
menu.addAction(start);
//Connect the signal to signal mapper
connect(start, &QAction::triggered, &signalMapper, QOverload<>::of(&QSignalMapper::map));
//Add a new mapping
signalMapper.setMapping(start, defaultApplicationIndex);
connect(&signalMapper, SIGNAL(mapped(int)),
this, SLOT(context(int)));
}
// Add popup menuitems
if (mContextItem) {
if (mApplications->getApplicationCount() > 0) {
menu.addSeparator();
}
//Create an action for the application
auto *recheckAction = new QAction(tr("Recheck"), &menu);
auto *copyAction = new QAction(tr("Copy"), &menu);
auto *hide = new QAction(tr("Hide"), &menu);
auto *hideallid = new QAction(tr("Hide all with id"), &menu);
auto *opencontainingfolder = new QAction(tr("Open containing folder"), &menu);
if (multipleSelection) {
hideallid->setDisabled(true);
opencontainingfolder->setDisabled(true);
}
if (mThread->isChecking())
recheckAction->setDisabled(true);
else
recheckAction->setDisabled(false);
menu.addAction(recheckAction);
menu.addSeparator();
menu.addAction(copyAction);
menu.addSeparator();
menu.addAction(hide);
menu.addAction(hideallid);
auto *suppress = new QAction(tr("Suppress selected id(s)"), &menu);
{
QVariantMap itemdata = mContextItem->data().toMap();
const QString messageId = itemdata[ERRORID].toString();
suppress->setEnabled(!ErrorLogger::isCriticalErrorId(messageId.toStdString()));
}
menu.addAction(suppress);
connect(suppress, &QAction::triggered, this, &ResultsTree::suppressSelectedIds);
menu.addSeparator();
menu.addAction(opencontainingfolder);
connect(recheckAction, &QAction::triggered, this, &ResultsTree::recheckSelectedFiles);
connect(copyAction, &QAction::triggered, this, &ResultsTree::copy);
connect(hide, &QAction::triggered, this, &ResultsTree::hideResult);
connect(hideallid, &QAction::triggered, this, &ResultsTree::hideAllIdResult);
connect(opencontainingfolder, &QAction::triggered, this, &ResultsTree::openContainingFolder);
const ProjectFile *currentProject = ProjectFile::getActiveProject();
if (currentProject && !currentProject->getTags().isEmpty()) {
menu.addSeparator();
QMenu *tagMenu = menu.addMenu(tr("Tag"));
{
auto *action = new QAction(tr("No tag"), tagMenu);
tagMenu->addAction(action);
connect(action, &QAction::triggered, [=]() {
tagSelectedItems(QString());
});
}
for (const QString& tagstr : currentProject->getTags()) {
auto *action = new QAction(tagstr, tagMenu);
tagMenu->addAction(action);
connect(action, &QAction::triggered, [=]() {
tagSelectedItems(tagstr);
});
}
}
}
//Start the menu
menu.exec(e->globalPos());
index = indexAt(e->pos());
if (index.isValid()) {
mContextItem = mModel.itemFromIndex(index);
}
}
}
void ResultsTree::startApplication(const QStandardItem *target, int application)
{
//If there are no applications specified, tell the user about it
if (mApplications->getApplicationCount() == 0) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("No editor application configured.\n\n"
"Configure the editor application for Cppcheck in preferences/Applications."),
QMessageBox::Ok,
this);
msg.exec();
return;
}
if (application == -1)
application = mApplications->getDefaultApplication();
if (application == -1) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("No default editor application selected.\n\n"
"Please select the default editor application in preferences/Applications."),
QMessageBox::Ok,
this);
msg.exec();
return;
}
if (target && application >= 0 && application < mApplications->getApplicationCount() && target->parent()) {
// Make sure we are working with the first column
if (target->column() != 0)
target = target->parent()->child(target->row(), 0);
QVariantMap targetdata = target->data().toMap();
//Replace (file) with filename
QString file = targetdata[FILENAME].toString();
file = QDir::toNativeSeparators(file);
qDebug() << "Opening file: " << file;
QFileInfo info(file);
if (!info.exists()) {
if (info.isAbsolute()) {
QMessageBox msgbox(this);
msgbox.setWindowTitle("Cppcheck");
msgbox.setText(tr("Could not find the file!"));
msgbox.setIcon(QMessageBox::Critical);
msgbox.exec();
} else {
QDir checkdir(mCheckPath);
if (checkdir.isAbsolute() && checkdir.exists()) {
file = mCheckPath + "/" + file;
} else {
QString dir = askFileDir(file);
dir += '/';
file = dir + file;
}
}
}
if (file.indexOf(" ") > -1) {
file.insert(0, "\"");
file.append("\"");
}
const Application& app = mApplications->getApplication(application);
QString params = app.getParameters();
params.replace("(file)", file, Qt::CaseInsensitive);
QVariant line = targetdata[LINE];
params.replace("(line)", QString("%1").arg(line.toInt()), Qt::CaseInsensitive);
params.replace("(message)", targetdata[MESSAGE].toString(), Qt::CaseInsensitive);
params.replace("(severity)", targetdata[SEVERITY].toString(), Qt::CaseInsensitive);
QString program = app.getPath();
// In Windows we must surround paths including spaces with quotation marks.
#ifdef Q_OS_WIN
if (program.indexOf(" ") > -1) {
if (!program.startsWith('"') && !program.endsWith('"')) {
program.insert(0, "\"");
program.append("\"");
}
}
#endif // Q_OS_WIN
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
const QString cmdLine = QString("%1 %2").arg(program).arg(params);
#endif
// this is reported as deprecated in Qt 5.15.2 but no longer in Qt 6
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
SUPPRESS_WARNING_CLANG_PUSH("-Wdeprecated")
SUPPRESS_WARNING_GCC_PUSH("-Wdeprecated-declarations")
#endif
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
const bool success = QProcess::startDetached(cmdLine);
#else
const bool success = QProcess::startDetached(program, QProcess::splitCommand(params));
#endif
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
SUPPRESS_WARNING_GCC_POP
SUPPRESS_WARNING_CLANG_POP
#endif
if (!success) {
QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(program);
QMessageBox msgbox(this);
msgbox.setWindowTitle("Cppcheck");
msgbox.setText(text);
msgbox.setIcon(QMessageBox::Critical);
msgbox.exec();
}
}
}
QString ResultsTree::askFileDir(const QString &file)
{
QString text = tr("Could not find file:") + '\n' + file + '\n';
QString title;
if (file.indexOf('/')) {
QString folderName = file.mid(0, file.indexOf('/'));
text += tr("Please select the folder '%1'").arg(folderName);
title = tr("Select Directory '%1'").arg(folderName);
} else {
text += tr("Please select the directory where file is located.");
title = tr("Select Directory");
}
QMessageBox msgbox(this);
msgbox.setWindowTitle("Cppcheck");
msgbox.setText(text);
msgbox.setIcon(QMessageBox::Warning);
msgbox.exec();
QString dir = QFileDialog::getExistingDirectory(this, title,
getPath(SETTINGS_LAST_SOURCE_PATH),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir.isEmpty())
return QString();
// User selected root path
if (QFileInfo::exists(dir + '/' + file))
mCheckPath = dir;
// user selected checked folder
else if (file.indexOf('/') > 0) {
dir += '/';
QString folderName = file.mid(0, file.indexOf('/'));
if (dir.indexOf('/' + folderName + '/'))
dir = dir.mid(0, dir.lastIndexOf('/' + folderName + '/'));
if (QFileInfo::exists(dir + '/' + file))
mCheckPath = dir;
}
// Otherwise; return
else
return QString();
setPath(SETTINGS_LAST_SOURCE_PATH, mCheckPath);
return mCheckPath;
}
void ResultsTree::copy()
{
if (!mSelectionModel)
return;
QString text;
for (const QModelIndex& index : mSelectionModel->selectedRows()) {
const QStandardItem *item = mModel.itemFromIndex(index);
if (!item->parent()) {
text += item->text() + '\n';
continue;
}
if (item->parent()->parent())
item = item->parent();
QVariantMap itemdata = item->data().toMap();
if (!itemdata.contains("id"))
continue;
QString inconclusive = itemdata[INCONCLUSIVE].toBool() ? ",inconclusive" : "";
text += itemdata[FILENAME].toString() + ':' + QString::number(itemdata[LINE].toInt()) + ':' + QString::number(itemdata[COLUMN].toInt())
+ ": "
+ QString::fromStdString(severityToString(ShowTypes::ShowTypeToSeverity((ShowTypes::ShowType)itemdata[SEVERITY].toInt()))) + inconclusive
+ ": "
+ itemdata[MESSAGE].toString()
+ " ["
+ itemdata[ERRORID].toString()
+ "]\n";
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(text);
}
void ResultsTree::hideResult()
{
if (!mSelectionModel)
return;
for (QModelIndex index : mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
//Set the "hide" flag for this item
QVariantMap itemdata = item->data().toMap();
itemdata[HIDE] = true;
item->setData(QVariant(itemdata));
refreshTree();
emit resultsHidden(true);
}
}
void ResultsTree::recheckSelectedFiles()
{
if (!mSelectionModel)
return;
QStringList selectedItems;
for (QModelIndex index : mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
while (item->parent())
item = item->parent();
QVariantMap itemdata = item->data().toMap();
QString currentFile = itemdata[FILENAME].toString();
if (!currentFile.isEmpty()) {
QString fileNameWithCheckPath;
QFileInfo curfileInfo(currentFile);
if (!curfileInfo.exists() && !mCheckPath.isEmpty() && currentFile.indexOf(mCheckPath) != 0)
fileNameWithCheckPath = mCheckPath + "/" + currentFile;
else
fileNameWithCheckPath = currentFile;
const QFileInfo fileInfo(fileNameWithCheckPath);
if (!fileInfo.exists()) {
askFileDir(currentFile);
return;
}
if (Path::isHeader(currentFile.toStdString())) {
if (!itemdata[FILE0].toString().isEmpty() && !selectedItems.contains(itemdata[FILE0].toString())) {
selectedItems<<((!mCheckPath.isEmpty() && (itemdata[FILE0].toString().indexOf(mCheckPath) != 0)) ? (mCheckPath + "/" + itemdata[FILE0].toString()) : itemdata[FILE0].toString());
if (!selectedItems.contains(fileNameWithCheckPath))
selectedItems<<fileNameWithCheckPath;
}
} else if (!selectedItems.contains(fileNameWithCheckPath))
selectedItems<<fileNameWithCheckPath;
}
}
emit checkSelected(std::move(selectedItems));
}
void ResultsTree::hideAllIdResult()
{
if (!mContextItem || !mContextItem->parent())
return;
// Make sure we are working with the first column
if (mContextItem->column() != 0)
mContextItem = mContextItem->parent()->child(mContextItem->row(), 0);
QVariantMap itemdata = mContextItem->data().toMap();
QString messageId = itemdata[ERRORID].toString();
mHiddenMessageId.append(messageId);
refreshTree();
emit resultsHidden(true);
}
void ResultsTree::suppressSelectedIds()
{
if (!mSelectionModel)
return;
QSet<QString> selectedIds;
for (QModelIndex index : mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
if (!item->parent())
continue;
if (item->parent()->parent())
item = item->parent();
QVariantMap itemdata = item->data().toMap();
if (!itemdata.contains("id"))
continue;
selectedIds << itemdata[ERRORID].toString();
}
// delete all errors with selected message Ids
for (int i = 0; i < mModel.rowCount(); i++) {
QStandardItem * const file = mModel.item(i, 0);
for (int j = 0; j < file->rowCount();) {
QStandardItem *errorItem = file->child(j, 0);
QVariantMap userdata = errorItem->data().toMap();
if (selectedIds.contains(userdata[ERRORID].toString())) {
file->removeRow(j);
} else {
j++;
}
}
if (file->rowCount() == 0)
mModel.removeRow(file->row());
}
emit suppressIds(selectedIds.values());
}
void ResultsTree::suppressHash()
{
if (!mSelectionModel)
return;
// Extract selected warnings
QSet<QStandardItem *> selectedWarnings;
for (QModelIndex index : mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
if (!item->parent())
continue;
while (item->parent()->parent())
item = item->parent();
selectedWarnings.insert(item);
}
bool changed = false;
ProjectFile *projectFile = ProjectFile::getActiveProject();
for (QStandardItem *item: selectedWarnings) {
QStandardItem *fileItem = item->parent();
const QVariantMap itemdata = item->data().toMap();
if (projectFile && itemdata.contains(HASH)) {
SuppressionList::Suppression suppression;
suppression.hash = itemdata[HASH].toULongLong();
suppression.errorId = itemdata[ERRORID].toString().toStdString();
suppression.fileName = itemdata[FILENAME].toString().toStdString();
suppression.lineNumber = itemdata[LINE].toInt();
projectFile->addSuppression(suppression);
changed = true;
}
fileItem->removeRow(item->row());
if (fileItem->rowCount() == 0)
mModel.removeRow(fileItem->row());
}
if (changed)
projectFile->write();
}
void ResultsTree::openContainingFolder()
{
QString filePath = getFilePath(mContextItem, true);
if (!filePath.isEmpty()) {
filePath = QFileInfo(filePath).absolutePath();
QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}
}
void ResultsTree::tagSelectedItems(const QString &tag)
{
if (!mSelectionModel)
return;
bool isTagged = false;
ProjectFile *currentProject = ProjectFile::getActiveProject();
for (QModelIndex index : mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
QVariantMap itemdata = item->data().toMap();
if (itemdata.contains("tags")) {
itemdata[TAGS] = tag;
item->setData(QVariant(itemdata));
item->parent()->child(index.row(), COLUMN_TAGS)->setText(tag);
if (currentProject && itemdata.contains(HASH)) {
isTagged = true;
currentProject->setWarningTags(itemdata[HASH].toULongLong(), tag);
}
}
}
if (isTagged)
currentProject->write();
}
void ResultsTree::context(int application)
{
startApplication(mContextItem, application);
}
void ResultsTree::quickStartApplication(const QModelIndex &index)
{
startApplication(mModel.itemFromIndex(index));
}
QString ResultsTree::getFilePath(const QStandardItem *target, bool fullPath)
{
if (target) {
// Make sure we are working with the first column
if (target->column() != 0)
target = target->parent()->child(target->row(), 0);
QVariantMap targetdata = target->data().toMap();
//Replace (file) with filename
QString file = targetdata[FILENAME].toString();
QString pathStr = QDir::toNativeSeparators(file);
if (!fullPath) {
QFileInfo fi(pathStr);
pathStr = fi.fileName();
}
return pathStr;
}
return QString();
}
QString ResultsTree::severityToIcon(Severity severity)
{
switch (severity) {
case Severity::error:
return ":images/dialog-error.png";
case Severity::style:
return ":images/applications-development.png";
case Severity::warning:
return ":images/dialog-warning.png";
case Severity::portability:
return ":images/applications-system.png";
case Severity::performance:
return ":images/utilities-system-monitor.png";
case Severity::information:
return ":images/dialog-information.png";
default:
return QString();
}
}
void ResultsTree::saveResults(Report *report) const
{
report->writeHeader();
for (int i = 0; i < mModel.rowCount(); i++) {
if (mSaveAllErrors || !isRowHidden(i, QModelIndex()))
saveErrors(report, mModel.item(i, 0));
}
report->writeFooter();
}
void ResultsTree::saveErrors(Report *report, const QStandardItem *fileItem) const
{
if (!fileItem) {
return;
}
for (int i = 0; i < fileItem->rowCount(); i++) {
const QStandardItem *error = fileItem->child(i, 0);
if (!error) {
continue;
}
if (isRowHidden(i, fileItem->index()) && !mSaveAllErrors) {
continue;
}
ErrorItem item;
readErrorItem(error, &item);
report->writeError(item);
}
}
static int indexOf(const QList<ErrorItem> &list, const ErrorItem &item)
{
for (int i = 0; i < list.size(); i++) {
if (ErrorItem::sameCID(item, list[i])) {
return i;
}
}
return -1;
}
void ResultsTree::updateFromOldReport(const QString &filename)
{
showColumn(COLUMN_SINCE_DATE);
QList<ErrorItem> oldErrors;
XmlReportV2 oldReport(filename, QString());
if (oldReport.open()) {
oldErrors = oldReport.read();
oldReport.close();
}
// Read current results..
for (int i = 0; i < mModel.rowCount(); i++) {
QStandardItem *fileItem = mModel.item(i,0);
for (int j = 0; j < fileItem->rowCount(); j++) {
QStandardItem *error = fileItem->child(j,0);
ErrorItem errorItem;
readErrorItem(error, &errorItem);
const int oldErrorIndex = indexOf(oldErrors, errorItem);
QVariantMap errordata = error->data().toMap();
// New error .. set the "sinceDate" property
if (oldErrorIndex >= 0 && !oldErrors[oldErrorIndex].sinceDate.isEmpty()) {
errordata[SINCEDATE] = oldErrors[oldErrorIndex].sinceDate;
error->setData(errordata);
fileItem->child(j, COLUMN_SINCE_DATE)->setText(oldErrors[oldErrorIndex].sinceDate);
} else if (oldErrorIndex < 0 || errordata[SINCEDATE].toString().isEmpty()) {
const QString sinceDate = QLocale::system().toString(QDate::currentDate(), QLocale::ShortFormat);
errordata[SINCEDATE] = sinceDate;
error->setData(errordata);
fileItem->child(j, COLUMN_SINCE_DATE)->setText(sinceDate);
if (oldErrorIndex < 0)
continue;
}
if (!errorItem.tags.isEmpty())
continue;
const ErrorItem &oldErrorItem = oldErrors[oldErrorIndex];
errordata[TAGS] = oldErrorItem.tags;
error->setData(errordata);
}
}
}
void ResultsTree::readErrorItem(const QStandardItem *error, ErrorItem *item) const
{
// Get error's user data
QVariantMap errordata = error->data().toMap();
item->severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(errordata[SEVERITY]));
item->summary = errordata[SUMMARY].toString();
item->message = errordata[MESSAGE].toString();
item->errorId = errordata[ERRORID].toString();
item->cwe = errordata[CWE].toInt();
item->hash = errordata[HASH].toULongLong();
item->inconclusive = errordata[INCONCLUSIVE].toBool();
item->file0 = errordata[FILE0].toString();
item->sinceDate = errordata[SINCEDATE].toString();
item->tags = errordata[TAGS].toString();
item->remark = errordata[REMARK].toString();
item->classification = error->parent()->child(error->row(), COLUMN_MISRA_CLASSIFICATION)->text();
item->guideline = error->parent()->child(error->row(), COLUMN_MISRA_GUIDELINE)->text();
if (error->rowCount() == 0) {
QErrorPathItem e;
e.file = stripPath(errordata[FILENAME].toString(), true);
e.line = errordata[LINE].toInt();
e.info = errordata[MESSAGE].toString();
item->errorPath << e;
}
for (int j = 0; j < error->rowCount(); j++) {
const QStandardItem *child_error = error->child(j, 0);
//Get error's user data
QVariant child_userdata = child_error->data();
//Convert it to QVariantMap
QVariantMap child_data = child_userdata.toMap();
QErrorPathItem e;
e.file = stripPath(child_data[FILENAME].toString(), true);
e.line = child_data[LINE].toInt();
e.info = child_data[MESSAGE].toString();
item->errorPath << e;
}
}
void ResultsTree::updateSettings(bool showFullPath,
bool saveFullPath,
bool saveAllErrors,
bool showErrorId,
bool showInconclusive)
{
if (mShowFullPath != showFullPath) {
mShowFullPath = showFullPath;
refreshFilePaths();
}
mSaveFullPath = saveFullPath;
mSaveAllErrors = saveAllErrors;
showIdColumn(showErrorId);
showInconclusiveColumn(showInconclusive);
}
void ResultsTree::setCheckDirectory(const QString &dir)
{
mCheckPath = dir;
}
const QString& ResultsTree::getCheckDirectory()
{
return mCheckPath;
}
QString ResultsTree::stripPath(const QString &path, bool saving) const
{
if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) {
return QString(path);
}
QDir dir(mCheckPath);
return dir.relativeFilePath(path);
}
void ResultsTree::refreshFilePaths(QStandardItem *item)
{
if (!item) {
return;
}
//Mark that this file's path hasn't been updated yet
bool updated = false;
//Loop through all errors within this file
for (int i = 0; i < item->rowCount(); i++) {
//Get error i
QStandardItem *error = item->child(i, 0);
if (!error) {
continue;
}
//Get error's user data and convert it to QVariantMap
QVariantMap userdata = error->data().toMap();
//Get list of files
QString file = userdata[FILENAME].toString();
//Update this error's text
error->setText(stripPath(file, false));
//If this error has backtraces make sure the files list has enough filenames
if (error->hasChildren()) {
//Loop through all files within the error
for (int j = 0; j < error->rowCount(); j++) {
//Get file
QStandardItem *child = error->child(j, 0);
if (!child) {
continue;
}
//Get child's user data
QVariant child_userdata = child->data();
//Convert it to QVariantMap
QVariantMap child_data = child_userdata.toMap();
//Get list of files
QString child_files = child_data[FILENAME].toString();
//Update file's path
child->setText(stripPath(child_files, false));
}
}
//if the main file hasn't been updated yet, update it now
if (!updated) {
updated = true;
item->setText(error->text());
}
}
}
void ResultsTree::refreshFilePaths()
{
qDebug("Refreshing file paths");
//Go through all file items (these are parent items that contain the errors)
for (int i = 0; i < mModel.rowCount(); i++) {
refreshFilePaths(mModel.item(i, 0));
}
}
bool ResultsTree::hasVisibleResults() const
{
return mVisibleErrors;
}
bool ResultsTree::hasResults() const
{
return mModel.rowCount() > 0;
}
void ResultsTree::translate()
{
mModel.setHorizontalHeaderLabels(getLabels());
//TODO go through all the errors in the tree and translate severity and message
}
void ResultsTree::showIdColumn(bool show)
{
mShowErrorId = show;
if (show)
showColumn(COLUMN_ID);
else
hideColumn(COLUMN_ID);
}
void ResultsTree::showInconclusiveColumn(bool show)
{
if (show)
showColumn(COLUMN_INCONCLUSIVE);
else
hideColumn(COLUMN_INCONCLUSIVE);
}
void ResultsTree::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
QTreeView::currentChanged(current, previous);
emit treeSelectionChanged(current);
}
| 56,369
|
C++
|
.cpp
| 1,419
| 31.174771
| 197
| 0.613819
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,321
|
checkstatistics.cpp
|
danmar_cppcheck/gui/checkstatistics.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkstatistics.h"
#include <QDebug>
#include <QList>
#include <QSet>
CheckStatistics::CheckStatistics(QObject *parent)
: QObject(parent)
{
clear();
}
static void addItem(QMap<QString,unsigned> &m, const QString &key)
{
if (m.contains(key))
m[key]++;
else
m[key] = 0;
}
void CheckStatistics::addItem(const QString &tool, ShowTypes::ShowType type)
{
const QString lower = tool.toLower();
switch (type) {
case ShowTypes::ShowStyle:
::addItem(mStyle, lower);
break;
case ShowTypes::ShowWarnings:
::addItem(mWarning, lower);
break;
case ShowTypes::ShowPerformance:
::addItem(mPerformance, lower);
break;
case ShowTypes::ShowPortability:
::addItem(mPortability, lower);
break;
case ShowTypes::ShowErrors:
::addItem(mError, lower);
break;
case ShowTypes::ShowInformation:
::addItem(mInformation, lower);
break;
case ShowTypes::ShowNone:
default:
qDebug() << "Unknown error type - not added to statistics.";
break;
}
}
void CheckStatistics::addChecker(const QString &checker)
{
mActiveCheckers.insert(checker.toStdString());
}
void CheckStatistics::clear()
{
mStyle.clear();
mWarning.clear();
mPerformance.clear();
mPortability.clear();
mInformation.clear();
mError.clear();
mActiveCheckers.clear();
mCheckersReport.clear();
}
unsigned CheckStatistics::getCount(const QString &tool, ShowTypes::ShowType type) const
{
const QString lower = tool.toLower();
switch (type) {
case ShowTypes::ShowStyle:
return mStyle.value(lower,0);
case ShowTypes::ShowWarnings:
return mWarning.value(lower,0);
case ShowTypes::ShowPerformance:
return mPerformance.value(lower,0);
case ShowTypes::ShowPortability:
return mPortability.value(lower,0);
case ShowTypes::ShowErrors:
return mError.value(lower,0);
case ShowTypes::ShowInformation:
return mInformation.value(lower,0);
case ShowTypes::ShowNone:
default:
qDebug() << "Unknown error type - returning zero statistics.";
return 0;
}
}
QStringList CheckStatistics::getTools() const
{
QSet<QString> ret;
for (const QString& tool: mStyle.keys()) ret.insert(tool);
for (const QString& tool: mWarning.keys()) ret.insert(tool);
for (const QString& tool: mPerformance.keys()) ret.insert(tool);
for (const QString& tool: mPortability.keys()) ret.insert(tool);
for (const QString& tool: mError.keys()) ret.insert(tool);
return ret.values();
}
| 3,388
|
C++
|
.cpp
| 108
| 26.805556
| 87
| 0.694283
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,323
|
helpdialog.cpp
|
danmar_cppcheck/gui/helpdialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "helpdialog.h"
#include "common.h"
#include "ui_helpdialog.h"
#include <QApplication>
#include <QFileInfo>
#include <QHelpEngine>
#include <QHelpContentWidget>
#include <QHelpIndexWidget>
#include <QMessageBox>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <QVBoxLayout>
class QWidget;
void HelpBrowser::setHelpEngine(QHelpEngine *helpEngine)
{
mHelpEngine = helpEngine;
}
QVariant HelpBrowser::loadResource(int type, const QUrl &name)
{
if (name.scheme() == "qthelp") {
QString url(name.toString());
while (url.indexOf("/./") > 0)
url.remove(url.indexOf("/./"), 2);
return QVariant(mHelpEngine->fileData(QUrl(url)));
}
return QTextBrowser::loadResource(type, name);
}
static QString getHelpFile()
{
const QString datadir = getDataDir();
QStringList paths;
paths << (datadir + "/help")
<< datadir
<< (QApplication::applicationDirPath() + "/help")
<< QApplication::applicationDirPath();
#ifdef FILESDIR
const QString filesdir = FILESDIR;
paths << (filesdir + "/help")
<< filesdir;
#endif
for (const QString &p: paths) {
QString filename = p + "/online-help.qhc";
if (QFileInfo::exists(filename))
return filename;
}
return QString();
}
HelpDialog::HelpDialog(QWidget *parent) :
QDialog(parent),
mUi(new Ui::HelpDialog)
{
mUi->setupUi(this);
QString helpFile = getHelpFile();
if (helpFile.isEmpty()) {
const QString msg = tr("Helpfile '%1' was not found").arg("online-help.qhc");
QMessageBox msgBox(QMessageBox::Warning,
tr("Cppcheck"),
msg,
QMessageBox::Ok,
this);
msgBox.exec();
mHelpEngine = nullptr;
return;
}
mHelpEngine = new QHelpEngine(helpFile);
// Disable the timestamp check of online-help.qhc by setting _q_readonly
mHelpEngine->setProperty("_q_readonly", QVariant::fromValue<bool>(true));
mHelpEngine->setupData();
mUi->contents->addWidget(mHelpEngine->contentWidget());
mUi->index->addWidget(mHelpEngine->indexWidget());
mUi->textBrowser->setHelpEngine(mHelpEngine);
mUi->textBrowser->setSource(QUrl("qthelp://cppcheck.sourceforge.io/doc/index.html"));
connect(mHelpEngine->contentWidget(),
SIGNAL(linkActivated(QUrl)),
mUi->textBrowser,
SLOT(setSource(QUrl)));
connect(mHelpEngine->indexWidget(),
SIGNAL(linkActivated(QUrl,QString)),
mUi->textBrowser,
SLOT(setSource(QUrl)));
}
HelpDialog::~HelpDialog()
{
delete mUi;
delete mHelpEngine;
}
| 3,493
|
C++
|
.cpp
| 104
| 28
| 89
| 0.66637
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,325
|
checkthread.cpp
|
danmar_cppcheck/gui/checkthread.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkthread.h"
#include "analyzerinfo.h"
#include "common.h"
#include "cppcheck.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "settings.h"
#include "standards.h"
#include "threadresult.h"
#include "utils.h"
#include <algorithm>
#include <fstream>
#include <iterator>
#include <list>
#include <set>
#include <string>
#include <vector>
#include <QByteArray>
#include <QChar>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QIODevice>
#include <QProcess>
#include <QRegularExpression>
#include <QSettings>
#include <QTextStream>
#include <QVariant>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QCharRef>
#endif
static QString unquote(QString s) {
if (s.startsWith("\""))
s = s.mid(1, s.size() - 2);
return s;
}
// NOLINTNEXTLINE(performance-unnecessary-value-param) - used as callback so we need to preserve the signature
int CheckThread::executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output) // cppcheck-suppress passedByValue
{
output.clear();
QStringList args2;
for (const std::string &arg: args)
args2 << QString::fromStdString(arg);
QProcess process;
QString e = unquote(QString::fromStdString(exe));
if (e.toLower().replace("\\", "/").endsWith("/python.exe") && !args.empty()) {
const QString path = e.left(e.size()-11);
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("PYTHONPATH", path + "/Lib/site-packages");
env.insert("PYTHONHOME", path);
process.setProcessEnvironment(env);
const QString pythonScript = unquote(args2[0]);
if (pythonScript.endsWith(".py")) {
const QString path2 = pythonScript.left(QString(pythonScript).replace('\\', '/').lastIndexOf("/"));
process.setWorkingDirectory(path2);
}
}
process.start(e, args2);
process.waitForFinished();
if (redirect == "2>&1") {
QString s1 = process.readAllStandardOutput();
QString s2 = process.readAllStandardError();
output = (s1 + "\n" + s2).toStdString();
} else
output = process.readAllStandardOutput().toStdString();
if (startsWith(redirect, "2> ")) {
std::ofstream fout(redirect.substr(3));
fout << process.readAllStandardError().toStdString();
}
return process.exitCode();
}
CheckThread::CheckThread(ThreadResult &result) :
mResult(result),
mCppcheck(result, true, executeCommand)
{}
void CheckThread::check(const Settings &settings)
{
mFiles.clear();
mCppcheck.settings() = settings;
start();
}
void CheckThread::analyseWholeProgram(const QStringList &files, const std::string& ctuInfo)
{
mFiles = files;
mAnalyseWholeProgram = true;
mCtuInfo = ctuInfo;
start();
}
// cppcheck-suppress unusedFunction - TODO: false positive
void CheckThread::run()
{
mState = Running;
if (!mFiles.isEmpty() || mAnalyseWholeProgram) {
mAnalyseWholeProgram = false;
std::string ctuInfo;
ctuInfo.swap(mCtuInfo);
qDebug() << "Whole program analysis";
std::list<FileWithDetails> files2;
std::transform(mFiles.cbegin(), mFiles.cend(), std::back_inserter(files2), [&](const QString& file) {
return FileWithDetails{file.toStdString(), 0};
});
mCppcheck.analyseWholeProgram(mCppcheck.settings().buildDir, files2, {}, ctuInfo);
mFiles.clear();
emit done();
return;
}
QString file = mResult.getNextFile();
while (!file.isEmpty() && mState == Running) {
qDebug() << "Checking file" << file;
mCppcheck.check(FileWithDetails(file.toStdString()));
runAddonsAndTools(nullptr, file);
emit fileChecked(file);
if (mState == Running)
file = mResult.getNextFile();
}
const FileSettings* fileSettings = nullptr;
mResult.getNextFileSettings(fileSettings);
while (fileSettings && mState == Running) {
file = QString::fromStdString(fileSettings->filename());
qDebug() << "Checking file" << file;
mCppcheck.check(*fileSettings);
runAddonsAndTools(fileSettings, QString::fromStdString(fileSettings->filename()));
emit fileChecked(file);
if (mState == Running)
mResult.getNextFileSettings(fileSettings);
}
if (mState == Running)
mState = Ready;
else
mState = Stopped;
emit done();
}
void CheckThread::runAddonsAndTools(const FileSettings *fileSettings, const QString &fileName)
{
for (const QString& addon : mAddonsAndTools) {
if (addon == CLANG_ANALYZER || addon == CLANG_TIDY) {
if (!fileSettings)
continue;
if (!fileSettings->cfg.empty() && !startsWith(fileSettings->cfg,"Debug"))
continue;
QStringList args;
for (std::list<std::string>::const_iterator incIt = fileSettings->includePaths.cbegin(); incIt != fileSettings->includePaths.cend(); ++incIt)
args << ("-I" + QString::fromStdString(*incIt));
for (std::list<std::string>::const_iterator i = fileSettings->systemIncludePaths.cbegin(); i != fileSettings->systemIncludePaths.cend(); ++i)
args << "-isystem" << QString::fromStdString(*i);
for (const QString& def : QString::fromStdString(fileSettings->defines).split(";")) {
args << ("-D" + def);
}
for (const std::string& U : fileSettings->undefs) {
args << QString::fromStdString("-U" + U);
}
const QString clangPath = CheckThread::clangTidyCmd();
if (!clangPath.isEmpty()) {
QDir dir(clangPath + "/../lib/clang");
for (const QString& ver : dir.entryList()) {
QString includePath = dir.absolutePath() + '/' + ver + "/include";
if (ver[0] != '.' && QDir(includePath).exists()) {
args << "-isystem" << includePath;
break;
}
}
}
#ifdef Q_OS_WIN
// To create compile_commands.json in windows see:
// https://bitsmaker.gitlab.io/post/clang-tidy-from-vs2015/
for (QString includePath : mClangIncludePaths) {
if (!includePath.isEmpty()) {
includePath.replace("\\", "/");
args << "-isystem" << includePath.trimmed();
}
}
args << "-U__STDC__" << "-fno-ms-compatibility";
#endif
if (!fileSettings->standard.empty())
args << ("-std=" + QString::fromStdString(fileSettings->standard));
else {
// TODO: pass C or C++ standard based on file type
const std::string std = mCppcheck.settings().standards.getCPP();
if (!std.empty()) {
args << ("-std=" + QString::fromStdString(std));
}
}
QString analyzerInfoFile;
const std::string &buildDir = mCppcheck.settings().buildDir;
if (!buildDir.empty()) {
analyzerInfoFile = QString::fromStdString(AnalyzerInformation::getAnalyzerInfoFile(buildDir, fileSettings->filename(), fileSettings->cfg));
QStringList args2(args);
args2.insert(0,"-E");
args2 << fileName;
QProcess process;
process.start(clangCmd(),args2);
process.waitForFinished();
const QByteArray &ba = process.readAllStandardOutput();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
const quint16 chksum = qChecksum(QByteArrayView(ba));
#else
const quint16 chksum = qChecksum(ba.data(), ba.length());
#endif
QFile f1(analyzerInfoFile + '.' + addon + "-E");
if (f1.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in1(&f1);
const quint16 oldchksum = in1.readAll().toInt();
if (oldchksum == chksum) {
QFile f2(analyzerInfoFile + '.' + addon + "-results");
if (f2.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in2(&f2);
parseClangErrors(addon, fileName, in2.readAll());
continue;
}
}
f1.close();
}
f1.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out1(&f1);
out1 << chksum;
QFile::remove(analyzerInfoFile + '.' + addon + "-results");
}
if (addon == CLANG_ANALYZER) {
/*
// Using clang
args.insert(0,"--analyze");
args.insert(1, "-Xanalyzer");
args.insert(2, "-analyzer-output=text");
args << fileName;
*/
// Using clang-tidy
args.insert(0,"-checks=-*,clang-analyzer-*");
args.insert(1, fileName);
args.insert(2, "--");
} else {
args.insert(0,"-checks=*,-clang-analyzer-*,-llvm*");
args.insert(1, fileName);
args.insert(2, "--");
}
{
const QString cmd(clangTidyCmd());
QString debug(cmd.contains(" ") ? ('\"' + cmd + '\"') : cmd);
for (const QString& arg : args) {
if (arg.contains(" "))
debug += " \"" + arg + '\"';
else
debug += ' ' + arg;
}
qDebug() << debug;
if (!analyzerInfoFile.isEmpty()) {
QFile f(analyzerInfoFile + '.' + addon + "-cmd");
if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&f);
out << debug;
}
}
}
QProcess process;
process.start(clangTidyCmd(), args);
process.waitForFinished(600*1000);
const QString errout(process.readAllStandardOutput() + "\n\n\n" + process.readAllStandardError());
if (!analyzerInfoFile.isEmpty()) {
QFile f(analyzerInfoFile + '.' + addon + "-results");
if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&f);
out << errout;
}
}
parseClangErrors(addon, fileName, errout);
}
}
}
void CheckThread::stop()
{
mState = Stopping;
Settings::terminate();
}
void CheckThread::parseClangErrors(const QString &tool, const QString &file0, QString err)
{
QList<ErrorItem> errorItems;
ErrorItem errorItem;
static const QRegularExpression r1("^(.+):([0-9]+):([0-9]+): (note|warning|error|fatal error): (.*)$");
static const QRegularExpression r2("^(.*)\\[([a-zA-Z0-9\\-_\\.]+)\\]$");
QTextStream in(&err, QIODevice::ReadOnly);
while (!in.atEnd()) {
QString line = in.readLine();
if (line.startsWith("Assertion failed:")) {
ErrorItem e;
e.errorPath.append(QErrorPathItem());
e.errorPath.last().file = file0;
e.errorPath.last().line = 1;
e.errorPath.last().column = 1;
e.errorId = tool + "-internal-error";
e.file0 = file0;
e.message = line;
e.severity = Severity::information;
errorItems.append(e);
continue;
}
const QRegularExpressionMatch r1MatchRes = r1.match(line);
if (!r1MatchRes.hasMatch())
continue;
if (r1MatchRes.captured(4) != "note") {
errorItems.append(errorItem);
errorItem = ErrorItem();
errorItem.file0 = r1MatchRes.captured(1);
}
errorItem.errorPath.append(QErrorPathItem());
errorItem.errorPath.last().file = r1MatchRes.captured(1);
errorItem.errorPath.last().line = r1MatchRes.captured(2).toInt();
errorItem.errorPath.last().column = r1MatchRes.captured(3).toInt();
if (r1MatchRes.captured(4) == "warning")
errorItem.severity = Severity::warning;
else if (r1MatchRes.captured(4) == "error" || r1MatchRes.captured(4) == "fatal error")
errorItem.severity = Severity::error;
QString message,id;
const QRegularExpressionMatch r2MatchRes = r2.match(r1MatchRes.captured(5));
if (r2MatchRes.hasMatch()) {
message = r2MatchRes.captured(1);
const QString id1(r2MatchRes.captured(2));
if (id1.startsWith("clang"))
id = id1;
else
id = tool + '-' + r2MatchRes.captured(2);
if (tool == CLANG_TIDY) {
if (id1.startsWith("performance"))
errorItem.severity = Severity::performance;
else if (id1.startsWith("portability"))
errorItem.severity = Severity::portability;
else if (id1.startsWith("misc") && !id1.contains("unused"))
errorItem.severity = Severity::warning;
else
errorItem.severity = Severity::style;
}
} else {
message = r1MatchRes.captured(5);
id = CLANG_ANALYZER;
}
if (errorItem.errorPath.size() == 1) {
errorItem.message = message;
errorItem.errorId = id;
}
errorItem.errorPath.last().info = message;
}
errorItems.append(errorItem);
for (const ErrorItem &e : errorItems) {
if (e.errorPath.isEmpty())
continue;
SuppressionList::ErrorMessage errorMessage;
errorMessage.setFileName(e.errorPath.back().file.toStdString());
errorMessage.lineNumber = e.errorPath.back().line;
errorMessage.errorId = e.errorId.toStdString();
errorMessage.symbolNames = e.symbolNames.toStdString();
if (isSuppressed(errorMessage))
continue;
std::list<ErrorMessage::FileLocation> callstack;
std::transform(e.errorPath.cbegin(), e.errorPath.cend(), std::back_inserter(callstack), [](const QErrorPathItem& path) {
return ErrorMessage::FileLocation(path.file.toStdString(), path.info.toStdString(), path.line, path.column);
});
const std::string f0 = file0.toStdString();
const std::string msg = e.message.toStdString();
const std::string id = e.errorId.toStdString();
ErrorMessage errmsg(callstack, f0, e.severity, msg, id, Certainty::normal);
mResult.reportErr(errmsg);
}
}
bool CheckThread::isSuppressed(const SuppressionList::ErrorMessage &errorMessage) const
{
return std::any_of(mSuppressions.cbegin(), mSuppressions.cend(), [&](const SuppressionList::Suppression& s) {
return s.isSuppressed(errorMessage);
});
}
QString CheckThread::clangCmd()
{
QString path = QSettings().value(SETTINGS_CLANG_PATH,QString()).toString();
if (!path.isEmpty())
path += '/';
path += "clang";
#ifdef Q_OS_WIN
path += ".exe";
#endif
QProcess process;
process.start(path, QStringList() << "--version");
process.waitForFinished();
if (process.exitCode() == 0)
return path;
#ifdef Q_OS_WIN
// Try to autodetect clang
if (QFileInfo("C:/Program Files/LLVM/bin/clang.exe").exists())
return "C:/Program Files/LLVM/bin/clang.exe";
#endif
return QString();
}
QString CheckThread::clangTidyCmd()
{
QString path = QSettings().value(SETTINGS_CLANG_PATH,QString()).toString();
if (!path.isEmpty())
path += '/';
path += "clang-tidy";
#ifdef Q_OS_WIN
path += ".exe";
#endif
QProcess process;
process.start(path, QStringList() << "--version");
process.waitForFinished();
if (process.exitCode() == 0)
return path;
#ifdef Q_OS_WIN
// Try to autodetect clang-tidy
if (QFileInfo("C:/Program Files/LLVM/bin/clang-tidy.exe").exists())
return "C:/Program Files/LLVM/bin/clang-tidy.exe";
#endif
return QString();
}
| 17,279
|
C++
|
.cpp
| 428
| 30.771028
| 157
| 0.582509
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,326
|
application.cpp
|
danmar_cppcheck/gui/application.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "application.h"
#include <utility>
Application::Application(QString name, QString path,
QString params)
: mName(std::move(name))
, mPath(std::move(path))
, mParameters(std::move(params))
{}
| 988
|
C++
|
.cpp
| 25
| 36.28
| 72
| 0.727083
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,328
|
newsuppressiondialog.cpp
|
danmar_cppcheck/gui/newsuppressiondialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "newsuppressiondialog.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "suppressions.h"
#include "ui_newsuppressiondialog.h"
#include <cstdint>
#include <string>
#include <QComboBox>
#include <QLineEdit>
#include <QString>
#include <QStringList>
class QWidget;
enum class Color : std::uint8_t;
NewSuppressionDialog::NewSuppressionDialog(QWidget *parent) :
QDialog(parent),
mUI(new Ui::NewSuppressionDialog)
{
mUI->setupUi(this);
class QErrorLogger : public ErrorLogger {
public:
void reportOut(const std::string & /*outmsg*/, Color /*c*/) override {}
void reportErr(const ErrorMessage &msg) override {
errorIds << QString::fromStdString(msg.id);
}
QStringList errorIds;
};
QErrorLogger errorLogger;
CppCheck::getErrorMessages(errorLogger);
errorLogger.errorIds.sort();
mUI->mComboErrorId->addItems(errorLogger.errorIds);
mUI->mComboErrorId->setCurrentIndex(-1);
mUI->mComboErrorId->setCurrentText("");
}
NewSuppressionDialog::~NewSuppressionDialog()
{
delete mUI;
}
SuppressionList::Suppression NewSuppressionDialog::getSuppression() const
{
SuppressionList::Suppression ret;
ret.errorId = mUI->mComboErrorId->currentText().toStdString();
if (ret.errorId.empty())
ret.errorId = "*";
ret.fileName = mUI->mTextFileName->text().toStdString();
if (!mUI->mTextLineNumber->text().isEmpty())
ret.lineNumber = mUI->mTextLineNumber->text().toInt();
ret.symbolName = mUI->mTextSymbolName->text().toStdString();
return ret;
}
void NewSuppressionDialog::setSuppression(const SuppressionList::Suppression &suppression)
{
setWindowTitle(tr("Edit suppression"));
mUI->mComboErrorId->setCurrentText(QString::fromStdString(suppression.errorId));
mUI->mTextFileName->setText(QString::fromStdString(suppression.fileName));
mUI->mTextLineNumber->setText(suppression.lineNumber > 0 ? QString::number(suppression.lineNumber) : QString());
mUI->mTextSymbolName->setText(QString::fromStdString(suppression.symbolName));
}
| 2,840
|
C++
|
.cpp
| 74
| 34.824324
| 116
| 0.743189
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,329
|
codeeditstyledialog.cpp
|
danmar_cppcheck/gui/codeeditstyledialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "codeeditstyledialog.h"
#include "codeeditor.h"
#include "codeeditstylecontrols.h"
#include <QDialogButtonBox>
#include <QFlags>
#include <QFontMetrics>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QString>
#include <QStringList>
#include <QVBoxLayout>
#include <QtGlobal>
class QWidget;
const QString StyleEditDialog::mSampleDocument(
"/*****\n"
"* Multiline Comment\n"
"*****/\n"
"#include <QApplication>\n"
"#include <iostream>\n"
"\n"
"class fwdClass;\n"
"\n"
"int main(int argc, char *argv[])\n"
"{\n"
" QApplication a(argc, argv);\n"
" int nLife = 42;\n"
" w.show();\n"
" // single line comment\n"
" // line below is highlighted\n"
" fwdClass( nLife );\n"
" return a.exec();\n"
"}\n"
"\n"
"void class fwdClass( double dValue ) {\n"
" std::cout << \"Ipsum Lorem: \"\n"
" << nValue\n"
" << std::endl;\n"
"}\n");
const QStringList StyleEditDialog::mErrSymbolsList = (
QStringList(QStringList()
<< "nLife"
<< "dValue"
<< "nValue"));
const int StyleEditDialog::mErrLineNum = 16;
StyleEditDialog::StyleEditDialog(const CodeEditorStyle& newStyle,
QWidget *parent /*= nullptr*/) :
QDialog(parent),
mStyleIncoming(newStyle),
mStyleOutgoing(newStyle)
{
auto *vboxMain = new QVBoxLayout(this);
auto *hboxEdit = new QHBoxLayout();
// Color/Weight controls
auto *flEditControls = new QFormLayout();
mBtnWidgetColorFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Editor Foreground Color"),
mBtnWidgetColorFG);
mBtnWidgetColorBG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Editor Background Color"),
mBtnWidgetColorBG);
mBtnHighlightBG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Highlight Background Color"),
mBtnHighlightBG);
mBtnLineNumFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Line Number Foreground Color"),
mBtnLineNumFG);
mBtnLineNumBG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Line Number Background Color"),
mBtnLineNumBG);
mBtnKeywordFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Keyword Foreground Color"),
mBtnKeywordFG);
mCBKeywordWeight = new SelectFontWeightCombo(this);
flEditControls->addRow(QObject::tr("Keyword Font Weight"),
mCBKeywordWeight);
mBtnClassFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Class Foreground Color"),
mBtnClassFG);
mCBClassWeight = new SelectFontWeightCombo(this);
flEditControls->addRow(QObject::tr("Class Font Weight"),
mCBClassWeight);
mBtnQuoteFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Quote Foreground Color"),
mBtnQuoteFG);
mCBQuoteWeight = new SelectFontWeightCombo(this);
flEditControls->addRow(QObject::tr("Quote Font Weight"),
mCBQuoteWeight);
mBtnCommentFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Comment Foreground Color"),
mBtnCommentFG);
mCBCommentWeight = new SelectFontWeightCombo(this);
flEditControls->addRow(QObject::tr("Comment Font Weight"),
mCBCommentWeight);
mBtnSymbolFG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Symbol Foreground Color"),
mBtnSymbolFG);
mBtnSymbolBG = new SelectColorButton(this);
flEditControls->addRow(QObject::tr("Symbol Background Color"),
mBtnSymbolBG);
mCBSymbolWeight = new SelectFontWeightCombo(this);
flEditControls->addRow(QObject::tr("Symbol Font Weight"),
mCBSymbolWeight);
hboxEdit->addLayout(flEditControls);
// CodeEditor to display Style
mSampleEditor = new CodeEditor(this);
QFont sampleFont("Monospace");
QFontMetrics fm(sampleFont);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
mSampleEditor->setMinimumWidth(fm.horizontalAdvance(QString(40, 'W')));
#else
mSampleEditor->setMinimumWidth(fm.width(QString(40, 'W')));
#endif
// designate highlight, errors, and symbols
mSampleEditor->setError(mSampleDocument, mErrLineNum, mErrSymbolsList);
// End Controls
hboxEdit->addWidget(mSampleEditor);
vboxMain->addLayout(hboxEdit);
// Default Controls
auto *hboxDefaultControls = new QHBoxLayout();
mBtnDefaultLight = new QPushButton(QObject::tr("Set to Default Light"),
this);
mBtnDefaultDark = new QPushButton(QObject::tr("Set to Default Dark"),
this);
hboxDefaultControls->addStretch(1);
hboxDefaultControls->addWidget(mBtnDefaultLight);
hboxDefaultControls->addWidget(mBtnDefaultDark);
hboxDefaultControls->addStretch(1);
vboxMain->addLayout(hboxDefaultControls);
vboxMain->addStretch(2);
// dialog controls
auto *dBtnBox = new QDialogButtonBox(
QDialogButtonBox::Cancel |
QDialogButtonBox::Ok |
QDialogButtonBox::Reset);
vboxMain->addStretch(1);
vboxMain->addWidget(dBtnBox);
// setup values for style controls
updateControls();
updateStyle();
connect(dBtnBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(dBtnBox, SIGNAL(rejected()), this, SLOT(reject()));
connect(dBtnBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()),
this, SLOT(resetStyle()));
connect(mBtnDefaultLight, SIGNAL(clicked()),
this, SLOT(setStyleDefaultLight()));
connect(mBtnDefaultDark, SIGNAL(clicked()),
this, SLOT(setStyleDefaultDark()));
connect(mBtnWidgetColorFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedWidgetFG(QColor)));
connect(mBtnWidgetColorBG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedWidgetBG(QColor)));
connect(mBtnHighlightBG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedHighlightBG(QColor)));
connect(mBtnLineNumFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedLineNumFG(QColor)));
connect(mBtnLineNumBG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedLineNumBG(QColor)));
connect(mBtnKeywordFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedKeywordFG(QColor)));
connect(mCBKeywordWeight, SIGNAL(weightChanged(QFont::Weight)),
this, SLOT(weightChangedKeyword(QFont::Weight)));
connect(mBtnClassFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedClassFG(QColor)));
connect(mCBClassWeight, SIGNAL(weightChanged(QFont::Weight)),
this, SLOT(weightChangedClass(QFont::Weight)));
connect(mBtnQuoteFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedQuoteFG(QColor)));
connect(mCBQuoteWeight, SIGNAL(weightChanged(QFont::Weight)),
this, SLOT(weightChangedQuote(QFont::Weight)));
connect(mBtnCommentFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedCommentFG(QColor)));
connect(mCBCommentWeight, SIGNAL(weightChanged(QFont::Weight)),
this, SLOT(weightChangedComment(QFont::Weight)));
connect(mBtnSymbolFG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedSymbolFG(QColor)));
connect(mBtnSymbolBG, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChangedSymbolBG(QColor)));
connect(mCBSymbolWeight, SIGNAL(weightChanged(QFont::Weight)),
this, SLOT(weightChangedSymbol(QFont::Weight)));
}
void StyleEditDialog::updateControls()
{
mBtnWidgetColorFG->setColor(mStyleOutgoing.widgetFGColor);
mBtnWidgetColorBG->setColor(mStyleOutgoing.widgetBGColor);
mBtnHighlightBG->setColor(mStyleOutgoing.highlightBGColor);
mBtnLineNumFG->setColor(mStyleOutgoing.lineNumFGColor);
mBtnLineNumBG->setColor(mStyleOutgoing.lineNumBGColor);
mBtnKeywordFG->setColor(mStyleOutgoing.keywordColor);
mCBKeywordWeight->setWeight(mStyleOutgoing.keywordWeight);
mBtnClassFG->setColor(mStyleOutgoing.classColor);
mCBClassWeight->setWeight(mStyleOutgoing.classWeight);
mBtnQuoteFG->setColor(mStyleOutgoing.quoteColor);
mCBQuoteWeight->setWeight(mStyleOutgoing.quoteWeight);
mBtnCommentFG->setColor(mStyleOutgoing.commentColor);
mCBCommentWeight->setWeight(mStyleOutgoing.commentWeight);
mBtnSymbolFG->setColor(mStyleOutgoing.symbolFGColor);
mBtnSymbolBG->setColor(mStyleOutgoing.symbolBGColor);
mCBSymbolWeight->setWeight(mStyleOutgoing.symbolWeight);
}
void StyleEditDialog::updateStyle()
{
mBtnDefaultLight->setEnabled(mStyleOutgoing != defaultStyleLight);
mBtnDefaultDark->setEnabled(mStyleOutgoing != defaultStyleDark);
// set Editor Styling
mSampleEditor->setStyle(mStyleOutgoing);
}
CodeEditorStyle StyleEditDialog::getStyle()
{
return mStyleOutgoing;
}
void StyleEditDialog::resetStyle()
{
mStyleOutgoing = mStyleIncoming;
updateControls();
updateStyle();
}
void StyleEditDialog::setStyleDefaultLight()
{
mStyleOutgoing = defaultStyleLight;
updateControls();
updateStyle();
}
void StyleEditDialog::setStyleDefaultDark()
{
mStyleOutgoing = defaultStyleDark;
updateControls();
updateStyle();
}
void StyleEditDialog::colorChangedWidgetFG(const QColor& newColor)
{
mStyleOutgoing.widgetFGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedWidgetBG(const QColor& newColor)
{
mStyleOutgoing.widgetBGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedHighlightBG(const QColor& newColor)
{
mStyleOutgoing.highlightBGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedLineNumFG(const QColor& newColor)
{
mStyleOutgoing.lineNumFGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedLineNumBG(const QColor& newColor)
{
mStyleOutgoing.lineNumBGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedKeywordFG(const QColor& newColor)
{
mStyleOutgoing.keywordColor = newColor;
updateStyle();
}
void StyleEditDialog::weightChangedKeyword(QFont::Weight newWeight)
{
mStyleOutgoing.keywordWeight = newWeight;
updateStyle();
}
void StyleEditDialog::colorChangedClassFG(const QColor& newColor)
{
mStyleOutgoing.classColor = newColor;
updateStyle();
}
void StyleEditDialog::weightChangedClass(QFont::Weight newWeight)
{
mStyleOutgoing.classWeight = newWeight;
updateStyle();
}
void StyleEditDialog::colorChangedQuoteFG(const QColor& newColor)
{
mStyleOutgoing.quoteColor = newColor;
updateStyle();
}
void StyleEditDialog::weightChangedQuote(QFont::Weight newWeight)
{
mStyleOutgoing.quoteWeight = newWeight;
updateStyle();
}
void StyleEditDialog::colorChangedCommentFG(const QColor& newColor)
{
mStyleOutgoing.commentColor = newColor;
updateStyle();
}
void StyleEditDialog::weightChangedComment(QFont::Weight newWeight)
{
mStyleOutgoing.commentWeight = newWeight;
updateStyle();
}
void StyleEditDialog::colorChangedSymbolFG(const QColor& newColor)
{
mStyleOutgoing.symbolFGColor = newColor;
updateStyle();
}
void StyleEditDialog::colorChangedSymbolBG(const QColor& newColor)
{
mStyleOutgoing.symbolBGColor = newColor;
updateStyle();
}
void StyleEditDialog::weightChangedSymbol(QFont::Weight newWeight)
{
mStyleOutgoing.symbolWeight = newWeight;
updateStyle();
}
| 12,627
|
C++
|
.cpp
| 326
| 32.840491
| 75
| 0.710979
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,330
|
aboutdialog.cpp
|
danmar_cppcheck/gui/aboutdialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2022 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "aboutdialog.h"
#include "ui_about.h"
#include <QDialogButtonBox>
#include <QLabel>
AboutDialog::AboutDialog(const QString &version, const QString &extraVersion, QWidget *parent)
: QDialog(parent)
, mUI(new Ui::About)
{
mUI->setupUi(this);
QString fmtVersion(version);
if (!extraVersion.isEmpty()) {
fmtVersion += " (" + extraVersion + ")";
}
mUI->mVersion->setText(mUI->mVersion->text().arg(fmtVersion));
QString date = __DATE__;
mUI->mCopyright->setText(mUI->mCopyright->text().arg(date.right(4)));
QString url = "<a href=\"https://cppcheck.sourceforge.io/\">https://cppcheck.sourceforge.io/</a>";
mUI->mHomepage->setText(mUI->mHomepage->text().arg(url));
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &AboutDialog::accept);
}
AboutDialog::~AboutDialog()
{
delete mUI;
}
| 1,610
|
C++
|
.cpp
| 41
| 36.268293
| 102
| 0.71721
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,332
|
cppchecklibrarydata.cpp
|
danmar_cppcheck/gui/cppchecklibrarydata.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppchecklibrarydata.h"
#include "utils.h"
#include <stdexcept>
#include <string>
#include <QObject>
#include <QVariant>
#include <QXmlStreamAttributes>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QtGlobal>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QStringRef>
#endif
const unsigned int CppcheckLibraryData::Function::Arg::ANY = ~0U;
const unsigned int CppcheckLibraryData::Function::Arg::VARIADIC = ~1U;
static std::string unhandledElement(const QXmlStreamReader &xmlReader)
{
throw std::runtime_error(QObject::tr("line %1: Unhandled element %2").arg(xmlReader.lineNumber()).arg(xmlReader.name().toString()).toStdString());
}
static std::string mandatoryAttibuteMissing(const QXmlStreamReader &xmlReader, const QString& attributeName)
{
throw std::runtime_error(QObject::tr("line %1: Mandatory attribute '%2' missing in '%3'")
.arg(xmlReader.lineNumber())
.arg(attributeName)
.arg(xmlReader.name().toString()).toStdString());
}
static CppcheckLibraryData::Container loadContainer(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Container container;
container.id = xmlReader.attributes().value("id").toString();
container.inherits = xmlReader.attributes().value("inherits").toString();
container.startPattern = xmlReader.attributes().value("startPattern").toString();
container.endPattern = xmlReader.attributes().value("endPattern").toString();
container.opLessAllowed = xmlReader.attributes().value("opLessAllowed").toString();
container.itEndPattern = xmlReader.attributes().value("itEndPattern").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "container") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "type") {
container.type.templateParameter = xmlReader.attributes().value("templateParameter").toString();
container.type.string = xmlReader.attributes().value("string").toString();
} else if (elementName == "size" || elementName == "access" || elementName == "other" || elementName == "rangeItemRecordType") {
const QString indexOperator = xmlReader.attributes().value("indexOperator").toString();
if (elementName == "access" && indexOperator == "array-like")
container.access_arrayLike = true;
const QString templateParameter = xmlReader.attributes().value("templateParameter").toString();
if (elementName == "size" && !templateParameter.isEmpty())
container.size_templateParameter = templateParameter.toInt();
for (;;) {
type = xmlReader.readNext();
if (xmlReader.name().toString() == elementName)
break;
if (type != QXmlStreamReader::StartElement)
continue;
CppcheckLibraryData::Container::Function function;
function.name = xmlReader.attributes().value("name").toString();
function.action = xmlReader.attributes().value("action").toString();
function.yields = xmlReader.attributes().value("yields").toString();
if (elementName == "size")
container.sizeFunctions.append(function);
else if (elementName == "access")
container.accessFunctions.append(function);
else if (elementName == "rangeItemRecordType") {
CppcheckLibraryData::Container::RangeItemRecordType rangeItemRecordType;
rangeItemRecordType.name = xmlReader.attributes().value("name").toString();
rangeItemRecordType.templateParameter = xmlReader.attributes().value("templateParameter").toString();
container.rangeItemRecordTypeList.append(rangeItemRecordType);
} else
container.otherFunctions.append(function);
}
} else {
unhandledElement(xmlReader);
}
}
return container;
}
static CppcheckLibraryData::Define loadDefine(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Define define;
define.name = xmlReader.attributes().value("name").toString();
define.value = xmlReader.attributes().value("value").toString();
return define;
}
static QString loadUndefine(const QXmlStreamReader &xmlReader)
{
return xmlReader.attributes().value("name").toString();
}
static CppcheckLibraryData::SmartPointer loadSmartPointer(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::SmartPointer smartPointer;
smartPointer.name = xmlReader.attributes().value("class-name").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "smart-pointer") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "unique") {
smartPointer.unique = true;
} else {
unhandledElement(xmlReader);
}
}
return smartPointer;
}
static CppcheckLibraryData::TypeChecks loadTypeChecks(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::TypeChecks typeChecks;
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "type-checks") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "suppress" || elementName == "check") {
QPair<QString, QString> entry(elementName, xmlReader.readElementText());
typeChecks.append(entry);
}
}
return typeChecks;
}
static CppcheckLibraryData::Function::Arg loadFunctionArg(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Function::Arg arg;
QString argnr = xmlReader.attributes().value("nr").toString();
if (argnr == "any")
arg.nr = CppcheckLibraryData::Function::Arg::ANY;
else if (argnr == "variadic")
arg.nr = CppcheckLibraryData::Function::Arg::VARIADIC;
else
arg.nr = argnr.toUInt();
arg.defaultValue = xmlReader.attributes().value("default").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "arg") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "not-bool")
arg.notbool = true;
else if (elementName == "not-null")
arg.notnull = true;
else if (elementName == "not-uninit")
arg.notuninit = true;
else if (elementName == "strz")
arg.strz = true;
else if (elementName == "formatstr")
arg.formatstr = true;
else if (elementName == "valid")
arg.valid = xmlReader.readElementText();
else if (elementName == "minsize") {
CppcheckLibraryData::Function::Arg::MinSize minsize;
minsize.type = xmlReader.attributes().value("type").toString();
minsize.arg = xmlReader.attributes().value("arg").toString();
minsize.arg2 = xmlReader.attributes().value("arg2").toString();
arg.minsizes.append(minsize);
} else if (elementName == "iterator") {
arg.iterator.container = xmlReader.attributes().value("container").toInt();
arg.iterator.type = xmlReader.attributes().value("type").toString();
} else {
unhandledElement(xmlReader);
}
}
return arg;
}
static CppcheckLibraryData::Function loadFunction(QXmlStreamReader &xmlReader, const QString &comments)
{
CppcheckLibraryData::Function function;
function.comments = comments;
function.name = xmlReader.attributes().value("name").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "function") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "noreturn")
function.noreturn = (xmlReader.readElementText() == "true") ? CppcheckLibraryData::Function::True : CppcheckLibraryData::Function::False;
else if (elementName == "pure")
function.gccPure = true;
else if (elementName == "const")
function.gccConst = true;
else if (elementName == "leak-ignore")
function.leakignore = true;
else if (elementName == "use-retval")
function.useretval = true;
else if (elementName == "returnValue") {
const QString container = xmlReader.attributes().value("container").toString();
function.returnValue.container = container.isNull() ? -1 : container.toInt();
function.returnValue.type = xmlReader.attributes().value("type").toString();
function.returnValue.value = xmlReader.readElementText();
} else if (elementName == "formatstr") {
function.formatstr.scan = xmlReader.attributes().value("scan").toString();
function.formatstr.secure = xmlReader.attributes().value("secure").toString();
} else if (elementName == "arg")
function.args.append(loadFunctionArg(xmlReader));
else if (elementName == "warn") {
function.warn.severity = xmlReader.attributes().value("severity").toString();
function.warn.cstd = xmlReader.attributes().value("cstd").toString();
function.warn.reason = xmlReader.attributes().value("reason").toString();
function.warn.alternatives = xmlReader.attributes().value("alternatives").toString();
function.warn.msg = xmlReader.readElementText();
} else if (elementName == "not-overlapping-data") {
const QStringList attributeList {"ptr1-arg", "ptr2-arg", "size-arg", "strlen-arg"};
for (const QString &attr : attributeList) {
if (xmlReader.attributes().hasAttribute(attr)) {
function.notOverlappingDataArgs[attr] = xmlReader.attributes().value(attr).toString();
}
}
} else if (elementName == "container") {
const QStringList attributeList {"action", "yields"};
for (const QString &attr : attributeList) {
if (xmlReader.attributes().hasAttribute(attr)) {
function.containerAttributes[attr] = xmlReader.attributes().value(attr).toString();
}
}
} else {
unhandledElement(xmlReader);
}
}
return function;
}
static CppcheckLibraryData::MemoryResource loadMemoryResource(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::MemoryResource memoryresource;
memoryresource.type = xmlReader.name().toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != memoryresource.type) {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "alloc" || elementName == "realloc") {
CppcheckLibraryData::MemoryResource::Alloc alloc;
alloc.isRealloc = (elementName == "realloc");
alloc.init = (xmlReader.attributes().value("init").toString() == "true");
if (xmlReader.attributes().hasAttribute("arg")) {
alloc.arg = xmlReader.attributes().value("arg").toInt();
}
if (alloc.isRealloc && xmlReader.attributes().hasAttribute("realloc-arg")) {
alloc.reallocArg = xmlReader.attributes().value("realloc-arg").toInt();
}
if (memoryresource.type == "memory") {
alloc.bufferSize = xmlReader.attributes().value("buffer-size").toString();
}
alloc.name = xmlReader.readElementText();
memoryresource.alloc.append(alloc);
} else if (elementName == "dealloc") {
CppcheckLibraryData::MemoryResource::Dealloc dealloc;
if (xmlReader.attributes().hasAttribute("arg")) {
dealloc.arg = xmlReader.attributes().value("arg").toInt();
}
dealloc.name = xmlReader.readElementText();
memoryresource.dealloc.append(dealloc);
} else if (elementName == "use")
memoryresource.use.append(xmlReader.readElementText());
else
unhandledElement(xmlReader);
}
return memoryresource;
}
static CppcheckLibraryData::PodType loadPodType(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::PodType podtype;
podtype.name = xmlReader.attributes().value("name").toString();
if (podtype.name.isEmpty()) {
mandatoryAttibuteMissing(xmlReader, "name");
}
podtype.stdtype = xmlReader.attributes().value("stdtype").toString();
podtype.size = xmlReader.attributes().value("size").toString();
podtype.sign = xmlReader.attributes().value("sign").toString();
return podtype;
}
static CppcheckLibraryData::PlatformType loadPlatformType(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::PlatformType platformType;
platformType.name = xmlReader.attributes().value("name").toString();
platformType.value = xmlReader.attributes().value("value").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "platformtype") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (QStringList({"unsigned", "long", "pointer", "const_ptr", "ptr_ptr"}).contains(elementName)) {
platformType.types.append(elementName);
} else if (elementName == "platform") {
platformType.platforms.append(xmlReader.attributes().value("type").toString());
} else {
unhandledElement(xmlReader);
}
}
return platformType;
}
static CppcheckLibraryData::Reflection loadReflection(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Reflection reflection;
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "reflection") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "call") {
CppcheckLibraryData::Reflection::Call call;
if (xmlReader.attributes().hasAttribute("arg")) {
call.arg = xmlReader.attributes().value("arg").toInt();
} else {
mandatoryAttibuteMissing(xmlReader, "arg");
}
call.name = xmlReader.readElementText();
reflection.calls.append(call);
} else {
unhandledElement(xmlReader);
}
}
return reflection;
}
static CppcheckLibraryData::Markup loadMarkup(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Markup markup;
QXmlStreamReader::TokenType type;
if (xmlReader.attributes().hasAttribute("ext")) {
markup.ext = xmlReader.attributes().value("ext").toString();
} else {
mandatoryAttibuteMissing(xmlReader, "ext");
}
if (xmlReader.attributes().hasAttribute("aftercode")) {
markup.afterCode = (xmlReader.attributes().value("aftercode") == QString("true"));
} else {
mandatoryAttibuteMissing(xmlReader, "aftercode");
}
if (xmlReader.attributes().hasAttribute("reporterrors")) {
markup.reportErrors = (xmlReader.attributes().value("reporterrors") == QString("true"));
} else {
mandatoryAttibuteMissing(xmlReader, "reporterrors");
}
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "markup") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "keywords") {
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "keywords") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "keyword") {
markup.keywords.append(xmlReader.attributes().value("name").toString());
} else {
unhandledElement(xmlReader);
}
}
} else if (elementName == "codeblocks") {
CppcheckLibraryData::Markup::CodeBlocks codeBlock;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "codeblocks") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "block") {
codeBlock.blocks.append(xmlReader.attributes().value("name").toString());
} else if (xmlReader.name().toString() == "structure") {
codeBlock.offset = xmlReader.attributes().value("offset").toInt();
codeBlock.start = xmlReader.attributes().value("start").toString();
codeBlock.end = xmlReader.attributes().value("end").toString();
} else {
unhandledElement(xmlReader);
}
}
markup.codeBlocks.append(codeBlock);
} else if (elementName == "exported") {
CppcheckLibraryData::Markup::Exporter exporter;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "exported") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "exporter") {
exporter.prefix = xmlReader.attributes().value("prefix").toString();
} else if (xmlReader.name().toString() == "prefix") {
exporter.prefixList.append(xmlReader.readElementText());
} else if (xmlReader.name().toString() == "suffix") {
exporter.suffixList.append(xmlReader.readElementText());
} else {
unhandledElement(xmlReader);
}
}
markup.exporter.append(exporter);
} else if (elementName == "imported") {
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "imported") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "importer") {
markup.importer.append(xmlReader.readElementText());
} else {
unhandledElement(xmlReader);
}
}
} else {
unhandledElement(xmlReader);
}
}
return markup;
}
static CppcheckLibraryData::Entrypoint loadEntrypoint(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Entrypoint entrypoint;
entrypoint.name = xmlReader.attributes().value("name").toString();
return entrypoint;
}
QString CppcheckLibraryData::open(QIODevice &file)
{
clear();
QString comments;
QXmlStreamReader xmlReader(&file);
while (!xmlReader.atEnd()) {
const QXmlStreamReader::TokenType t = xmlReader.readNext();
switch (t) {
case QXmlStreamReader::Comment:
if (!comments.isEmpty())
comments += "\n";
comments += xmlReader.text().toString();
break;
case QXmlStreamReader::StartElement:
try {
const QString elementName(xmlReader.name().toString());
if (elementName == "def")
;
else if (elementName == "container")
containers.append(loadContainer(xmlReader));
else if (elementName == "define")
defines.append(loadDefine(xmlReader));
else if (elementName == "undefine")
undefines.append(loadUndefine(xmlReader));
else if (elementName == "function")
functions.append(loadFunction(xmlReader, comments));
else if (elementName == "memory" || elementName == "resource")
memoryresource.append(loadMemoryResource(xmlReader));
else if (elementName == "podtype")
podtypes.append(loadPodType(xmlReader));
else if (elementName == "smart-pointer")
smartPointers.append(loadSmartPointer(xmlReader));
else if (elementName == "type-checks")
typeChecks.append(loadTypeChecks(xmlReader));
else if (elementName == "platformtype")
platformTypes.append(loadPlatformType(xmlReader));
else if (elementName == "reflection")
reflections.append(loadReflection(xmlReader));
else if (elementName == "markup")
markups.append(loadMarkup(xmlReader));
else if (elementName == "entrypoint")
entrypoints.append(loadEntrypoint(xmlReader));
else
unhandledElement(xmlReader);
} catch (std::runtime_error &e) {
return e.what();
}
comments.clear();
break;
default:
break;
}
}
if (xmlReader.hasError())
return xmlReader.errorString();
return QString();
}
static void writeContainerFunctions(QXmlStreamWriter &xmlWriter, const QString &name, int extra, const QList<CppcheckLibraryData::Container::Function> &functions)
{
if (functions.isEmpty() && extra < 0)
return;
xmlWriter.writeStartElement(name);
if (extra >= 0) {
if (name == "access")
xmlWriter.writeAttribute("indexOperator", "array-like");
else if (name == "size")
xmlWriter.writeAttribute("templateParameter", QString::number(extra));
}
for (const CppcheckLibraryData::Container::Function &function : functions) {
xmlWriter.writeStartElement("function");
xmlWriter.writeAttribute("name", function.name);
if (!function.action.isEmpty())
xmlWriter.writeAttribute("action", function.action);
if (!function.yields.isEmpty())
xmlWriter.writeAttribute("yields", function.yields);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeContainerRangeItemRecords(QXmlStreamWriter &xmlWriter, const QList<CppcheckLibraryData::Container::RangeItemRecordType> &rangeItemRecords)
{
if (rangeItemRecords.isEmpty())
return;
xmlWriter.writeStartElement("rangeItemRecordType");
for (const CppcheckLibraryData::Container::RangeItemRecordType &item : rangeItemRecords) {
xmlWriter.writeStartElement("member");
xmlWriter.writeAttribute("name", item.name);
xmlWriter.writeAttribute("templateParameter", item.templateParameter);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeContainer(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Container &container)
{
xmlWriter.writeStartElement("container");
xmlWriter.writeAttribute("id", container.id);
if (!container.startPattern.isEmpty())
xmlWriter.writeAttribute("startPattern", container.startPattern);
if (!container.endPattern.isNull())
xmlWriter.writeAttribute("endPattern", container.endPattern);
if (!container.inherits.isEmpty())
xmlWriter.writeAttribute("inherits", container.inherits);
if (!container.opLessAllowed.isEmpty())
xmlWriter.writeAttribute("opLessAllowed", container.opLessAllowed);
if (!container.itEndPattern.isEmpty())
xmlWriter.writeAttribute("itEndPattern", container.itEndPattern);
if (!container.type.templateParameter.isEmpty() || !container.type.string.isEmpty()) {
xmlWriter.writeStartElement("type");
if (!container.type.templateParameter.isEmpty())
xmlWriter.writeAttribute("templateParameter", container.type.templateParameter);
if (!container.type.string.isEmpty())
xmlWriter.writeAttribute("string", container.type.string);
xmlWriter.writeEndElement();
}
writeContainerFunctions(xmlWriter, "size", container.size_templateParameter, container.sizeFunctions);
writeContainerFunctions(xmlWriter, "access", container.access_arrayLike?1:-1, container.accessFunctions);
writeContainerFunctions(xmlWriter, "other", -1, container.otherFunctions);
writeContainerRangeItemRecords(xmlWriter, container.rangeItemRecordTypeList);
xmlWriter.writeEndElement();
}
static void writeFunction(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Function &function)
{
QString comments = function.comments;
while (comments.startsWith("\n"))
comments = comments.mid(1);
while (comments.endsWith("\n"))
comments.chop(1);
for (const QString &comment : comments.split('\n')) {
if (comment.length() >= 1)
xmlWriter.writeComment(comment);
}
xmlWriter.writeStartElement("function");
xmlWriter.writeAttribute("name", function.name);
if (function.useretval)
xmlWriter.writeEmptyElement("use-retval");
if (function.gccConst)
xmlWriter.writeEmptyElement("const");
if (function.gccPure)
xmlWriter.writeEmptyElement("pure");
if (!function.returnValue.empty()) {
xmlWriter.writeStartElement("returnValue");
if (!function.returnValue.type.isNull())
xmlWriter.writeAttribute("type", function.returnValue.type);
if (function.returnValue.container >= 0)
xmlWriter.writeAttribute("container", QString::number(function.returnValue.container));
if (!function.returnValue.value.isNull())
xmlWriter.writeCharacters(function.returnValue.value);
xmlWriter.writeEndElement();
}
if (function.noreturn != CppcheckLibraryData::Function::Unknown)
xmlWriter.writeTextElement("noreturn", bool_to_string(function.noreturn == CppcheckLibraryData::Function::True));
if (function.leakignore)
xmlWriter.writeEmptyElement("leak-ignore");
// Argument info..
for (const CppcheckLibraryData::Function::Arg &arg : function.args) {
if (arg.formatstr) {
xmlWriter.writeStartElement("formatstr");
if (!function.formatstr.scan.isNull())
xmlWriter.writeAttribute("scan", function.formatstr.scan);
if (!function.formatstr.secure.isNull())
xmlWriter.writeAttribute("secure", function.formatstr.secure);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement("arg");
if (arg.nr == CppcheckLibraryData::Function::Arg::ANY)
xmlWriter.writeAttribute("nr", "any");
else if (arg.nr == CppcheckLibraryData::Function::Arg::VARIADIC)
xmlWriter.writeAttribute("nr", "variadic");
else
xmlWriter.writeAttribute("nr", QString::number(arg.nr));
if (!arg.defaultValue.isNull())
xmlWriter.writeAttribute("default", arg.defaultValue);
if (arg.formatstr)
xmlWriter.writeEmptyElement("formatstr");
if (arg.notnull)
xmlWriter.writeEmptyElement("not-null");
if (arg.notuninit)
xmlWriter.writeEmptyElement("not-uninit");
if (arg.notbool)
xmlWriter.writeEmptyElement("not-bool");
if (arg.strz)
xmlWriter.writeEmptyElement("strz");
if (!arg.valid.isEmpty())
xmlWriter.writeTextElement("valid",arg.valid);
for (const CppcheckLibraryData::Function::Arg::MinSize &minsize : arg.minsizes) {
xmlWriter.writeStartElement("minsize");
xmlWriter.writeAttribute("type", minsize.type);
xmlWriter.writeAttribute("arg", minsize.arg);
if (!minsize.arg2.isEmpty())
xmlWriter.writeAttribute("arg2", minsize.arg2);
xmlWriter.writeEndElement();
}
if (arg.iterator.container >= 0 || !arg.iterator.type.isNull()) {
xmlWriter.writeStartElement("iterator");
if (arg.iterator.container >= 0)
xmlWriter.writeAttribute("container", QString::number(arg.iterator.container));
if (!arg.iterator.type.isNull())
xmlWriter.writeAttribute("type", arg.iterator.type);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!function.warn.isEmpty()) {
xmlWriter.writeStartElement("warn");
if (!function.warn.severity.isEmpty())
xmlWriter.writeAttribute("severity", function.warn.severity);
if (!function.warn.cstd.isEmpty())
xmlWriter.writeAttribute("cstd", function.warn.cstd);
if (!function.warn.alternatives.isEmpty())
xmlWriter.writeAttribute("alternatives", function.warn.alternatives);
if (!function.warn.reason.isEmpty())
xmlWriter.writeAttribute("reason", function.warn.reason);
if (!function.warn.msg.isEmpty())
xmlWriter.writeCharacters(function.warn.msg);
xmlWriter.writeEndElement();
}
if (!function.notOverlappingDataArgs.isEmpty()) {
xmlWriter.writeStartElement("not-overlapping-data");
for (const QString& value : function.notOverlappingDataArgs) {
xmlWriter.writeAttribute(function.notOverlappingDataArgs.key(value), value);
}
xmlWriter.writeEndElement();
}
if (!function.containerAttributes.isEmpty()) {
xmlWriter.writeStartElement("container");
for (const QString& value : function.containerAttributes) {
xmlWriter.writeAttribute(function.containerAttributes.key(value), value);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeMemoryResource(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::MemoryResource &mr)
{
xmlWriter.writeStartElement(mr.type);
for (const CppcheckLibraryData::MemoryResource::Alloc &alloc : mr.alloc) {
if (alloc.isRealloc) {
xmlWriter.writeStartElement("realloc");
} else {
xmlWriter.writeStartElement("alloc");
}
xmlWriter.writeAttribute("init", bool_to_string(alloc.init));
if (alloc.arg != -1) {
xmlWriter.writeAttribute("arg", QString("%1").arg(alloc.arg));
}
if (alloc.isRealloc && alloc.reallocArg != -1) {
xmlWriter.writeAttribute("realloc-arg", QString("%1").arg(alloc.reallocArg));
}
if (mr.type == "memory" && !alloc.bufferSize.isEmpty()) {
xmlWriter.writeAttribute("buffer-size", alloc.bufferSize);
}
xmlWriter.writeCharacters(alloc.name);
xmlWriter.writeEndElement();
}
for (const CppcheckLibraryData::MemoryResource::Dealloc &dealloc : mr.dealloc) {
xmlWriter.writeStartElement("dealloc");
if (dealloc.arg != -1) {
xmlWriter.writeAttribute("arg", QString("%1").arg(dealloc.arg));
}
xmlWriter.writeCharacters(dealloc.name);
xmlWriter.writeEndElement();
}
for (const QString &use : mr.use) {
xmlWriter.writeTextElement("use", use);
}
xmlWriter.writeEndElement();
}
static void writeTypeChecks(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::TypeChecks &typeChecks)
{
xmlWriter.writeStartElement("type-checks");
if (!typeChecks.isEmpty()) {
xmlWriter.writeStartElement("unusedvar");
}
for (const QPair<QString, QString> &check : typeChecks) {
xmlWriter.writeStartElement(check.first);
xmlWriter.writeCharacters(check.second);
xmlWriter.writeEndElement();
}
if (!typeChecks.isEmpty()) {
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writePlatformType(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::PlatformType &pt)
{
xmlWriter.writeStartElement("platformtype");
xmlWriter.writeAttribute("name", pt.name);
xmlWriter.writeAttribute("value", pt.value);
for (const QString &type : pt.types) {
xmlWriter.writeStartElement(type);
xmlWriter.writeEndElement();
}
for (const QString &platform : pt.platforms) {
xmlWriter.writeStartElement("platform");
if (!platform.isEmpty()) {
xmlWriter.writeAttribute("type", platform);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeReflection(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Reflection &refl)
{
xmlWriter.writeStartElement("reflection");
for (const CppcheckLibraryData::Reflection::Call &call : refl.calls) {
xmlWriter.writeStartElement("call");
xmlWriter.writeAttribute("arg", QString("%1").arg(call.arg));
xmlWriter.writeCharacters(call.name);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeMarkup(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Markup &mup)
{
xmlWriter.writeStartElement("markup");
xmlWriter.writeAttribute("ext", mup.ext);
xmlWriter.writeAttribute("aftercode", QVariant(mup.afterCode).toString());
xmlWriter.writeAttribute("reporterrors", QVariant(mup.reportErrors).toString());
if (!mup.keywords.isEmpty()) {
xmlWriter.writeStartElement("keywords");
for (const QString &keyword : mup.keywords) {
xmlWriter.writeStartElement("keyword");
xmlWriter.writeAttribute("name", keyword);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.importer.isEmpty()) {
xmlWriter.writeStartElement("imported");
for (const QString &import : mup.importer) {
xmlWriter.writeStartElement("importer");
xmlWriter.writeCharacters(import);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.exporter.isEmpty()) {
xmlWriter.writeStartElement("exported");
for (const CppcheckLibraryData::Markup::Exporter &exporter : mup.exporter) {
xmlWriter.writeStartElement("exporter");
xmlWriter.writeAttribute("prefix", exporter.prefix);
for (const QString &prefix : exporter.prefixList) {
xmlWriter.writeStartElement("prefix");
xmlWriter.writeCharacters(prefix);
xmlWriter.writeEndElement();
}
for (const QString &suffix : exporter.suffixList) {
xmlWriter.writeStartElement("suffix");
xmlWriter.writeCharacters(suffix);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.codeBlocks.isEmpty()) {
for (const CppcheckLibraryData::Markup::CodeBlocks &codeblock : mup.codeBlocks) {
xmlWriter.writeStartElement("codeblocks");
for (const QString &block : codeblock.blocks) {
xmlWriter.writeStartElement("block");
xmlWriter.writeAttribute("name", block);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement("structure");
xmlWriter.writeAttribute("offset", QString("%1").arg(codeblock.offset));
xmlWriter.writeAttribute("start", codeblock.start);
xmlWriter.writeAttribute("end", codeblock.end);
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
}
}
xmlWriter.writeEndElement();
}
QString CppcheckLibraryData::toString() const
{
QString outputString;
QXmlStreamWriter xmlWriter(&outputString);
xmlWriter.setAutoFormatting(true);
xmlWriter.setAutoFormattingIndent(2);
xmlWriter.writeStartDocument("1.0");
xmlWriter.writeStartElement("def");
xmlWriter.writeAttribute("format","2");
for (const Define &define : defines) {
xmlWriter.writeStartElement("define");
xmlWriter.writeAttribute("name", define.name);
xmlWriter.writeAttribute("value", define.value);
xmlWriter.writeEndElement();
}
for (const QString &undef : undefines) {
xmlWriter.writeStartElement("undefine");
xmlWriter.writeAttribute("name", undef);
xmlWriter.writeEndElement();
}
for (const Function &function : functions) {
writeFunction(xmlWriter, function);
}
for (const MemoryResource &mr : memoryresource) {
writeMemoryResource(xmlWriter, mr);
}
for (const Container &container : containers) {
writeContainer(xmlWriter, container);
}
for (const PodType &podtype : podtypes) {
xmlWriter.writeStartElement("podtype");
xmlWriter.writeAttribute("name", podtype.name);
if (!podtype.stdtype.isEmpty())
xmlWriter.writeAttribute("stdtype", podtype.stdtype);
if (!podtype.sign.isEmpty())
xmlWriter.writeAttribute("sign", podtype.sign);
if (!podtype.size.isEmpty())
xmlWriter.writeAttribute("size", podtype.size);
xmlWriter.writeEndElement();
}
for (const TypeChecks &check : typeChecks) {
writeTypeChecks(xmlWriter, check);
}
for (const SmartPointer &smartPtr : smartPointers) {
xmlWriter.writeStartElement("smart-pointer");
xmlWriter.writeAttribute("class-name", smartPtr.name);
if (smartPtr.unique) {
xmlWriter.writeEmptyElement("unique");
}
xmlWriter.writeEndElement();
}
for (const PlatformType &pt : platformTypes) {
writePlatformType(xmlWriter, pt);
}
for (const Reflection &refl : reflections) {
writeReflection(xmlWriter, refl);
}
for (const Markup &mup : markups) {
writeMarkup(xmlWriter, mup);
}
for (const Entrypoint &ent : entrypoints) {
xmlWriter.writeStartElement("entrypoint");
xmlWriter.writeAttribute("name", ent.name);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
return outputString;
}
| 40,172
|
C++
|
.cpp
| 871
| 36.796785
| 162
| 0.64324
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,333
|
common.cpp
|
danmar_cppcheck/gui/common.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QList>
#include <QMap>
#include <QSettings>
#include <QStringList>
#include <QVariant>
#include <Qt>
QString getPath(const QString &type)
{
QSettings settings;
QString path = settings.value(type, QString()).toString();
if (path.isEmpty()) {
// if not set, fallback to last check path hoping that it will be close enough
path = settings.value(SETTINGS_LAST_CHECK_PATH, QString()).toString();
if (path.isEmpty())
// if not set, return user's home directory as the best we can do for now
return QDir::homePath();
}
return path;
}
void setPath(const QString &type, const QString &value)
{
QSettings settings;
settings.setValue(type, value);
}
QString toFilterString(const QMap<QString,QString>& filters, bool addAllSupported, bool addAll)
{
QStringList entries;
if (addAllSupported) {
entries << QCoreApplication::translate("toFilterString", "All supported files (%1)")
.arg(filters.values().join(" "));
}
if (addAll) {
entries << QCoreApplication::translate("toFilterString", "All files (%1)").arg("*.*");
}
// We're using the description of the filters as the map keys, the file
// name patterns are our values. The generated filter string list will
// thus be sorted alphabetically over the descriptions.
for (const auto& k: filters.keys()) {
entries << QString("%1 (%2)").arg(k).arg(filters.value(k));
}
return entries.join(";;");
}
QString getDataDir()
{
QSettings settings;
const QString dataDir = settings.value("DATADIR", QString()).toString();
if (!dataDir.isEmpty())
return dataDir;
const QString appPath = QFileInfo(QCoreApplication::applicationFilePath()).canonicalPath();
if (QFileInfo::exists(appPath + "/std.cfg"))
return appPath;
if (appPath.indexOf("/cppcheck/", 0, Qt::CaseInsensitive) > 0)
return appPath.left(appPath.indexOf("/cppcheck/", 0, Qt::CaseInsensitive) + 9);
return appPath;
}
| 2,868
|
C++
|
.cpp
| 76
| 33.631579
| 95
| 0.698201
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,335
|
settingsdialog.cpp
|
danmar_cppcheck/gui/settingsdialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "settingsdialog.h"
#include "application.h"
#include "applicationdialog.h"
#include "applicationlist.h"
#include "codeeditorstyle.h"
#include "codeeditstyledialog.h"
#include "common.h"
#include "translationhandler.h"
#include "ui_settings.h"
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QPushButton>
#include <QRadioButton>
#include <QSettings>
#include <QSize>
#include <QThread>
#include <QVariant>
#include <QWidget>
SettingsDialog::SettingsDialog(ApplicationList *list,
TranslationHandler *translator,
bool premium,
QWidget *parent) :
QDialog(parent),
mApplications(list),
mTempApplications(new ApplicationList(this)),
mTranslator(translator),
mUI(new Ui::Settings),
mPremium(premium)
{
mUI->setupUi(this);
mUI->mPythonPathWarning->setStyleSheet("color: red");
QSettings settings;
mTempApplications->copy(list);
mUI->mJobs->setText(settings.value(SETTINGS_CHECK_THREADS, 1).toString());
mUI->mForce->setCheckState(boolToCheckState(settings.value(SETTINGS_CHECK_FORCE, false).toBool()));
mUI->mShowFullPath->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_FULL_PATH, false).toBool()));
mUI->mShowNoErrorsMessage->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_NO_ERRORS, false).toBool()));
mUI->mShowDebugWarnings->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool()));
mUI->mSaveAllErrors->setCheckState(boolToCheckState(settings.value(SETTINGS_SAVE_ALL_ERRORS, false).toBool()));
mUI->mSaveFullPath->setCheckState(boolToCheckState(settings.value(SETTINGS_SAVE_FULL_PATH, false).toBool()));
mUI->mInlineSuppressions->setCheckState(boolToCheckState(settings.value(SETTINGS_INLINE_SUPPRESSIONS, false).toBool()));
mUI->mEnableInconclusive->setCheckState(boolToCheckState(settings.value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool()));
mUI->mShowStatistics->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_STATISTICS, false).toBool()));
mUI->mShowErrorId->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_ERROR_ID, true).toBool()));
mUI->mCheckForUpdates->setCheckState(boolToCheckState(settings.value(SETTINGS_CHECK_FOR_UPDATES, false).toBool()));
mUI->mEditPythonPath->setText(settings.value(SETTINGS_PYTHON_PATH, QString()).toString());
validateEditPythonPath();
if (premium)
mUI->mGroupBoxMisra->setVisible(false);
mUI->mEditMisraFile->setText(settings.value(SETTINGS_MISRA_FILE, QString()).toString());
#ifdef Q_OS_WIN
//mUI->mTabClang->setVisible(true);
mUI->mEditClangPath->setText(settings.value(SETTINGS_CLANG_PATH, QString()).toString());
mUI->mEditVsIncludePaths->setText(settings.value(SETTINGS_VS_INCLUDE_PATHS, QString()).toString());
connect(mUI->mBtnBrowseClangPath, &QPushButton::released, this, &SettingsDialog::browseClangPath);
#else
mUI->mTabClang->setVisible(false);
#endif
mCurrentStyle = new CodeEditorStyle(CodeEditorStyle::loadSettings(&settings));
manageStyleControls();
connect(mUI->mEditPythonPath, SIGNAL(textEdited(QString)),
this, SLOT(validateEditPythonPath()));
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &SettingsDialog::ok);
connect(mUI->mButtons, &QDialogButtonBox::rejected, this, &SettingsDialog::reject);
connect(mUI->mBtnAddApplication, SIGNAL(clicked()),
this, SLOT(addApplication()));
connect(mUI->mBtnRemoveApplication, SIGNAL(clicked()),
this, SLOT(removeApplication()));
connect(mUI->mBtnEditApplication, SIGNAL(clicked()),
this, SLOT(editApplication()));
connect(mUI->mBtnDefaultApplication, SIGNAL(clicked()),
this, SLOT(defaultApplication()));
connect(mUI->mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(editApplication()));
connect(mUI->mBtnBrowsePythonPath, &QPushButton::clicked, this, &SettingsDialog::browsePythonPath);
connect(mUI->mBtnBrowseMisraFile, &QPushButton::clicked, this, &SettingsDialog::browseMisraFile);
connect(mUI->mBtnEditTheme, SIGNAL(clicked()), this, SLOT(editCodeEditorStyle()));
connect(mUI->mThemeSystem, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeDark, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeLight, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeCustom, SIGNAL(toggled(bool)), mUI->mBtnEditTheme, SLOT(setEnabled(bool)));
mUI->mListWidget->setSortingEnabled(false);
populateApplicationList();
const int count = QThread::idealThreadCount();
if (count != -1)
mUI->mLblIdealThreads->setText(QString::number(count));
else
mUI->mLblIdealThreads->setText(tr("N/A"));
loadSettings();
initTranslationsList();
}
SettingsDialog::~SettingsDialog()
{
saveSettings();
delete mCurrentStyle;
delete mUI;
}
void SettingsDialog::initTranslationsList()
{
const QString current = mTranslator->getCurrentLanguage();
for (const TranslationInfo& translation : mTranslator->getTranslations()) {
auto *item = new QListWidgetItem;
item->setText(translation.mName);
item->setData(mLangCodeRole, QVariant(translation.mCode));
mUI->mListLanguages->addItem(item);
if (translation.mCode == current || translation.mCode == current.mid(0, 2))
mUI->mListLanguages->setCurrentItem(item);
}
}
Qt::CheckState SettingsDialog::boolToCheckState(bool yes)
{
if (yes) {
return Qt::Checked;
}
return Qt::Unchecked;
}
bool SettingsDialog::checkStateToBool(Qt::CheckState state)
{
return state == Qt::Checked;
}
void SettingsDialog::loadSettings()
{
QSettings settings;
resize(settings.value(SETTINGS_CHECK_DIALOG_WIDTH, 800).toInt(),
settings.value(SETTINGS_CHECK_DIALOG_HEIGHT, 600).toInt());
}
void SettingsDialog::saveSettings() const
{
QSettings settings;
settings.setValue(SETTINGS_CHECK_DIALOG_WIDTH, size().width());
settings.setValue(SETTINGS_CHECK_DIALOG_HEIGHT, size().height());
}
void SettingsDialog::saveSettingValues() const
{
int jobs = mUI->mJobs->text().toInt();
if (jobs <= 0) {
jobs = 1;
}
QSettings settings;
settings.setValue(SETTINGS_CHECK_THREADS, jobs);
saveCheckboxValue(&settings, mUI->mForce, SETTINGS_CHECK_FORCE);
saveCheckboxValue(&settings, mUI->mSaveAllErrors, SETTINGS_SAVE_ALL_ERRORS);
saveCheckboxValue(&settings, mUI->mSaveFullPath, SETTINGS_SAVE_FULL_PATH);
saveCheckboxValue(&settings, mUI->mShowFullPath, SETTINGS_SHOW_FULL_PATH);
saveCheckboxValue(&settings, mUI->mShowNoErrorsMessage, SETTINGS_SHOW_NO_ERRORS);
saveCheckboxValue(&settings, mUI->mShowDebugWarnings, SETTINGS_SHOW_DEBUG_WARNINGS);
saveCheckboxValue(&settings, mUI->mInlineSuppressions, SETTINGS_INLINE_SUPPRESSIONS);
saveCheckboxValue(&settings, mUI->mEnableInconclusive, SETTINGS_INCONCLUSIVE_ERRORS);
saveCheckboxValue(&settings, mUI->mShowStatistics, SETTINGS_SHOW_STATISTICS);
saveCheckboxValue(&settings, mUI->mShowErrorId, SETTINGS_SHOW_ERROR_ID);
saveCheckboxValue(&settings, mUI->mCheckForUpdates, SETTINGS_CHECK_FOR_UPDATES);
settings.setValue(SETTINGS_PYTHON_PATH, mUI->mEditPythonPath->text());
if (!mPremium)
settings.setValue(SETTINGS_MISRA_FILE, mUI->mEditMisraFile->text());
#ifdef Q_OS_WIN
settings.setValue(SETTINGS_CLANG_PATH, mUI->mEditClangPath->text());
settings.setValue(SETTINGS_VS_INCLUDE_PATHS, mUI->mEditVsIncludePaths->text());
#endif
const QListWidgetItem *currentLang = mUI->mListLanguages->currentItem();
if (currentLang) {
const QString langcode = currentLang->data(mLangCodeRole).toString();
settings.setValue(SETTINGS_LANGUAGE, langcode);
}
CodeEditorStyle::saveSettings(&settings, *mCurrentStyle);
}
void SettingsDialog::saveCheckboxValue(QSettings *settings, const QCheckBox *box,
const QString &name)
{
settings->setValue(name, checkStateToBool(box->checkState()));
}
void SettingsDialog::validateEditPythonPath()
{
const auto pythonPath = mUI->mEditPythonPath->text();
if (pythonPath.isEmpty()) {
mUI->mEditPythonPath->setStyleSheet("");
mUI->mPythonPathWarning->hide();
return;
}
QFileInfo pythonPathInfo(pythonPath);
if (!pythonPathInfo.exists() ||
!pythonPathInfo.isFile() ||
!pythonPathInfo.isExecutable()) {
mUI->mEditPythonPath->setStyleSheet("QLineEdit {border: 1px solid red}");
mUI->mPythonPathWarning->setText(tr("The executable file \"%1\" is not available").arg(pythonPath));
mUI->mPythonPathWarning->show();
} else {
mUI->mEditPythonPath->setStyleSheet("");
mUI->mPythonPathWarning->hide();
}
}
void SettingsDialog::addApplication()
{
Application app;
ApplicationDialog dialog(tr("Add a new application"), app, this);
if (dialog.exec() == QDialog::Accepted) {
mTempApplications->addApplication(app);
mUI->mListWidget->addItem(app.getName());
}
}
void SettingsDialog::removeApplication()
{
for (QListWidgetItem *item : mUI->mListWidget->selectedItems()) {
const int removeIndex = mUI->mListWidget->row(item);
const int currentDefault = mTempApplications->getDefaultApplication();
mTempApplications->removeApplication(removeIndex);
if (removeIndex == currentDefault)
// If default app is removed set default to unknown
mTempApplications->setDefault(-1);
else if (removeIndex < currentDefault)
// Move default app one up if earlier app was removed
mTempApplications->setDefault(currentDefault - 1);
}
mUI->mListWidget->clear();
populateApplicationList();
}
void SettingsDialog::editApplication()
{
for (QListWidgetItem *item : mUI->mListWidget->selectedItems()) {
const int row = mUI->mListWidget->row(item);
Application& app = mTempApplications->getApplication(row);
ApplicationDialog dialog(tr("Modify an application"), app, this);
if (dialog.exec() == QDialog::Accepted) {
QString name = app.getName();
if (mTempApplications->getDefaultApplication() == row)
name += tr(" [Default]");
item->setText(name);
}
}
}
void SettingsDialog::defaultApplication()
{
QList<QListWidgetItem *> selected = mUI->mListWidget->selectedItems();
if (!selected.isEmpty()) {
const int index = mUI->mListWidget->row(selected[0]);
mTempApplications->setDefault(index);
mUI->mListWidget->clear();
populateApplicationList();
}
}
void SettingsDialog::populateApplicationList()
{
const int defapp = mTempApplications->getDefaultApplication();
for (int i = 0; i < mTempApplications->getApplicationCount(); i++) {
const Application& app = mTempApplications->getApplication(i);
QString name = app.getName();
if (i == defapp) {
name += " ";
name += tr("[Default]");
}
mUI->mListWidget->addItem(name);
}
// Select default application, or if there is no default app then the
// first item.
if (defapp == -1)
mUI->mListWidget->setCurrentRow(0);
else {
if (mTempApplications->getApplicationCount() > defapp)
mUI->mListWidget->setCurrentRow(defapp);
else
mUI->mListWidget->setCurrentRow(0);
}
}
void SettingsDialog::ok()
{
mApplications->copy(mTempApplications);
accept();
}
bool SettingsDialog::showFullPath() const
{
return checkStateToBool(mUI->mShowFullPath->checkState());
}
bool SettingsDialog::saveFullPath() const
{
return checkStateToBool(mUI->mSaveFullPath->checkState());
}
bool SettingsDialog::saveAllErrors() const
{
return checkStateToBool(mUI->mSaveAllErrors->checkState());
}
bool SettingsDialog::showNoErrorsMessage() const
{
return checkStateToBool(mUI->mShowNoErrorsMessage->checkState());
}
bool SettingsDialog::showErrorId() const
{
return checkStateToBool(mUI->mShowErrorId->checkState());
}
bool SettingsDialog::showInconclusive() const
{
return checkStateToBool(mUI->mEnableInconclusive->checkState());
}
void SettingsDialog::browsePythonPath()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Select python binary"), QDir::rootPath());
if (fileName.contains("python", Qt::CaseInsensitive))
mUI->mEditPythonPath->setText(fileName);
}
void SettingsDialog::browseMisraFile()
{
const QString fileName = QFileDialog::getOpenFileName(this, tr("Select MISRA File"), QDir::homePath(), "Misra File (*.pdf *.txt)");
if (!fileName.isEmpty())
mUI->mEditMisraFile->setText(fileName);
}
// Slot to set default light style
void SettingsDialog::setCodeEditorStyleDefault()
{
if (mUI->mThemeSystem->isChecked())
*mCurrentStyle = CodeEditorStyle::getSystemTheme();
if (mUI->mThemeLight->isChecked())
*mCurrentStyle = defaultStyleLight;
if (mUI->mThemeDark->isChecked())
*mCurrentStyle = defaultStyleDark;
manageStyleControls();
}
// Slot to edit custom style
void SettingsDialog::editCodeEditorStyle()
{
StyleEditDialog dlg(*mCurrentStyle, this);
const int nResult = dlg.exec();
if (nResult == QDialog::Accepted) {
*mCurrentStyle = dlg.getStyle();
manageStyleControls();
}
}
void SettingsDialog::browseClangPath()
{
QString selectedDir = QFileDialog::getExistingDirectory(this,
tr("Select clang path"),
QDir::rootPath());
if (!selectedDir.isEmpty()) {
mUI->mEditClangPath->setText(selectedDir);
}
}
void SettingsDialog::manageStyleControls()
{
const bool isSystemTheme = mCurrentStyle->isSystemTheme();
const bool isDefaultLight = !isSystemTheme && *mCurrentStyle == defaultStyleLight;
const bool isDefaultDark = !isSystemTheme && *mCurrentStyle == defaultStyleDark;
mUI->mThemeSystem->setChecked(isSystemTheme);
mUI->mThemeLight->setChecked(isDefaultLight && !isDefaultDark);
mUI->mThemeDark->setChecked(!isDefaultLight && isDefaultDark);
mUI->mThemeCustom->setChecked(!isSystemTheme && !isDefaultLight && !isDefaultDark);
mUI->mBtnEditTheme->setEnabled(!isSystemTheme && !isDefaultLight && !isDefaultDark);
}
| 15,586
|
C++
|
.cpp
| 370
| 36.754054
| 135
| 0.715284
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,336
|
libraryeditargdialog.cpp
|
danmar_cppcheck/gui/libraryeditargdialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libraryeditargdialog.h"
#include "ui_libraryeditargdialog.h"
#include <QCheckBox>
#include <QComboBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QString>
#include <QStringList>
class QWidget;
LibraryEditArgDialog::LibraryEditArgDialog(QWidget *parent, const CppcheckLibraryData::Function::Arg &arg) :
QDialog(parent),
mUi(new Ui::LibraryEditArgDialog),
mMinSizes(arg.minsizes)
{
mUi->setupUi(this);
mUi->notbool->setChecked(arg.notbool);
mUi->notnull->setChecked(arg.notnull);
mUi->notuninit->setChecked(arg.notuninit);
mUi->strz->setChecked(arg.strz);
mUi->formatstr->setChecked(arg.formatstr);
mUi->valid->setText(arg.valid);
mUi->minsize1type->setEnabled(true);
mUi->minsize1arg->setEnabled(arg.minsizes.count() >= 1);
mUi->minsize1arg2->setEnabled(arg.minsizes.count() >= 1 && arg.minsizes[0].type == "mul");
mUi->minsize2type->setEnabled(arg.minsizes.count() >= 1);
mUi->minsize2arg->setEnabled(arg.minsizes.count() >= 2);
mUi->minsize2arg2->setEnabled(arg.minsizes.count() >= 2 && arg.minsizes[1].type == "mul");
QStringList items;
items << "None" << "argvalue" << "mul" << "sizeof" << "strlen";
mUi->minsize1type->clear();
mUi->minsize1type->addItems(items);
if (arg.minsizes.count() >= 1) {
mUi->minsize1type->setCurrentIndex(items.indexOf(mMinSizes[0].type));
mUi->minsize1arg->setValue(mMinSizes[0].arg.toInt());
if (arg.minsizes[0].type == "mul")
mUi->minsize1arg2->setValue(mMinSizes[0].arg2.toInt());
else
mUi->minsize1arg2->setValue(0);
} else {
mUi->minsize1type->setCurrentIndex(0);
mUi->minsize1arg->setValue(0);
mUi->minsize1arg2->setValue(0);
}
mUi->minsize2type->clear();
mUi->minsize2type->addItems(items);
if (arg.minsizes.count() >= 2) {
mUi->minsize2type->setCurrentIndex(items.indexOf(mMinSizes[1].type));
mUi->minsize2arg->setValue(mMinSizes[1].arg.toInt());
if (arg.minsizes[1].type == "mul")
mUi->minsize2arg2->setValue(mMinSizes[1].arg2.toInt());
else
mUi->minsize2arg2->setValue(0);
} else {
mUi->minsize2type->setCurrentIndex(0);
mUi->minsize2arg->setValue(0);
mUi->minsize2arg2->setValue(0);
}
}
LibraryEditArgDialog::~LibraryEditArgDialog()
{
delete mUi;
}
CppcheckLibraryData::Function::Arg LibraryEditArgDialog::getArg() const
{
CppcheckLibraryData::Function::Arg ret;
ret.notbool = mUi->notbool->isChecked();
ret.notnull = mUi->notnull->isChecked();
ret.notuninit = mUi->notuninit->isChecked();
ret.strz = mUi->strz->isChecked();
ret.formatstr = mUi->formatstr->isChecked();
if (mUi->minsize1type->currentIndex() != 0) {
CppcheckLibraryData::Function::Arg::MinSize minsize1;
minsize1.type = mUi->minsize1type->currentText();
minsize1.arg = QString::number(mUi->minsize1arg->value());
if (minsize1.type == "mul")
minsize1.arg2 = QString::number(mUi->minsize1arg2->value());
ret.minsizes.append(minsize1);
if (mUi->minsize2type->currentIndex() != 0) {
CppcheckLibraryData::Function::Arg::MinSize minsize2;
minsize2.type = mUi->minsize2type->currentText();
minsize2.arg = QString::number(mUi->minsize2arg->value());
if (minsize2.type == "mul")
minsize2.arg2 = QString::number(mUi->minsize2arg2->value());
ret.minsizes.append(minsize2);
}
}
ret.valid = mUi->valid->text();
return ret;
}
void LibraryEditArgDialog::minsizeChanged()
{
mUi->minsize1arg->setEnabled(mUi->minsize1type->currentIndex() != 0);
mUi->minsize1arg2->setEnabled(mUi->minsize1type->currentText() == "mul");
mUi->minsize2type->setEnabled(mUi->minsize1type->currentIndex() != 0);
mUi->minsize2arg->setEnabled(mUi->minsize2type->currentIndex() != 0);
mUi->minsize2arg2->setEnabled(mUi->minsize2type->currentText() == "mul");
}
| 4,803
|
C++
|
.cpp
| 114
| 36.666667
| 108
| 0.676005
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,337
|
projectfile.cpp
|
danmar_cppcheck/gui/projectfile.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "projectfile.h"
#include "common.h"
#include "config.h"
#include "importproject.h"
#include "settings.h"
#include "utils.h"
#include <utility>
#include <QFile>
#include <QDir>
#include <QIODevice>
#include <QLatin1String>
#include <QRegularExpression>
#include <QXmlStreamAttributes>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QStringRef>
#endif
ProjectFile *ProjectFile::mActiveProject;
ProjectFile::ProjectFile(QObject *parent) :
QObject(parent)
{
clear();
}
ProjectFile::ProjectFile(QString filename, QObject *parent) :
QObject(parent),
mFilename(std::move(filename))
{
clear();
read();
}
void ProjectFile::clear()
{
const Settings settings;
clangParser = false;
mCheckLevel = CheckLevel::normal;
mRootPath.clear();
mBuildDir.clear();
mImportProject.clear();
mIncludeDirs.clear();
mDefines.clear();
mUndefines.clear();
mPaths.clear();
mExcludedPaths.clear();
mLibraries.clear();
mPlatform.clear();
mProjectName.clear();
mSuppressions.clear();
mAddons.clear();
mClangAnalyzer = mClangTidy = false;
mAnalyzeAllVsConfigs = false;
mCheckHeaders = true;
mCheckUnusedTemplates = true;
mInlineSuppression = true;
mMaxCtuDepth = settings.maxCtuDepth;
mMaxTemplateRecursion = settings.maxTemplateRecursion;
mCheckUnknownFunctionReturn.clear();
safeChecks.clear();
mVsConfigurations.clear();
mTags.clear();
mWarningTags.clear();
// Premium
mBughunting = false;
mCertIntPrecision = 0;
mCodingStandards.clear();
mPremiumLicenseFile.clear();
}
bool ProjectFile::read(const QString &filename)
{
if (!filename.isEmpty())
mFilename = filename;
QFile file(mFilename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
clear();
QXmlStreamReader xmlReader(&file);
bool insideProject = false;
bool projectTagFound = false;
while (!xmlReader.atEnd()) {
switch (xmlReader.readNext()) {
case QXmlStreamReader::StartElement:
if (xmlReader.name() == QString(CppcheckXml::ProjectElementName)) {
insideProject = true;
projectTagFound = true;
break;
}
if (!insideProject)
break;
// Read root path from inside project element
if (xmlReader.name() == QString(CppcheckXml::RootPathName))
readRootPath(xmlReader);
// Read root path from inside project element
if (xmlReader.name() == QString(CppcheckXml::BuildDirElementName))
readBuildDir(xmlReader);
// Find paths to check from inside project element
if (xmlReader.name() == QString(CppcheckXml::PathsElementName))
readCheckPaths(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::ImportProjectElementName))
readImportProject(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::AnalyzeAllVsConfigsElementName))
mAnalyzeAllVsConfigs = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::Parser))
clangParser = true;
if (xmlReader.name() == QString(CppcheckXml::CheckHeadersElementName))
mCheckHeaders = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::CheckUnusedTemplatesElementName))
mCheckUnusedTemplates = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::InlineSuppression))
mInlineSuppression = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::CheckLevelExhaustiveElementName))
mCheckLevel = CheckLevel::exhaustive;
// Find include directory from inside project element
if (xmlReader.name() == QString(CppcheckXml::IncludeDirElementName))
readIncludeDirs(xmlReader);
// Find preprocessor define from inside project element
if (xmlReader.name() == QString(CppcheckXml::DefinesElementName))
readDefines(xmlReader);
// Find preprocessor define from inside project element
if (xmlReader.name() == QString(CppcheckXml::UndefinesElementName))
readStringList(mUndefines, xmlReader, CppcheckXml::UndefineName);
// Find exclude list from inside project element
if (xmlReader.name() == QString(CppcheckXml::ExcludeElementName))
readExcludes(xmlReader);
// Find ignore list from inside project element
// These are read for compatibility
if (xmlReader.name() == QString(CppcheckXml::IgnoreElementName))
readExcludes(xmlReader);
// Find libraries list from inside project element
if (xmlReader.name() == QString(CppcheckXml::LibrariesElementName))
readStringList(mLibraries, xmlReader, CppcheckXml::LibraryElementName);
if (xmlReader.name() == QString(CppcheckXml::PlatformElementName))
readPlatform(xmlReader);
// Find suppressions list from inside project element
if (xmlReader.name() == QString(CppcheckXml::SuppressionsElementName))
readSuppressions(xmlReader);
// Unknown function return values
if (xmlReader.name() == QString(CppcheckXml::CheckUnknownFunctionReturn))
readStringList(mCheckUnknownFunctionReturn, xmlReader, CppcheckXml::Name);
// check all function parameter values
if (xmlReader.name() == QString(Settings::SafeChecks::XmlRootName))
safeChecks.loadFromXml(xmlReader);
// Addons
if (xmlReader.name() == QString(CppcheckXml::AddonsElementName))
readStringList(mAddons, xmlReader, CppcheckXml::AddonElementName);
// Tools
if (xmlReader.name() == QString(CppcheckXml::ToolsElementName)) {
QStringList tools;
readStringList(tools, xmlReader, CppcheckXml::ToolElementName);
mClangAnalyzer = tools.contains(CLANG_ANALYZER);
mClangTidy = tools.contains(CLANG_TIDY);
}
if (xmlReader.name() == QString(CppcheckXml::TagsElementName))
readStringList(mTags, xmlReader, CppcheckXml::TagElementName);
if (xmlReader.name() == QString(CppcheckXml::TagWarningsElementName))
readTagWarnings(xmlReader, xmlReader.attributes().value(QString(), CppcheckXml::TagAttributeName).toString());
if (xmlReader.name() == QString(CppcheckXml::MaxCtuDepthElementName))
mMaxCtuDepth = readInt(xmlReader, mMaxCtuDepth);
if (xmlReader.name() == QString(CppcheckXml::MaxTemplateRecursionElementName))
mMaxTemplateRecursion = readInt(xmlReader, mMaxTemplateRecursion);
// VSConfiguration
if (xmlReader.name() == QString(CppcheckXml::VSConfigurationElementName))
readVsConfigurations(xmlReader);
// Cppcheck Premium
if (xmlReader.name() == QString(CppcheckXml::BughuntingElementName))
mBughunting = true;
if (xmlReader.name() == QString(CppcheckXml::CodingStandardsElementName))
readStringList(mCodingStandards, xmlReader, CppcheckXml::CodingStandardElementName);
if (xmlReader.name() == QString(CppcheckXml::CertIntPrecisionElementName))
mCertIntPrecision = readInt(xmlReader, 0);
if (xmlReader.name() == QString(CppcheckXml::LicenseFileElementName))
mPremiumLicenseFile = readString(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::ProjectNameElementName))
mProjectName = readString(xmlReader);
break;
case QXmlStreamReader::EndElement:
if (xmlReader.name() == QString(CppcheckXml::ProjectElementName))
insideProject = false;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
}
file.close();
return projectTagFound;
}
void ProjectFile::readRootPath(const QXmlStreamReader &reader)
{
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::RootPathNameAttrib).toString();
if (!name.isEmpty())
mRootPath = name;
}
void ProjectFile::readBuildDir(QXmlStreamReader &reader)
{
mBuildDir.clear();
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mBuildDir = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readImportProject(QXmlStreamReader &reader)
{
mImportProject.clear();
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mImportProject = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
bool ProjectFile::readBool(QXmlStreamReader &reader)
{
bool ret = false;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = (reader.text().toString() == "true");
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
int ProjectFile::readInt(QXmlStreamReader &reader, int defaultValue)
{
int ret = defaultValue;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = reader.text().toString().toInt();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
QString ProjectFile::readString(QXmlStreamReader &reader)
{
QString ret;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readIncludeDirs(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read dir-elements
if (reader.name().toString() == CppcheckXml::DirElementName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::DirNameAttrib).toString();
if (!name.isEmpty())
mIncludeDirs << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::IncludeDirElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readDefines(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read define-elements
if (reader.name().toString() == CppcheckXml::DefineName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::DefineNameAttrib).toString();
if (!name.isEmpty())
mDefines << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::DefinesElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readCheckPaths(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read dir-elements
if (reader.name().toString() == CppcheckXml::PathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::PathNameAttrib).toString();
if (!name.isEmpty())
mPaths << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::PathsElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readExcludes(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read exclude-elements
if (reader.name().toString() == CppcheckXml::ExcludePathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::ExcludePathNameAttrib).toString();
if (!name.isEmpty())
mExcludedPaths << name;
}
// Read ignore-elements - deprecated but support reading them
else if (reader.name().toString() == CppcheckXml::IgnorePathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::IgnorePathNameAttrib).toString();
if (!name.isEmpty())
mExcludedPaths << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::IgnoreElementName)
allRead = true;
if (reader.name().toString() == CppcheckXml::ExcludeElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readVsConfigurations(QXmlStreamReader &reader)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::VSConfigurationName) {
QString config;
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
config = reader.text().toString();
}
mVsConfigurations << config;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::VSConfigurationName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readPlatform(QXmlStreamReader &reader)
{
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mPlatform = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readSuppressions(QXmlStreamReader &reader)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::SuppressionElementName) {
SuppressionList::Suppression suppression;
if (reader.attributes().hasAttribute(QString(),"fileName"))
suppression.fileName = reader.attributes().value(QString(),"fileName").toString().toStdString();
if (reader.attributes().hasAttribute(QString(),"lineNumber"))
suppression.lineNumber = reader.attributes().value(QString(),"lineNumber").toInt();
if (reader.attributes().hasAttribute(QString(),"symbolName"))
suppression.symbolName = reader.attributes().value(QString(),"symbolName").toString().toStdString();
if (reader.attributes().hasAttribute(QString(),"hash"))
suppression.hash = reader.attributes().value(QString(),"hash").toULongLong();
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
suppression.errorId = reader.text().toString().toStdString();
}
mSuppressions << suppression;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::SuppressionElementName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readTagWarnings(QXmlStreamReader &reader, const QString &tag)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::WarningElementName) {
const std::size_t hash = reader.attributes().value(QString(), CppcheckXml::HashAttributeName).toULongLong();
mWarningTags[hash] = tag;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::WarningElementName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[])
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == elementname) {
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
QString text = reader.text().toString();
stringlist << text;
}
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != elementname)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::setIncludes(const QStringList &includes)
{
mIncludeDirs = includes;
}
void ProjectFile::setDefines(const QStringList &defines)
{
mDefines = defines;
}
void ProjectFile::setUndefines(const QStringList &undefines)
{
mUndefines = undefines;
}
void ProjectFile::setCheckPaths(const QStringList &paths)
{
mPaths = paths;
}
void ProjectFile::setExcludedPaths(const QStringList &paths)
{
mExcludedPaths = paths;
}
void ProjectFile::setLibraries(const QStringList &libraries)
{
mLibraries = libraries;
}
void ProjectFile::setPlatform(const QString &platform)
{
mPlatform = platform;
}
QList<SuppressionList::Suppression> ProjectFile::getCheckingSuppressions() const
{
const QRegularExpression re1("^[a-zA-Z0-9_\\-]+/.*");
const QRegularExpression re2("^[^/]+$");
QList<SuppressionList::Suppression> result;
for (SuppressionList::Suppression suppression : mSuppressions) {
if (re1.match(suppression.fileName.c_str()).hasMatch() || re2.match(suppression.fileName.c_str()).hasMatch()) {
if (suppression.fileName[0] != '*')
suppression.fileName = QFileInfo(mFilename).absolutePath().toStdString() + "/" + suppression.fileName;
}
result << suppression;
}
return result;
}
void ProjectFile::setSuppressions(const QList<SuppressionList::Suppression> &suppressions)
{
mSuppressions = suppressions;
}
void ProjectFile::addSuppression(const SuppressionList::Suppression &suppression)
{
mSuppressions.append(suppression);
}
void ProjectFile::setAddons(const QStringList &addons)
{
mAddons = addons;
}
void ProjectFile::setVSConfigurations(const QStringList &vsConfigs)
{
mVsConfigurations = vsConfigs;
}
void ProjectFile::setCheckLevel(ProjectFile::CheckLevel checkLevel)
{
mCheckLevel = checkLevel;
}
bool ProjectFile::isCheckLevelExhaustive() const
{
return mCheckLevel == CheckLevel::exhaustive;
}
void ProjectFile::setWarningTags(std::size_t hash, const QString& tags)
{
if (tags.isEmpty())
mWarningTags.erase(hash);
else if (hash > 0)
mWarningTags[hash] = tags;
}
QString ProjectFile::getWarningTags(std::size_t hash) const
{
auto it = mWarningTags.find(hash);
return (it != mWarningTags.end()) ? it->second : QString();
}
bool ProjectFile::write(const QString &filename)
{
if (!filename.isEmpty())
mFilename = filename;
QFile file(mFilename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument("1.0");
xmlWriter.writeStartElement(CppcheckXml::ProjectElementName);
xmlWriter.writeAttribute(CppcheckXml::ProjectVersionAttrib, CppcheckXml::ProjectFileVersion);
if (!mRootPath.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::RootPathName);
xmlWriter.writeAttribute(CppcheckXml::RootPathNameAttrib, mRootPath);
xmlWriter.writeEndElement();
}
if (!mBuildDir.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::BuildDirElementName);
xmlWriter.writeCharacters(mBuildDir);
xmlWriter.writeEndElement();
}
if (!mPlatform.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::PlatformElementName);
xmlWriter.writeCharacters(mPlatform);
xmlWriter.writeEndElement();
}
if (!mImportProject.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ImportProjectElementName);
xmlWriter.writeCharacters(mImportProject);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement(CppcheckXml::AnalyzeAllVsConfigsElementName);
xmlWriter.writeCharacters(bool_to_string(mAnalyzeAllVsConfigs));
xmlWriter.writeEndElement();
if (clangParser) {
xmlWriter.writeStartElement(CppcheckXml::Parser);
xmlWriter.writeCharacters("clang");
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement(CppcheckXml::CheckHeadersElementName);
xmlWriter.writeCharacters(bool_to_string(mCheckHeaders));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::CheckUnusedTemplatesElementName);
xmlWriter.writeCharacters(bool_to_string(mCheckUnusedTemplates));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::InlineSuppression);
xmlWriter.writeCharacters(bool_to_string(mInlineSuppression));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::MaxCtuDepthElementName);
xmlWriter.writeCharacters(QString::number(mMaxCtuDepth));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::MaxTemplateRecursionElementName);
xmlWriter.writeCharacters(QString::number(mMaxTemplateRecursion));
xmlWriter.writeEndElement();
if (!mIncludeDirs.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::IncludeDirElementName);
for (const QString& incdir : mIncludeDirs) {
xmlWriter.writeStartElement(CppcheckXml::DirElementName);
xmlWriter.writeAttribute(CppcheckXml::DirNameAttrib, incdir);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mDefines.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::DefinesElementName);
for (const QString& define : mDefines) {
xmlWriter.writeStartElement(CppcheckXml::DefineName);
xmlWriter.writeAttribute(CppcheckXml::DefineNameAttrib, define);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mVsConfigurations.isEmpty()) {
writeStringList(xmlWriter,
mVsConfigurations,
CppcheckXml::VSConfigurationElementName,
CppcheckXml::VSConfigurationName);
}
writeStringList(xmlWriter,
mUndefines,
CppcheckXml::UndefinesElementName,
CppcheckXml::UndefineName);
if (!mPaths.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::PathsElementName);
for (const QString& path : mPaths) {
xmlWriter.writeStartElement(CppcheckXml::PathName);
xmlWriter.writeAttribute(CppcheckXml::PathNameAttrib, path);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mExcludedPaths.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ExcludeElementName);
for (const QString& path : mExcludedPaths) {
xmlWriter.writeStartElement(CppcheckXml::ExcludePathName);
xmlWriter.writeAttribute(CppcheckXml::ExcludePathNameAttrib, path);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mLibraries,
CppcheckXml::LibrariesElementName,
CppcheckXml::LibraryElementName);
if (!mSuppressions.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::SuppressionsElementName);
for (const SuppressionList::Suppression &suppression : mSuppressions) {
xmlWriter.writeStartElement(CppcheckXml::SuppressionElementName);
if (!suppression.fileName.empty())
xmlWriter.writeAttribute("fileName", QString::fromStdString(suppression.fileName));
if (suppression.lineNumber > 0)
xmlWriter.writeAttribute("lineNumber", QString::number(suppression.lineNumber));
if (!suppression.symbolName.empty())
xmlWriter.writeAttribute("symbolName", QString::fromStdString(suppression.symbolName));
if (suppression.hash > 0)
xmlWriter.writeAttribute(CppcheckXml::HashAttributeName, QString::number(suppression.hash));
if (!suppression.errorId.empty())
xmlWriter.writeCharacters(QString::fromStdString(suppression.errorId));
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mCheckUnknownFunctionReturn,
CppcheckXml::CheckUnknownFunctionReturn,
CppcheckXml::Name);
safeChecks.saveToXml(xmlWriter);
writeStringList(xmlWriter,
mAddons,
CppcheckXml::AddonsElementName,
CppcheckXml::AddonElementName);
QStringList tools;
if (mClangAnalyzer)
tools << CLANG_ANALYZER;
if (mClangTidy)
tools << CLANG_TIDY;
writeStringList(xmlWriter,
tools,
CppcheckXml::ToolsElementName,
CppcheckXml::ToolElementName);
writeStringList(xmlWriter, mTags, CppcheckXml::TagsElementName, CppcheckXml::TagElementName);
if (!mWarningTags.empty()) {
QStringList tags;
for (const auto& wt: mWarningTags) {
if (!tags.contains(wt.second))
tags.append(wt.second);
}
for (const QString &tag: tags) {
xmlWriter.writeStartElement(CppcheckXml::TagWarningsElementName);
xmlWriter.writeAttribute(CppcheckXml::TagAttributeName, tag);
for (const auto& wt: mWarningTags) {
if (wt.second == tag) {
xmlWriter.writeStartElement(CppcheckXml::WarningElementName);
xmlWriter.writeAttribute(CppcheckXml::HashAttributeName, QString::number(wt.first));
xmlWriter.writeEndElement();
}
}
xmlWriter.writeEndElement();
}
}
if (mCheckLevel == CheckLevel::exhaustive) {
xmlWriter.writeStartElement(CppcheckXml::CheckLevelExhaustiveElementName);
xmlWriter.writeEndElement();
}
// Cppcheck Premium
if (mBughunting) {
xmlWriter.writeStartElement(CppcheckXml::BughuntingElementName);
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mCodingStandards,
CppcheckXml::CodingStandardsElementName,
CppcheckXml::CodingStandardElementName);
if (mCertIntPrecision > 0) {
xmlWriter.writeStartElement(CppcheckXml::CertIntPrecisionElementName);
xmlWriter.writeCharacters(QString::number(mCertIntPrecision));
xmlWriter.writeEndElement();
}
if (!mProjectName.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ProjectNameElementName);
xmlWriter.writeCharacters(mProjectName);
xmlWriter.writeEndElement();
}
if (!mPremiumLicenseFile.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::LicenseFileElementName);
xmlWriter.writeCharacters(mPremiumLicenseFile);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndDocument();
file.close();
return true;
}
void ProjectFile::writeStringList(QXmlStreamWriter &xmlWriter, const QStringList &stringlist, const char startelementname[], const char stringelementname[])
{
if (stringlist.isEmpty())
return;
xmlWriter.writeStartElement(startelementname);
for (const QString& str : stringlist) {
xmlWriter.writeStartElement(stringelementname);
xmlWriter.writeCharacters(str);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
QStringList ProjectFile::fromNativeSeparators(const QStringList &paths)
{
QStringList ret;
for (const QString &path : paths)
ret << QDir::fromNativeSeparators(path);
return ret;
}
QStringList ProjectFile::getAddonsAndTools() const
{
QStringList ret(mAddons);
if (mClangAnalyzer)
ret << CLANG_ANALYZER;
if (mClangTidy)
ret << CLANG_TIDY;
return ret;
}
void ProjectFile::SafeChecks::loadFromXml(QXmlStreamReader &xmlReader)
{
classes = externalFunctions = internalFunctions = externalVariables = false;
int level = 0;
do {
const QXmlStreamReader::TokenType type = xmlReader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
++level;
if (xmlReader.name() == QString(Settings::SafeChecks::XmlClasses))
classes = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlExternalFunctions))
externalFunctions = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlInternalFunctions))
internalFunctions = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlExternalVariables))
externalVariables = true;
break;
case QXmlStreamReader::EndElement:
if (level <= 0)
return;
level--;
break;
// Not handled
case QXmlStreamReader::Characters:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::SafeChecks::saveToXml(QXmlStreamWriter &xmlWriter) const
{
if (!classes && !externalFunctions && !internalFunctions && !externalVariables)
return;
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlRootName));
if (classes) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlClasses));
xmlWriter.writeEndElement();
}
if (externalFunctions) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlExternalFunctions));
xmlWriter.writeEndElement();
}
if (internalFunctions) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlInternalFunctions));
xmlWriter.writeEndElement();
}
if (externalVariables) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlExternalVariables));
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
QString ProjectFile::getAddonFilePath(QString filesDir, const QString &addon)
{
if (QFile(addon).exists())
return addon;
if (!filesDir.endsWith("/"))
filesDir += "/";
QStringList searchPaths;
searchPaths << filesDir << (filesDir + "addons/") << (filesDir + "../addons/")
#ifdef FILESDIR
<< (QLatin1String(FILESDIR) + "/addons/")
#endif
;
for (const QString& path : searchPaths) {
QString f = path + addon + ".py";
if (QFile(f).exists())
return f;
}
return QString();
}
| 40,714
|
C++
|
.cpp
| 1,026
| 30.782651
| 156
| 0.65645
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,338
|
resultsview.cpp
|
danmar_cppcheck/gui/resultsview.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resultsview.h"
#include "checkstatistics.h"
#include "checkersreport.h"
#include "codeeditor.h"
#include "codeeditorstyle.h"
#include "common.h"
#include "csvreport.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "printablereport.h"
#include "resultstree.h"
#include "settings.h"
#include "txtreport.h"
#include "xmlreport.h"
#include "xmlreportv2.h"
#include "ui_resultsview.h"
#include <set>
#include <string>
#include <QAbstractItemModel>
#include <QApplication>
#include <QByteArray>
#include <QClipboard>
#include <QDate>
#include <QDateTime>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QLabel>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QPoint>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QProgressBar>
#include <QSettings>
#include <QSplitter>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTextDocument>
#include <QTextEdit>
#include <QTextStream>
#include <QVariant>
#include <QVariantMap>
#include <Qt>
ResultsView::ResultsView(QWidget * parent) :
QWidget(parent),
mUI(new Ui::ResultsView),
mStatistics(new CheckStatistics(this))
{
mUI->setupUi(this);
connect(mUI->mTree, &ResultsTree::resultsHidden, this, &ResultsView::resultsHidden);
connect(mUI->mTree, &ResultsTree::checkSelected, this, &ResultsView::checkSelected);
connect(mUI->mTree, &ResultsTree::treeSelectionChanged, this, &ResultsView::updateDetails);
connect(mUI->mTree, &ResultsTree::suppressIds, this, &ResultsView::suppressIds);
connect(this, &ResultsView::showResults, mUI->mTree, &ResultsTree::showResults);
connect(this, &ResultsView::showCppcheckResults, mUI->mTree, &ResultsTree::showCppcheckResults);
connect(this, &ResultsView::showClangResults, mUI->mTree, &ResultsTree::showClangResults);
connect(this, &ResultsView::collapseAllResults, mUI->mTree, &ResultsTree::collapseAll);
connect(this, &ResultsView::expandAllResults, mUI->mTree, &ResultsTree::expandAll);
connect(this, &ResultsView::showHiddenResults, mUI->mTree, &ResultsTree::showHiddenResults);
mUI->mListLog->setContextMenuPolicy(Qt::CustomContextMenu);
}
void ResultsView::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
mUI->mProgress->setMinimum(0);
mUI->mProgress->setVisible(false);
mUI->mLabelCriticalErrors->setVisible(false);
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI->mCode->setStyle(theStyle);
QByteArray state = settings->value(SETTINGS_MAINWND_SPLITTER_STATE).toByteArray();
mUI->mVerticalSplitter->restoreState(state);
mShowNoErrorsMessage = settings->value(SETTINGS_SHOW_NO_ERRORS, true).toBool();
mUI->mTree->initialize(settings, list, checkThreadHandler);
}
ResultsView::~ResultsView()
{
delete mUI;
delete mCheckSettings;
}
void ResultsView::clear(bool results)
{
if (results) {
mUI->mTree->clear();
}
mUI->mDetails->setText(QString());
mStatistics->clear();
delete mCheckSettings;
mCheckSettings = nullptr;
//Clear the progressbar
mUI->mProgress->setMaximum(PROGRESS_MAX);
mUI->mProgress->setValue(0);
mUI->mProgress->setFormat("%p%");
mUI->mLabelCriticalErrors->setVisible(false);
mSuccess = false;
}
void ResultsView::clear(const QString &filename)
{
mUI->mTree->clear(filename);
}
void ResultsView::clearRecheckFile(const QString &filename)
{
mUI->mTree->clearRecheckFile(filename);
}
const ShowTypes & ResultsView::getShowTypes() const
{
return mUI->mTree->mShowSeverities;
}
void ResultsView::setReportType(ReportType reportType) {
mUI->mTree->setReportType(reportType);
}
void ResultsView::progress(int value, const QString& description)
{
mUI->mProgress->setValue(value);
mUI->mProgress->setFormat(QString("%p% (%1)").arg(description));
}
void ResultsView::error(const ErrorItem &item)
{
if (item.severity == Severity::internal && (item.errorId == "logChecker" || item.errorId.endsWith("-logChecker"))) {
mStatistics->addChecker(item.message);
return;
}
handleCriticalError(item);
if (item.severity == Severity::internal)
return;
if (mUI->mTree->addErrorItem(item)) {
emit gotResults();
mStatistics->addItem(item.tool(), ShowTypes::SeverityToShowType(item.severity));
}
}
void ResultsView::filterResults(const QString& filter)
{
mUI->mTree->filterResults(filter);
}
void ResultsView::saveStatistics(const QString &filename) const
{
QFile f(filename);
if (!f.open(QIODevice::Text | QIODevice::Append))
return;
QTextStream ts(&f);
ts << '[' << QDate::currentDate().toString("dd.MM.yyyy") << "]\n";
ts << QDateTime::currentMSecsSinceEpoch() << '\n';
for (const QString& tool : mStatistics->getTools()) {
ts << tool << "-error:" << mStatistics->getCount(tool, ShowTypes::ShowErrors) << '\n';
ts << tool << "-warning:" << mStatistics->getCount(tool, ShowTypes::ShowWarnings) << '\n';
ts << tool << "-style:" << mStatistics->getCount(tool, ShowTypes::ShowStyle) << '\n';
ts << tool << "-performance:" << mStatistics->getCount(tool, ShowTypes::ShowPerformance) << '\n';
ts << tool << "-portability:" << mStatistics->getCount(tool, ShowTypes::ShowPortability) << '\n';
}
}
void ResultsView::updateFromOldReport(const QString &filename) const
{
mUI->mTree->updateFromOldReport(filename);
}
void ResultsView::save(const QString &filename, Report::Type type, const QString& productName) const
{
Report *report = nullptr;
switch (type) {
case Report::CSV:
report = new CsvReport(filename);
break;
case Report::TXT:
report = new TxtReport(filename);
break;
case Report::XMLV2:
report = new XmlReportV2(filename, productName);
break;
}
if (report) {
if (report->create())
mUI->mTree->saveResults(report);
else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
delete report;
report = nullptr;
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
}
void ResultsView::print()
{
QPrinter printer;
QPrintDialog dialog(&printer, this);
dialog.setWindowTitle(tr("Print Report"));
if (dialog.exec() != QDialog::Accepted)
return;
print(&printer);
}
void ResultsView::printPreview()
{
QPrinter printer;
QPrintPreviewDialog dialog(&printer, this);
connect(&dialog, SIGNAL(paintRequested(QPrinter*)), SLOT(print(QPrinter*)));
dialog.exec();
}
void ResultsView::print(QPrinter* printer)
{
if (!hasResults()) {
QMessageBox msgBox;
msgBox.setText(tr("No errors found, nothing to print."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
PrintableReport report;
mUI->mTree->saveResults(&report);
QTextDocument doc(report.getFormattedReportText());
doc.print(printer);
}
void ResultsView::updateSettings(bool showFullPath,
bool saveFullPath,
bool saveAllErrors,
bool showNoErrorsMessage,
bool showErrorId,
bool showInconclusive)
{
mUI->mTree->updateSettings(showFullPath, saveFullPath, saveAllErrors, showErrorId, showInconclusive);
mShowNoErrorsMessage = showNoErrorsMessage;
}
void ResultsView::updateStyleSetting(QSettings *settings)
{
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI->mCode->setStyle(theStyle);
}
void ResultsView::setCheckDirectory(const QString &dir)
{
mUI->mTree->setCheckDirectory(dir);
}
QString ResultsView::getCheckDirectory()
{
return mUI->mTree->getCheckDirectory();
}
void ResultsView::setCheckSettings(const Settings &settings)
{
delete mCheckSettings;
mCheckSettings = new Settings;
*mCheckSettings = settings;
}
void ResultsView::checkingStarted(int count)
{
mSuccess = true;
mUI->mProgress->setVisible(true);
mUI->mProgress->setMaximum(PROGRESS_MAX);
mUI->mProgress->setValue(0);
mUI->mProgress->setFormat(tr("%p% (%1 of %2 files checked)").arg(0).arg(count));
}
void ResultsView::checkingFinished()
{
mUI->mProgress->setVisible(false);
mUI->mProgress->setFormat("%p%");
{
Settings checkSettings;
const std::set<std::string> activeCheckers = mStatistics->getActiveCheckers();
CheckersReport checkersReport(mCheckSettings ? *mCheckSettings : checkSettings, activeCheckers);
mStatistics->setCheckersReport(QString::fromStdString(checkersReport.getReport(mCriticalErrors.toStdString())));
}
// TODO: Items can be mysteriously hidden when checking is finished, this function
// call should be redundant but it "unhides" the wrongly hidden items.
mUI->mTree->refreshTree();
//Should we inform user of non visible/not found errors?
if (mShowNoErrorsMessage) {
//Tell user that we found no errors
if (!hasResults()) {
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
tr("No errors found."),
QMessageBox::Ok,
this);
msg.exec();
} //If we have errors but they aren't visible, tell user about it
else if (!mUI->mTree->hasVisibleResults()) {
QString text = tr("Errors were found, but they are configured to be hidden.\n" \
"To toggle what kind of errors are shown, open view menu.");
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
text,
QMessageBox::Ok,
this);
msg.exec();
}
}
}
bool ResultsView::hasVisibleResults() const
{
return mUI->mTree->hasVisibleResults();
}
bool ResultsView::hasResults() const
{
return mUI->mTree->hasResults();
}
void ResultsView::saveSettings(QSettings *settings)
{
mUI->mTree->saveSettings();
QByteArray state = mUI->mVerticalSplitter->saveState();
settings->setValue(SETTINGS_MAINWND_SPLITTER_STATE, state);
mUI->mVerticalSplitter->restoreState(state);
}
void ResultsView::translate()
{
mUI->retranslateUi(this);
mUI->mTree->translate();
}
void ResultsView::disableProgressbar()
{
mUI->mProgress->setEnabled(false);
}
void ResultsView::readErrorsXml(const QString &filename)
{
mSuccess = false; // Don't know if results come from an aborted analysis
const int version = XmlReport::determineVersion(filename);
if (version == 0) {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
if (version == 1) {
QMessageBox msgBox;
msgBox.setText(tr("XML format version 1 is no longer supported."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
XmlReportV2 report(filename, QString());
QList<ErrorItem> errors;
if (report.open()) {
errors = report.read();
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
for (const ErrorItem& item : errors) {
handleCriticalError(item);
mUI->mTree->addErrorItem(item);
}
QString dir;
if (!errors.isEmpty() && !errors[0].errorPath.isEmpty()) {
QString relativePath = QFileInfo(filename).canonicalPath();
if (QFileInfo::exists(relativePath + '/' + errors[0].errorPath[0].file))
dir = relativePath;
}
mUI->mTree->setCheckDirectory(dir);
}
void ResultsView::updateDetails(const QModelIndex &index)
{
const auto *model = qobject_cast<const QStandardItemModel*>(mUI->mTree->model());
QStandardItem *item = model->itemFromIndex(index);
if (!item) {
mUI->mCode->clear();
mUI->mDetails->setText(QString());
return;
}
// Make sure we are working with the first column
if (item->parent() && item->column() != 0)
item = item->parent()->child(item->row(), 0);
QVariantMap itemdata = item->data().toMap();
// If there is no severity data then it is a parent item without summary and message
if (!itemdata.contains("severity")) {
mUI->mCode->clear();
mUI->mDetails->setText(QString());
return;
}
const QString message = itemdata["message"].toString();
QString formattedMsg = message;
const QString file0 = itemdata["file0"].toString();
if (!file0.isEmpty() && Path::isHeader(itemdata["file"].toString().toStdString()))
formattedMsg += QString("\n\n%1: %2").arg(tr("First included by")).arg(QDir::toNativeSeparators(file0));
if (itemdata["cwe"].toInt() > 0)
formattedMsg.prepend("CWE: " + QString::number(itemdata["cwe"].toInt()) + "\n");
if (mUI->mTree->showIdColumn())
formattedMsg.prepend(tr("Id") + ": " + itemdata["id"].toString() + "\n");
if (itemdata["incomplete"].toBool())
formattedMsg += "\n" + tr("Bug hunting analysis is incomplete");
mUI->mDetails->setText(formattedMsg);
const int lineNumber = itemdata["line"].toInt();
QString filepath = itemdata["file"].toString();
if (!QFileInfo::exists(filepath) && QFileInfo::exists(mUI->mTree->getCheckDirectory() + '/' + filepath))
filepath = mUI->mTree->getCheckDirectory() + '/' + filepath;
QStringList symbols;
if (itemdata.contains("symbolNames"))
symbols = itemdata["symbolNames"].toString().split("\n");
if (filepath == mUI->mCode->getFileName()) {
mUI->mCode->setError(lineNumber, symbols);
return;
}
QFile file(filepath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
mUI->mCode->clear();
return;
}
QTextStream in(&file);
mUI->mCode->setError(in.readAll(), lineNumber, symbols);
mUI->mCode->setFileName(filepath);
}
void ResultsView::log(const QString &str)
{
mUI->mListLog->addItem(str);
}
void ResultsView::debugError(const ErrorItem &item)
{
mUI->mListLog->addItem(item.toString());
}
void ResultsView::logClear()
{
mUI->mListLog->clear();
}
void ResultsView::logCopyEntry()
{
const QListWidgetItem * item = mUI->mListLog->currentItem();
if (nullptr != item) {
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(item->text());
}
}
void ResultsView::logCopyComplete()
{
QString logText;
for (int i=0; i < mUI->mListLog->count(); ++i) {
const QListWidgetItem * item = mUI->mListLog->item(i);
if (nullptr != item) {
logText += item->text();
}
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(logText);
}
void ResultsView::on_mListLog_customContextMenuRequested(const QPoint &pos)
{
if (mUI->mListLog->count() <= 0)
return;
const QPoint globalPos = mUI->mListLog->mapToGlobal(pos);
QMenu contextMenu;
contextMenu.addAction(tr("Clear Log"), this, SLOT(logClear()));
contextMenu.addAction(tr("Copy this Log entry"), this, SLOT(logCopyEntry()));
contextMenu.addAction(tr("Copy complete Log"), this, SLOT(logCopyComplete()));
contextMenu.exec(globalPos);
}
void ResultsView::stopAnalysis()
{
mSuccess = false;
mUI->mLabelCriticalErrors->setText(tr("Analysis was stopped"));
mUI->mLabelCriticalErrors->setVisible(true);
}
void ResultsView::handleCriticalError(const ErrorItem &item)
{
if (ErrorLogger::isCriticalErrorId(item.errorId.toStdString())) {
if (!mCriticalErrors.contains(item.errorId)) {
if (!mCriticalErrors.isEmpty())
mCriticalErrors += ",";
mCriticalErrors += item.errorId;
if (item.severity == Severity::internal)
mCriticalErrors += " (suppressed)";
}
QString msg = tr("There was a critical error with id '%1'").arg(item.errorId);
if (!item.file0.isEmpty())
msg += ", " + tr("when checking %1").arg(item.file0);
else
msg += ", " + tr("when checking a file");
msg += ". " + tr("Analysis was aborted.");
mUI->mLabelCriticalErrors->setText(msg);
mUI->mLabelCriticalErrors->setVisible(true);
mSuccess = false;
}
}
bool ResultsView::isSuccess() const {
return mSuccess;
}
| 17,820
|
C++
|
.cpp
| 501
| 30.067864
| 120
| 0.673089
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,339
|
platforms.cpp
|
danmar_cppcheck/gui/platforms.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platforms.h"
Platforms::Platforms(QObject *parent)
: QObject(parent)
{
init();
}
void Platforms::add(const QString &title, Platform::Type platform)
{
PlatformData plat;
plat.mTitle = title;
plat.mType = platform;
plat.mActMainWindow = nullptr;
mPlatforms << plat;
}
void Platforms::init()
{
add(tr("Native"), Platform::Type::Native);
add(tr("Unix 32-bit"), Platform::Type::Unix32);
add(tr("Unix 64-bit"), Platform::Type::Unix64);
add(tr("Windows 32-bit ANSI"), Platform::Type::Win32A);
add(tr("Windows 32-bit Unicode"), Platform::Type::Win32W);
add(tr("Windows 64-bit"), Platform::Type::Win64);
}
int Platforms::getCount() const
{
return mPlatforms.count();
}
PlatformData& Platforms::get(Platform::Type platform)
{
QList<PlatformData>::iterator iter = mPlatforms.begin();
while (iter != mPlatforms.end()) {
if (iter->mType == platform) {
return *iter;
}
++iter;
}
return mPlatforms.first();
}
| 1,768
|
C++
|
.cpp
| 55
| 28.781818
| 72
| 0.698301
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,340
|
projectfiledialog.cpp
|
danmar_cppcheck/gui/projectfiledialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "projectfiledialog.h"
#include "checkthread.h"
#include "common.h"
#include "importproject.h"
#include "library.h"
#include "newsuppressiondialog.h"
#include "platform.h"
#include "platforms.h"
#include "projectfile.h"
#include "settings.h"
#include "ui_projectfile.h"
#include <list>
#include <string>
#include <utility>
#include <QByteArray>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QFlags>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMap>
#include <QObject>
#include <QPushButton>
#include <QRadioButton>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QSettings>
#include <QSize>
#include <QSpinBox>
#include <QVariant>
static constexpr char ADDON_MISRA[] = "misra";
static constexpr char CODING_STANDARD_MISRA_C_2023[] = "misra-c-2023";
static constexpr char CODING_STANDARD_MISRA_CPP_2008[] = "misra-cpp-2008";
static constexpr char CODING_STANDARD_MISRA_CPP_2023[] = "misra-cpp-2023";
static constexpr char CODING_STANDARD_CERT_C[] = "cert-c-2016";
static constexpr char CODING_STANDARD_CERT_CPP[] = "cert-cpp-2016";
static constexpr char CODING_STANDARD_AUTOSAR[] = "autosar";
/** Return paths from QListWidget */
static QStringList getPaths(const QListWidget *list)
{
const int count = list->count();
QStringList paths;
for (int i = 0; i < count; i++) {
QListWidgetItem *item = list->item(i);
paths << QDir::fromNativeSeparators(item->text());
}
return paths;
}
/** Platforms shown in the platform combobox */
static constexpr Platform::Type builtinPlatforms[] = {
Platform::Type::Native,
Platform::Type::Win32A,
Platform::Type::Win32W,
Platform::Type::Win64,
Platform::Type::Unix32,
Platform::Type::Unix64
};
static constexpr int numberOfBuiltinPlatforms = sizeof(builtinPlatforms) / sizeof(builtinPlatforms[0]);
QStringList ProjectFileDialog::getProjectConfigs(const QString &fileName)
{
if (!fileName.endsWith(".sln") && !fileName.endsWith(".vcxproj"))
return QStringList();
QStringList ret;
ImportProject importer;
Settings projSettings;
importer.import(fileName.toStdString(), &projSettings);
for (const std::string &cfg : importer.getVSConfigs())
ret << QString::fromStdString(cfg);
return ret;
}
ProjectFileDialog::ProjectFileDialog(ProjectFile *projectFile, bool premium, QWidget *parent)
: QDialog(parent)
, mUI(new Ui::ProjectFile)
, mProjectFile(projectFile)
, mPremium(premium)
{
mUI->setupUi(this);
mUI->mToolClangAnalyzer->hide();
const QFileInfo inf(projectFile->getFilename());
QString filename = inf.fileName();
QString title = tr("Project file: %1").arg(filename);
setWindowTitle(title);
loadSettings();
mUI->premiumLicense->setVisible(premium);
// Checkboxes for the libraries..
const QString applicationFilePath = QCoreApplication::applicationFilePath();
const QString appPath = QFileInfo(applicationFilePath).canonicalPath();
const QString datadir = getDataDir();
QStringList searchPaths;
searchPaths << appPath << appPath + "/cfg" << inf.canonicalPath();
#ifdef FILESDIR
if (FILESDIR[0])
searchPaths << FILESDIR << FILESDIR "/cfg";
#endif
if (!datadir.isEmpty())
searchPaths << datadir << datadir + "/cfg";
QStringList libs;
// Search the std.cfg first since other libraries could depend on it
QString stdLibraryFilename;
for (const QString &sp : searchPaths) {
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.cfg"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
QString library = item.fileName();
if (library.compare("std.cfg", Qt::CaseInsensitive) != 0)
continue;
Library lib;
const QString fullfilename = sp + "/" + library;
const Library::Error err = lib.load(nullptr, fullfilename.toLatin1());
if (err.errorcode != Library::ErrorCode::OK)
continue;
// Working std.cfg found
stdLibraryFilename = fullfilename;
break;
}
if (!stdLibraryFilename.isEmpty())
break;
}
// Search other libraries
for (const QString &sp : searchPaths) {
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.cfg"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
QString library = item.fileName();
{
Library lib;
const QString fullfilename = sp + "/" + library;
Library::Error err = lib.load(nullptr, fullfilename.toLatin1());
if (err.errorcode != Library::ErrorCode::OK) {
// Some libraries depend on std.cfg so load it first and test again
lib.load(nullptr, stdLibraryFilename.toLatin1());
err = lib.load(nullptr, fullfilename.toLatin1());
}
if (err.errorcode != Library::ErrorCode::OK)
continue;
}
library.chop(4);
if (library.compare("std", Qt::CaseInsensitive) == 0)
continue;
if (libs.indexOf(library) == -1)
libs << library;
}
}
libs.sort();
mUI->mLibraries->clear();
for (const QString &lib : libs) {
auto* item = new QListWidgetItem(lib, mUI->mLibraries);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
item->setCheckState(Qt::Unchecked); // AND initialize check state
}
// Platforms..
Platforms platforms;
for (const Platform::Type builtinPlatform : builtinPlatforms)
mUI->mComboBoxPlatform->addItem(platforms.get(builtinPlatform).mTitle);
QStringList platformFiles;
for (QString sp : searchPaths) {
if (sp.endsWith("/cfg"))
sp = sp.mid(0,sp.length()-3) + "platforms";
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.xml"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
const QString platformFile = item.fileName();
Platform plat2;
if (!plat2.loadFromFile(applicationFilePath.toStdString().c_str(), platformFile.toStdString()))
continue;
if (platformFiles.indexOf(platformFile) == -1)
platformFiles << platformFile;
}
}
platformFiles.sort();
mUI->mComboBoxPlatform->addItems(platformFiles);
// integer. allow empty.
mUI->mEditCertIntPrecision->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*"),this));
mUI->mEditTags->setValidator(new QRegularExpressionValidator(QRegularExpression("[a-zA-Z0-9 ;]*"),this));
const QRegularExpression undefRegExp("\\s*([a-zA-Z_][a-zA-Z0-9_]*[; ]*)*");
mUI->mEditUndefines->setValidator(new QRegularExpressionValidator(undefRegExp, this));
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &ProjectFileDialog::ok);
connect(mUI->mBtnBrowseBuildDir, &QPushButton::clicked, this, &ProjectFileDialog::browseBuildDir);
connect(mUI->mBtnClearImportProject, &QPushButton::clicked, this, &ProjectFileDialog::clearImportProject);
connect(mUI->mBtnBrowseImportProject, &QPushButton::clicked, this, &ProjectFileDialog::browseImportProject);
connect(mUI->mBtnAddCheckPath, SIGNAL(clicked()), this, SLOT(addCheckPath()));
connect(mUI->mBtnEditCheckPath, &QPushButton::clicked, this, &ProjectFileDialog::editCheckPath);
connect(mUI->mBtnRemoveCheckPath, &QPushButton::clicked, this, &ProjectFileDialog::removeCheckPath);
connect(mUI->mBtnAddInclude, SIGNAL(clicked()), this, SLOT(addIncludeDir()));
connect(mUI->mBtnEditInclude, &QPushButton::clicked, this, &ProjectFileDialog::editIncludeDir);
connect(mUI->mBtnRemoveInclude, &QPushButton::clicked, this, &ProjectFileDialog::removeIncludeDir);
connect(mUI->mBtnAddIgnorePath, SIGNAL(clicked()), this, SLOT(addExcludePath()));
connect(mUI->mBtnAddIgnoreFile, SIGNAL(clicked()), this, SLOT(addExcludeFile()));
connect(mUI->mBtnEditIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::editExcludePath);
connect(mUI->mBtnRemoveIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::removeExcludePath);
connect(mUI->mBtnIncludeUp, &QPushButton::clicked, this, &ProjectFileDialog::moveIncludePathUp);
connect(mUI->mBtnIncludeDown, &QPushButton::clicked, this, &ProjectFileDialog::moveIncludePathDown);
connect(mUI->mBtnAddSuppression, &QPushButton::clicked, this, &ProjectFileDialog::addSuppression);
connect(mUI->mBtnRemoveSuppression, &QPushButton::clicked, this, &ProjectFileDialog::removeSuppression);
connect(mUI->mListSuppressions, &QListWidget::doubleClicked, this, &ProjectFileDialog::editSuppression);
connect(mUI->mBtnBrowseMisraFile, &QPushButton::clicked, this, &ProjectFileDialog::browseMisraFile);
connect(mUI->mChkAllVsConfigs, &QCheckBox::clicked, this, &ProjectFileDialog::checkAllVSConfigs);
connect(mUI->mBtnBrowseLicense, &QPushButton::clicked, this, &ProjectFileDialog::browseLicenseFile);
loadFromProjectFile(projectFile);
}
ProjectFileDialog::~ProjectFileDialog()
{
saveSettings();
delete mUI;
}
void ProjectFileDialog::loadSettings()
{
QSettings settings;
resize(settings.value(SETTINGS_PROJECT_DIALOG_WIDTH, 470).toInt(),
settings.value(SETTINGS_PROJECT_DIALOG_HEIGHT, 330).toInt());
}
void ProjectFileDialog::saveSettings() const
{
QSettings settings;
settings.setValue(SETTINGS_PROJECT_DIALOG_WIDTH, size().width());
settings.setValue(SETTINGS_PROJECT_DIALOG_HEIGHT, size().height());
}
static void updateAddonCheckBox(QCheckBox *cb, const ProjectFile *projectFile, const QString &dataDir, const QString &addon)
{
if (projectFile)
cb->setChecked(projectFile->getAddons().contains(addon));
if (ProjectFile::getAddonFilePath(dataDir, addon).isEmpty()) {
cb->setEnabled(false);
cb->setText(cb->text() + QObject::tr(" (Not found)"));
}
}
void ProjectFileDialog::checkAllVSConfigs()
{
if (mUI->mChkAllVsConfigs->isChecked()) {
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
item->setCheckState(Qt::Checked);
}
}
mUI->mListVsConfigs->setEnabled(!mUI->mChkAllVsConfigs->isChecked());
}
void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
{
setRootPath(projectFile->getRootPath());
setBuildDir(projectFile->getBuildDir());
setIncludepaths(projectFile->getIncludeDirs());
setDefines(projectFile->getDefines());
setUndefines(projectFile->getUndefines());
setCheckPaths(projectFile->getCheckPaths());
setImportProject(projectFile->getImportProject());
mUI->mChkAllVsConfigs->setChecked(projectFile->getAnalyzeAllVsConfigs());
setProjectConfigurations(getProjectConfigs(mUI->mEditImportProject->text()));
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
if (projectFile->getAnalyzeAllVsConfigs() || projectFile->getVsConfigurations().contains(item->text()))
item->setCheckState(Qt::Checked);
else
item->setCheckState(Qt::Unchecked);
}
if (projectFile->isCheckLevelExhaustive())
mUI->mCheckLevelExhaustive->setChecked(true);
else
mUI->mCheckLevelNormal->setChecked(true);
mUI->mCheckHeaders->setChecked(projectFile->getCheckHeaders());
mUI->mCheckUnusedTemplates->setChecked(projectFile->getCheckUnusedTemplates());
mUI->mInlineSuppressions->setChecked(projectFile->getInlineSuppression());
mUI->mMaxCtuDepth->setValue(projectFile->getMaxCtuDepth());
mUI->mMaxTemplateRecursion->setValue(projectFile->getMaxTemplateRecursion());
if (projectFile->clangParser)
mUI->mBtnClangParser->setChecked(true);
else
mUI->mBtnCppcheckParser->setChecked(true);
mUI->mBtnSafeClasses->setChecked(projectFile->safeChecks.classes);
setExcludedPaths(projectFile->getExcludedPaths());
setLibraries(projectFile->getLibraries());
const QString& platform = projectFile->getPlatform();
if (platform.endsWith(".xml")) {
int i;
for (i = numberOfBuiltinPlatforms; i < mUI->mComboBoxPlatform->count(); ++i) {
if (mUI->mComboBoxPlatform->itemText(i) == platform)
break;
}
if (i < mUI->mComboBoxPlatform->count())
mUI->mComboBoxPlatform->setCurrentIndex(i);
else {
mUI->mComboBoxPlatform->addItem(platform);
mUI->mComboBoxPlatform->setCurrentIndex(i);
}
} else {
int i;
for (i = 0; i < numberOfBuiltinPlatforms; ++i) {
const Platform::Type p = builtinPlatforms[i];
if (platform == Platform::toString(p))
break;
}
if (i < numberOfBuiltinPlatforms)
mUI->mComboBoxPlatform->setCurrentIndex(i);
else
mUI->mComboBoxPlatform->setCurrentIndex(-1);
}
mUI->mComboBoxPlatform->setCurrentText(projectFile->getPlatform());
setSuppressions(projectFile->getSuppressions());
// TODO
// Human knowledge..
/*
mUI->mListUnknownFunctionReturn->clear();
mUI->mListUnknownFunctionReturn->addItem("rand()");
for (int row = 0; row < mUI->mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI->mListUnknownFunctionReturn->item(row);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
const bool unknownValues = projectFile->getCheckUnknownFunctionReturn().contains(item->text());
item->setCheckState(unknownValues ? Qt::Checked : Qt::Unchecked); // AND initialize check state
}
mUI->mCheckSafeClasses->setChecked(projectFile->getSafeChecks().classes);
mUI->mCheckSafeExternalFunctions->setChecked(projectFile->getSafeChecks().externalFunctions);
mUI->mCheckSafeInternalFunctions->setChecked(projectFile->getSafeChecks().internalFunctions);
mUI->mCheckSafeExternalVariables->setChecked(projectFile->getSafeChecks().externalVariables);
*/
// Addons..
QSettings settings;
const QString dataDir = getDataDir();
updateAddonCheckBox(mUI->mAddonThreadSafety, projectFile, dataDir, "threadsafety");
updateAddonCheckBox(mUI->mAddonY2038, projectFile, dataDir, "y2038");
// Misra checkbox..
mUI->mMisraC->setText(mPremium ? "Misra C" : "Misra C 2012");
updateAddonCheckBox(mUI->mMisraC, projectFile, dataDir, ADDON_MISRA);
mUI->mMisraVersion->setEnabled(mUI->mMisraC->isChecked());
connect(mUI->mMisraC, &QCheckBox::toggled, mUI->mMisraVersion, &QComboBox::setEnabled);
const QString &misraFile = settings.value(SETTINGS_MISRA_FILE, QString()).toString();
mUI->mEditMisraFile->setText(misraFile);
mUI->mMisraVersion->setVisible(mPremium);
mUI->mMisraVersion->setCurrentIndex(projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_C_2023));
if (mPremium) {
mUI->mLabelMisraFile->setVisible(false);
mUI->mEditMisraFile->setVisible(false);
mUI->mBtnBrowseMisraFile->setVisible(false);
} else if (!mUI->mMisraC->isEnabled()) {
mUI->mEditMisraFile->setEnabled(false);
mUI->mBtnBrowseMisraFile->setEnabled(false);
}
mUI->mMisraCpp->setEnabled(mPremium);
mUI->mMisraCppVersion->setVisible(mPremium);
if (projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_CPP_2008)) {
mUI->mMisraCpp->setChecked(true);
mUI->mMisraCppVersion->setCurrentIndex(0);
}
else if (projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_CPP_2023)) {
mUI->mMisraCpp->setChecked(true);
mUI->mMisraCppVersion->setCurrentIndex(1);
} else {
mUI->mMisraCpp->setChecked(false);
mUI->mMisraCppVersion->setCurrentIndex(1);
}
mUI->mMisraCppVersion->setEnabled(mUI->mMisraCpp->isChecked());
connect(mUI->mMisraCpp, &QCheckBox::toggled, mUI->mMisraCppVersion, &QComboBox::setEnabled);
mUI->mCertC2016->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_CERT_C));
mUI->mCertCpp2016->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_CERT_CPP));
mUI->mAutosar->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_AUTOSAR));
if (projectFile->getCertIntPrecision() <= 0)
mUI->mEditCertIntPrecision->setText(QString());
else
mUI->mEditCertIntPrecision->setText(QString::number(projectFile->getCertIntPrecision()));
mUI->mCertC2016->setEnabled(mPremium);
mUI->mCertCpp2016->setEnabled(mPremium);
mUI->mAutosar->setEnabled(mPremium);
mUI->mLabelCertIntPrecision->setVisible(mPremium);
mUI->mEditCertIntPrecision->setVisible(mPremium);
mUI->mBughunting->setChecked(mPremium && projectFile->getBughunting());
mUI->mBughunting->setEnabled(mPremium);
mUI->mToolClangAnalyzer->setChecked(projectFile->getClangAnalyzer());
mUI->mToolClangTidy->setChecked(projectFile->getClangTidy());
if (CheckThread::clangTidyCmd().isEmpty()) {
mUI->mToolClangTidy->setText(tr("Clang-tidy (not found)"));
mUI->mToolClangTidy->setEnabled(false);
}
mUI->mEditTags->setText(projectFile->getTags().join(';'));
mUI->mEditLicenseFile->setText(projectFile->getLicenseFile());
updatePathsAndDefines();
}
void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
{
projectFile->setRootPath(getRootPath());
projectFile->setBuildDir(getBuildDir());
projectFile->setImportProject(getImportProject());
projectFile->setAnalyzeAllVsConfigs(mUI->mChkAllVsConfigs->isChecked());
projectFile->setVSConfigurations(getProjectConfigurations());
projectFile->setCheckHeaders(mUI->mCheckHeaders->isChecked());
projectFile->setCheckUnusedTemplates(mUI->mCheckUnusedTemplates->isChecked());
projectFile->setInlineSuppression(mUI->mInlineSuppressions->isChecked());
projectFile->setMaxCtuDepth(mUI->mMaxCtuDepth->value());
projectFile->setMaxTemplateRecursion(mUI->mMaxTemplateRecursion->value());
projectFile->setIncludes(getIncludePaths());
projectFile->setDefines(getDefines());
projectFile->setUndefines(getUndefines());
projectFile->setCheckPaths(getCheckPaths());
projectFile->setExcludedPaths(getExcludedPaths());
projectFile->setLibraries(getLibraries());
projectFile->setCheckLevel(mUI->mCheckLevelExhaustive->isChecked() ? ProjectFile::CheckLevel::exhaustive : ProjectFile::CheckLevel::normal);
projectFile->clangParser = mUI->mBtnClangParser->isChecked();
projectFile->safeChecks.classes = mUI->mBtnSafeClasses->isChecked();
if (mUI->mComboBoxPlatform->currentText().endsWith(".xml"))
projectFile->setPlatform(mUI->mComboBoxPlatform->currentText());
else {
const int i = mUI->mComboBoxPlatform->currentIndex();
if (i>=0 && i < numberOfBuiltinPlatforms)
projectFile->setPlatform(Platform::toString(builtinPlatforms[i]));
else
projectFile->setPlatform(QString());
}
projectFile->setSuppressions(getSuppressions());
// Human knowledge
/*
QStringList unknownReturnValues;
for (int row = 0; row < mUI->mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI->mListUnknownFunctionReturn->item(row);
if (item->checkState() == Qt::Checked)
unknownReturnValues << item->text();
}
projectFile->setCheckUnknownFunctionReturn(unknownReturnValues);
ProjectFile::SafeChecks safeChecks;
safeChecks.classes = mUI->mCheckSafeClasses->isChecked();
safeChecks.externalFunctions = mUI->mCheckSafeExternalFunctions->isChecked();
safeChecks.internalFunctions = mUI->mCheckSafeInternalFunctions->isChecked();
safeChecks.externalVariables = mUI->mCheckSafeExternalVariables->isChecked();
projectFile->setSafeChecks(safeChecks);
*/
// Addons
QStringList addons;
if (mUI->mAddonThreadSafety->isChecked())
addons << "threadsafety";
if (mUI->mAddonY2038->isChecked())
addons << "y2038";
if (mUI->mMisraC->isChecked())
addons << ADDON_MISRA;
projectFile->setAddons(addons);
QStringList codingStandards;
if (mUI->mCertC2016->isChecked())
codingStandards << CODING_STANDARD_CERT_C;
if (mUI->mCertCpp2016->isChecked())
codingStandards << CODING_STANDARD_CERT_CPP;
if (mPremium && mUI->mMisraVersion->currentIndex() == 1)
codingStandards << CODING_STANDARD_MISRA_C_2023;
if (mUI->mMisraCpp->isChecked() && mUI->mMisraCppVersion->currentIndex() == 0)
codingStandards << CODING_STANDARD_MISRA_CPP_2008;
if (mUI->mMisraCpp->isChecked() && mUI->mMisraCppVersion->currentIndex() == 1)
codingStandards << CODING_STANDARD_MISRA_CPP_2023;
if (mUI->mAutosar->isChecked())
codingStandards << CODING_STANDARD_AUTOSAR;
projectFile->setCodingStandards(std::move(codingStandards));
projectFile->setCertIntPrecision(mUI->mEditCertIntPrecision->text().toInt());
projectFile->setBughunting(mUI->mBughunting->isChecked());
projectFile->setClangAnalyzer(mUI->mToolClangAnalyzer->isChecked());
projectFile->setClangTidy(mUI->mToolClangTidy->isChecked());
if (mPremium)
projectFile->setLicenseFile(mUI->mEditLicenseFile->text());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
projectFile->setTags(mUI->mEditTags->text().split(";", Qt::SkipEmptyParts));
#else
projectFile->setTags(mUI->mEditTags->text().split(";", QString::SkipEmptyParts));
#endif
}
void ProjectFileDialog::ok()
{
saveToProjectFile(mProjectFile);
mProjectFile->write();
accept();
}
QString ProjectFileDialog::getExistingDirectory(const QString &caption, bool trailingSlash)
{
const QFileInfo inf(mProjectFile->getFilename());
const QString projectPath = inf.absolutePath();
QString selectedDir = QFileDialog::getExistingDirectory(this,
caption,
projectPath);
if (selectedDir.isEmpty())
return QString();
// Check if the path is relative to project file's path and if so
// make it a relative path instead of absolute path.
const QDir dir(projectPath);
const QString relpath(dir.relativeFilePath(selectedDir));
if (!relpath.startsWith("../.."))
selectedDir = relpath;
// Trailing slash..
if (trailingSlash && !selectedDir.endsWith('/'))
selectedDir += '/';
return selectedDir;
}
void ProjectFileDialog::browseBuildDir()
{
const QString dir(getExistingDirectory(tr("Select Cppcheck build dir"), false));
if (!dir.isEmpty())
mUI->mEditBuildDir->setText(dir);
}
void ProjectFileDialog::updatePathsAndDefines()
{
const QString &fileName = mUI->mEditImportProject->text();
const bool importProject = !fileName.isEmpty();
const bool hasConfigs = fileName.endsWith(".sln") || fileName.endsWith(".vcxproj");
mUI->mBtnClearImportProject->setEnabled(importProject);
mUI->mListCheckPaths->setEnabled(!importProject);
mUI->mListIncludeDirs->setEnabled(!importProject);
mUI->mBtnAddCheckPath->setEnabled(!importProject);
mUI->mBtnEditCheckPath->setEnabled(!importProject);
mUI->mBtnRemoveCheckPath->setEnabled(!importProject);
mUI->mEditUndefines->setEnabled(!importProject);
mUI->mBtnAddInclude->setEnabled(!importProject);
mUI->mBtnEditInclude->setEnabled(!importProject);
mUI->mBtnRemoveInclude->setEnabled(!importProject);
mUI->mBtnIncludeUp->setEnabled(!importProject);
mUI->mBtnIncludeDown->setEnabled(!importProject);
mUI->mChkAllVsConfigs->setEnabled(hasConfigs);
mUI->mListVsConfigs->setEnabled(hasConfigs && !mUI->mChkAllVsConfigs->isChecked());
if (!hasConfigs)
mUI->mListVsConfigs->clear();
}
void ProjectFileDialog::clearImportProject()
{
mUI->mEditImportProject->clear();
updatePathsAndDefines();
}
void ProjectFileDialog::browseImportProject()
{
const QFileInfo inf(mProjectFile->getFilename());
const QDir &dir = inf.absoluteDir();
QMap<QString,QString> filters;
filters[tr("Visual Studio")] = "*.sln *.vcxproj";
filters[tr("Compile database")] = "compile_commands.json";
filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString fileName = QFileDialog::getOpenFileName(this, tr("Import Project"),
dir.canonicalPath(),
toFilterString(filters));
if (!fileName.isEmpty()) {
mUI->mEditImportProject->setText(dir.relativeFilePath(fileName));
updatePathsAndDefines();
setProjectConfigurations(getProjectConfigs(fileName));
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
item->setCheckState(Qt::Checked);
}
}
}
QStringList ProjectFileDialog::getProjectConfigurations() const
{
QStringList configs;
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
if (item->checkState() == Qt::Checked)
configs << item->text();
}
return configs;
}
void ProjectFileDialog::setProjectConfigurations(const QStringList &configs)
{
mUI->mListVsConfigs->clear();
mUI->mListVsConfigs->setEnabled(!configs.isEmpty() && !mUI->mChkAllVsConfigs->isChecked());
for (const QString &cfg : configs) {
auto* item = new QListWidgetItem(cfg, mUI->mListVsConfigs);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
item->setCheckState(Qt::Unchecked);
}
}
QString ProjectFileDialog::getImportProject() const
{
return mUI->mEditImportProject->text();
}
void ProjectFileDialog::addIncludeDir(const QString &dir)
{
if (dir.isEmpty())
return;
const QString newdir = QDir::toNativeSeparators(dir);
auto *item = new QListWidgetItem(newdir);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListIncludeDirs->addItem(item);
}
void ProjectFileDialog::addCheckPath(const QString &path)
{
if (path.isEmpty())
return;
const QString newpath = QDir::toNativeSeparators(path);
auto *item = new QListWidgetItem(newpath);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListCheckPaths->addItem(item);
}
void ProjectFileDialog::addExcludePath(const QString &path)
{
if (path.isEmpty())
return;
const QString newpath = QDir::toNativeSeparators(path);
auto *item = new QListWidgetItem(newpath);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListExcludedPaths->addItem(item);
}
QString ProjectFileDialog::getRootPath() const
{
QString root = mUI->mEditProjectRoot->text();
root = root.trimmed();
root = QDir::fromNativeSeparators(root);
return root;
}
QString ProjectFileDialog::getBuildDir() const
{
return mUI->mEditBuildDir->text();
}
QStringList ProjectFileDialog::getIncludePaths() const
{
return getPaths(mUI->mListIncludeDirs);
}
QStringList ProjectFileDialog::getDefines() const
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
return mUI->mEditDefines->text().trimmed().split(QRegularExpression("\\s*;\\s*"), Qt::SkipEmptyParts);
#else
return mUI->mEditDefines->text().trimmed().split(QRegularExpression("\\s*;\\s*"), QString::SkipEmptyParts);
#endif
}
QStringList ProjectFileDialog::getUndefines() const
{
const QString undefine = mUI->mEditUndefines->text().trimmed();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
QStringList undefines = undefine.split(QRegularExpression("\\s*;\\s*"), Qt::SkipEmptyParts);
#else
QStringList undefines = undefine.split(QRegularExpression("\\s*;\\s*"), QString::SkipEmptyParts);
#endif
undefines.removeDuplicates();
return undefines;
}
QStringList ProjectFileDialog::getCheckPaths() const
{
return getPaths(mUI->mListCheckPaths);
}
QStringList ProjectFileDialog::getExcludedPaths() const
{
return getPaths(mUI->mListExcludedPaths);
}
QStringList ProjectFileDialog::getLibraries() const
{
QStringList libraries;
for (int row = 0; row < mUI->mLibraries->count(); ++row) {
QListWidgetItem *item = mUI->mLibraries->item(row);
if (item->checkState() == Qt::Checked)
libraries << item->text();
}
return libraries;
}
void ProjectFileDialog::setRootPath(const QString &root)
{
mUI->mEditProjectRoot->setText(QDir::toNativeSeparators(root));
}
void ProjectFileDialog::setBuildDir(const QString &buildDir)
{
mUI->mEditBuildDir->setText(buildDir);
}
void ProjectFileDialog::setImportProject(const QString &importProject)
{
mUI->mEditImportProject->setText(importProject);
}
void ProjectFileDialog::setIncludepaths(const QStringList &includes)
{
for (const QString& dir : includes) {
addIncludeDir(dir);
}
}
void ProjectFileDialog::setDefines(const QStringList &defines)
{
mUI->mEditDefines->setText(defines.join(";"));
}
void ProjectFileDialog::setUndefines(const QStringList &undefines)
{
mUI->mEditUndefines->setText(undefines.join(";"));
}
void ProjectFileDialog::setCheckPaths(const QStringList &paths)
{
for (const QString& path : paths) {
addCheckPath(path);
}
}
void ProjectFileDialog::setExcludedPaths(const QStringList &paths)
{
for (const QString& path : paths) {
addExcludePath(path);
}
}
void ProjectFileDialog::setLibraries(const QStringList &libraries)
{
for (int row = 0; row < mUI->mLibraries->count(); ++row) {
QListWidgetItem *item = mUI->mLibraries->item(row);
item->setCheckState(libraries.contains(item->text()) ? Qt::Checked : Qt::Unchecked);
}
}
void ProjectFileDialog::addSingleSuppression(const SuppressionList::Suppression &suppression)
{
mSuppressions += suppression;
mUI->mListSuppressions->addItem(QString::fromStdString(suppression.getText()));
}
void ProjectFileDialog::setSuppressions(const QList<SuppressionList::Suppression> &suppressions)
{
mUI->mListSuppressions->clear();
QList<SuppressionList::Suppression> new_suppressions = suppressions;
mSuppressions.clear();
for (const SuppressionList::Suppression &suppression : new_suppressions) {
addSingleSuppression(suppression);
}
mUI->mListSuppressions->sortItems();
}
void ProjectFileDialog::addCheckPath()
{
QString dir = getExistingDirectory(tr("Select a directory to check"), false);
if (!dir.isEmpty())
addCheckPath(dir);
}
void ProjectFileDialog::editCheckPath()
{
QListWidgetItem *item = mUI->mListCheckPaths->currentItem();
mUI->mListCheckPaths->editItem(item);
}
void ProjectFileDialog::removeCheckPath()
{
const int row = mUI->mListCheckPaths->currentRow();
QListWidgetItem *item = mUI->mListCheckPaths->takeItem(row);
delete item;
}
void ProjectFileDialog::addIncludeDir()
{
const QString dir = getExistingDirectory(tr("Select include directory"), true);
if (!dir.isEmpty())
addIncludeDir(dir);
}
void ProjectFileDialog::removeIncludeDir()
{
const int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
delete item;
}
void ProjectFileDialog::editIncludeDir()
{
QListWidgetItem *item = mUI->mListIncludeDirs->currentItem();
mUI->mListIncludeDirs->editItem(item);
}
void ProjectFileDialog::addExcludePath()
{
addExcludePath(getExistingDirectory(tr("Select directory to ignore"), true));
}
void ProjectFileDialog::addExcludeFile()
{
const QFileInfo inf(mProjectFile->getFilename());
const QDir &dir = inf.absoluteDir();
QMap<QString,QString> filters;
filters[tr("Source files")] = "*.c *.cpp";
filters[tr("All files")] = "*.*";
addExcludePath(QFileDialog::getOpenFileName(this, tr("Exclude file"), dir.canonicalPath(), toFilterString(filters)));
}
void ProjectFileDialog::editExcludePath()
{
QListWidgetItem *item = mUI->mListExcludedPaths->currentItem();
mUI->mListExcludedPaths->editItem(item);
}
void ProjectFileDialog::removeExcludePath()
{
const int row = mUI->mListExcludedPaths->currentRow();
QListWidgetItem *item = mUI->mListExcludedPaths->takeItem(row);
delete item;
}
void ProjectFileDialog::moveIncludePathUp()
{
int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
row = row > 0 ? row - 1 : 0;
mUI->mListIncludeDirs->insertItem(row, item);
mUI->mListIncludeDirs->setCurrentItem(item);
}
void ProjectFileDialog::moveIncludePathDown()
{
int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
const int count = mUI->mListIncludeDirs->count();
row = row < count ? row + 1 : count;
mUI->mListIncludeDirs->insertItem(row, item);
mUI->mListIncludeDirs->setCurrentItem(item);
}
void ProjectFileDialog::addSuppression()
{
NewSuppressionDialog dlg;
if (dlg.exec() == QDialog::Accepted) {
addSingleSuppression(dlg.getSuppression());
}
}
void ProjectFileDialog::removeSuppression()
{
const int row = mUI->mListSuppressions->currentRow();
QListWidgetItem *item = mUI->mListSuppressions->takeItem(row);
if (!item)
return;
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0)
mSuppressions.removeAt(suppressionIndex);
delete item;
}
void ProjectFileDialog::editSuppression(const QModelIndex & /*index*/)
{
const int row = mUI->mListSuppressions->currentRow();
QListWidgetItem *item = mUI->mListSuppressions->item(row);
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0) { // TODO what if suppression is not found?
NewSuppressionDialog dlg;
dlg.setSuppression(mSuppressions[suppressionIndex]);
if (dlg.exec() == QDialog::Accepted) {
mSuppressions[suppressionIndex] = dlg.getSuppression();
setSuppressions(mSuppressions);
}
}
}
int ProjectFileDialog::getSuppressionIndex(const QString &shortText) const
{
const std::string s = shortText.toStdString();
for (int i = 0; i < mSuppressions.size(); ++i) {
if (mSuppressions[i].getText() == s)
return i;
}
return -1;
}
void ProjectFileDialog::browseMisraFile()
{
const QString fileName = QFileDialog::getOpenFileName(this,
tr("Select MISRA rule texts file"),
QDir::homePath(),
tr("MISRA rule texts file (%1)").arg("*.txt"));
if (!fileName.isEmpty()) {
QSettings settings;
mUI->mEditMisraFile->setText(fileName);
settings.setValue(SETTINGS_MISRA_FILE, fileName);
mUI->mMisraC->setText("MISRA C 2012");
mUI->mMisraC->setEnabled(true);
updateAddonCheckBox(mUI->mMisraC, nullptr, getDataDir(), ADDON_MISRA);
}
}
void ProjectFileDialog::browseLicenseFile()
{
const QFileInfo inf(mProjectFile->getFilename());
const QString projectPath = inf.absolutePath();
const QString fileName = QFileDialog::getOpenFileName(this, tr("Select license file"), projectPath, tr("License file (%1)").arg("*.lic"));
if (fileName.isEmpty())
return;
const QDir dir(projectPath);
mUI->mEditLicenseFile->setText(dir.relativeFilePath(fileName));
}
| 37,096
|
C++
|
.cpp
| 870
| 36.911494
| 144
| 0.704036
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,341
|
mainwindow.cpp
|
danmar_cppcheck/gui/mainwindow.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "addoninfo.h"
#include "applicationlist.h"
#include "aboutdialog.h"
#include "analyzerinfo.h"
#include "checkstatistics.h"
#include "checkthread.h"
#include "common.h"
#include "cppcheck.h"
#include "errortypes.h"
#include "filelist.h"
#include "filesettings.h"
#include "compliancereportdialog.h"
#include "fileviewdialog.h"
#include "helpdialog.h"
#include "importproject.h"
#include "librarydialog.h"
#include "platform.h"
#include "projectfile.h"
#include "projectfiledialog.h"
#include "report.h"
#include "resultsview.h"
#include "scratchpad.h"
#include "settings.h"
#include "showtypes.h"
#include "statsdialog.h"
#include "settingsdialog.h"
#include "standards.h"
#include "suppressions.h"
#include "threadhandler.h"
#include "threadresult.h"
#include "translationhandler.h"
#include "ui_mainwindow.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include <QApplication>
#include <QAction>
#include <QActionGroup>
#include <QByteArray>
#include <QChar>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QKeySequence>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QMap>
#include <QMenu>
#include <QMessageBox>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QPushButton>
#include <QRegularExpression>
#include <QSettings>
#include <QSize>
#include <QTimer>
#include <QTemporaryFile>
#include <QToolBar>
#include <QUrl>
#include <QVariant>
#include <Qt>
#include "json.h"
static const QString compile_commands_json("compile_commands.json");
static QString fromNativePath(const QString& p) {
#ifdef Q_OS_WIN
QString ret(p);
ret.replace('\\', '/');
return ret;
#else
return p;
#endif
}
MainWindow::MainWindow(TranslationHandler* th, QSettings* settings) :
mSettings(settings),
mApplications(new ApplicationList(this)),
mTranslation(th),
mUI(new Ui::MainWindow),
mPlatformActions(new QActionGroup(this)),
mCStandardActions(new QActionGroup(this)),
mCppStandardActions(new QActionGroup(this)),
mSelectLanguageActions(new QActionGroup(this)),
mSelectReportActions(new QActionGroup(this))
{
{
Settings tempSettings;
tempSettings.exename = QCoreApplication::applicationFilePath().toStdString();
Settings::loadCppcheckCfg(tempSettings, tempSettings.supprs); // TODO: how to handle error?
mCppcheckCfgProductName = QString::fromStdString(tempSettings.cppcheckCfgProductName);
mCppcheckCfgAbout = QString::fromStdString(tempSettings.cppcheckCfgAbout);
}
mUI->setupUi(this);
mThread = new ThreadHandler(this);
mUI->mResults->initialize(mSettings, mApplications, mThread);
// Filter timer to delay filtering results slightly while typing
mFilterTimer = new QTimer(this);
mFilterTimer->setInterval(500);
mFilterTimer->setSingleShot(true);
connect(mFilterTimer, &QTimer::timeout, this, &MainWindow::filterResults);
// "Filter" toolbar
mLineEditFilter = new QLineEdit(mUI->mToolBarFilter);
mLineEditFilter->setPlaceholderText(tr("Quick Filter:"));
mLineEditFilter->setClearButtonEnabled(true);
mUI->mToolBarFilter->addWidget(mLineEditFilter);
connect(mLineEditFilter, SIGNAL(textChanged(QString)), mFilterTimer, SLOT(start()));
connect(mLineEditFilter, &QLineEdit::returnPressed, this, &MainWindow::filterResults);
connect(mUI->mActionPrint, SIGNAL(triggered()), mUI->mResults, SLOT(print()));
connect(mUI->mActionPrintPreview, SIGNAL(triggered()), mUI->mResults, SLOT(printPreview()));
connect(mUI->mActionQuit, &QAction::triggered, this, &MainWindow::close);
connect(mUI->mActionAnalyzeFiles, &QAction::triggered, this, &MainWindow::analyzeFiles);
connect(mUI->mActionAnalyzeDirectory, &QAction::triggered, this, &MainWindow::analyzeDirectory);
connect(mUI->mActionSettings, &QAction::triggered, this, &MainWindow::programSettings);
connect(mUI->mActionClearResults, &QAction::triggered, this, &MainWindow::clearResults);
connect(mUI->mActionOpenXML, &QAction::triggered, this, &MainWindow::openResults);
connect(mUI->mActionShowStyle, &QAction::toggled, this, &MainWindow::showStyle);
connect(mUI->mActionShowErrors, &QAction::toggled, this, &MainWindow::showErrors);
connect(mUI->mActionShowWarnings, &QAction::toggled, this, &MainWindow::showWarnings);
connect(mUI->mActionShowPortability, &QAction::toggled, this, &MainWindow::showPortability);
connect(mUI->mActionShowPerformance, &QAction::toggled, this, &MainWindow::showPerformance);
connect(mUI->mActionShowInformation, &QAction::toggled, this, &MainWindow::showInformation);
connect(mUI->mActionShowCppcheck, &QAction::toggled, mUI->mResults, &ResultsView::showCppcheckResults);
connect(mUI->mActionShowClang, &QAction::toggled, mUI->mResults, &ResultsView::showClangResults);
connect(mUI->mActionCheckAll, &QAction::triggered, this, &MainWindow::checkAll);
connect(mUI->mActionUncheckAll, &QAction::triggered, this, &MainWindow::uncheckAll);
connect(mUI->mActionCollapseAll, &QAction::triggered, mUI->mResults, &ResultsView::collapseAllResults);
connect(mUI->mActionExpandAll, &QAction::triggered, mUI->mResults, &ResultsView::expandAllResults);
connect(mUI->mActionShowHidden, &QAction::triggered, mUI->mResults, &ResultsView::showHiddenResults);
connect(mUI->mActionViewStats, &QAction::triggered, this, &MainWindow::showStatistics);
connect(mUI->mActionLibraryEditor, &QAction::triggered, this, &MainWindow::showLibraryEditor);
connect(mUI->mActionReanalyzeModified, &QAction::triggered, this, &MainWindow::reAnalyzeModified);
connect(mUI->mActionReanalyzeAll, &QAction::triggered, this, &MainWindow::reAnalyzeAll);
connect(mUI->mActionCheckLibrary, &QAction::triggered, this, &MainWindow::checkLibrary);
connect(mUI->mActionCheckConfiguration, &QAction::triggered, this, &MainWindow::checkConfiguration);
connect(mUI->mActionStop, &QAction::triggered, this, &MainWindow::stopAnalysis);
connect(mUI->mActionSave, &QAction::triggered, this, &MainWindow::save);
connect(mUI->mActionComplianceReport, &QAction::triggered, this, &MainWindow::complianceReport);
// About menu
connect(mUI->mActionAbout, &QAction::triggered, this, &MainWindow::about);
connect(mUI->mActionLicense, &QAction::triggered, this, &MainWindow::showLicense);
// View > Toolbar menu
connect(mUI->mActionToolBarMain, SIGNAL(toggled(bool)), this, SLOT(toggleMainToolBar()));
connect(mUI->mActionToolBarView, SIGNAL(toggled(bool)), this, SLOT(toggleViewToolBar()));
connect(mUI->mActionToolBarFilter, SIGNAL(toggled(bool)), this, SLOT(toggleFilterToolBar()));
connect(mUI->mActionAuthors, &QAction::triggered, this, &MainWindow::showAuthors);
connect(mThread, &ThreadHandler::done, this, &MainWindow::analysisDone);
connect(mThread, &ThreadHandler::log, mUI->mResults, &ResultsView::log);
connect(mThread, &ThreadHandler::debugError, mUI->mResults, &ResultsView::debugError);
connect(mUI->mResults, &ResultsView::gotResults, this, &MainWindow::resultsAdded);
connect(mUI->mResults, &ResultsView::resultsHidden, mUI->mActionShowHidden, &QAction::setEnabled);
connect(mUI->mResults, &ResultsView::checkSelected, this, &MainWindow::performSelectedFilesCheck);
connect(mUI->mResults, &ResultsView::suppressIds, this, &MainWindow::suppressIds);
connect(mUI->mMenuView, &QMenu::aboutToShow, this, &MainWindow::aboutToShowViewMenu);
// Change report type
connect(mUI->mActionReportNormal, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportAutosar, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportCertC, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportCertCpp, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraC, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraCpp2008, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraCpp2023, &QAction::triggered, this, &MainWindow::changeReportType);
// File menu
connect(mUI->mActionNewProjectFile, &QAction::triggered, this, &MainWindow::newProjectFile);
connect(mUI->mActionOpenProjectFile, &QAction::triggered, this, &MainWindow::openProjectFile);
connect(mUI->mActionShowScratchpad, &QAction::triggered, this, &MainWindow::showScratchpad);
connect(mUI->mActionCloseProjectFile, &QAction::triggered, this, &MainWindow::closeProjectFile);
connect(mUI->mActionEditProjectFile, &QAction::triggered, this, &MainWindow::editProjectFile);
connect(mUI->mActionHelpContents, &QAction::triggered, this, &MainWindow::openHelpContents);
loadSettings();
mThread->initialize(mUI->mResults);
if (mProjectFile)
formatAndSetTitle(tr("Project:") + ' ' + mProjectFile->getFilename());
else
formatAndSetTitle();
mUI->mActionComplianceReport->setVisible(isCppcheckPremium());
enableCheckButtons(true);
mUI->mActionPrint->setShortcut(QKeySequence::Print);
enableResultsButtons();
enableProjectOpenActions(true);
enableProjectActions(false);
// Must setup MRU menu before CLI param handling as it can load a
// project file and update MRU menu.
for (int i = 0; i < MaxRecentProjects; ++i) {
mRecentProjectActs[i] = new QAction(this);
mRecentProjectActs[i]->setVisible(false);
connect(mRecentProjectActs[i], SIGNAL(triggered()),
this, SLOT(openRecentProject()));
}
mRecentProjectActs[MaxRecentProjects] = nullptr; // The separator
mUI->mActionProjectMRU->setVisible(false);
updateMRUMenuItems();
QStringList args = QCoreApplication::arguments();
//Remove the application itself
args.removeFirst();
if (!args.isEmpty()) {
handleCLIParams(args);
}
mUI->mActionCloseProjectFile->setEnabled(mProjectFile != nullptr);
mUI->mActionEditProjectFile->setEnabled(mProjectFile != nullptr);
for (int i = 0; i < mPlatforms.getCount(); i++) {
PlatformData platform = mPlatforms.mPlatforms[i];
auto *action = new QAction(this);
platform.mActMainWindow = action;
mPlatforms.mPlatforms[i] = platform;
action->setText(platform.mTitle);
action->setData(platform.mType);
action->setCheckable(true);
action->setActionGroup(mPlatformActions);
mUI->mMenuAnalyze->insertAction(mUI->mActionPlatforms, action);
connect(action, SIGNAL(triggered()), this, SLOT(selectPlatform()));
}
mUI->mActionReportNormal->setActionGroup(mSelectReportActions);
mUI->mActionReportAutosar->setActionGroup(mSelectReportActions);
mUI->mActionReportCertC->setActionGroup(mSelectReportActions);
mUI->mActionReportCertCpp->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraC->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraCpp2008->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraCpp2023->setActionGroup(mSelectReportActions);
mUI->mActionC89->setActionGroup(mCStandardActions);
mUI->mActionC99->setActionGroup(mCStandardActions);
mUI->mActionC11->setActionGroup(mCStandardActions);
//mUI->mActionC17->setActionGroup(mCStandardActions);
//mUI->mActionC23->setActionGroup(mCStandardActions);
mUI->mActionCpp03->setActionGroup(mCppStandardActions);
mUI->mActionCpp11->setActionGroup(mCppStandardActions);
mUI->mActionCpp14->setActionGroup(mCppStandardActions);
mUI->mActionCpp17->setActionGroup(mCppStandardActions);
mUI->mActionCpp20->setActionGroup(mCppStandardActions);
//mUI->mActionCpp23->setActionGroup(mCppStandardActions);
//mUI->mActionCpp26->setActionGroup(mCppStandardActions);
mUI->mActionEnforceC->setActionGroup(mSelectLanguageActions);
mUI->mActionEnforceCpp->setActionGroup(mSelectLanguageActions);
mUI->mActionAutoDetectLanguage->setActionGroup(mSelectLanguageActions);
// TODO: we no longer default to a Windows platform in CLI - so we should probably also get rid of this in the GUI
// For Windows platforms default to Win32 checked platform.
// For other platforms default to unspecified/default which means the
// platform Cppcheck GUI was compiled on.
#if defined(_WIN32)
constexpr Platform::Type defaultPlatform = Platform::Type::Win32W;
#else
constexpr Platform::Type defaultPlatform = Platform::Type::Unspecified;
#endif
PlatformData &platform = mPlatforms.get((Platform::Type)mSettings->value(SETTINGS_CHECKED_PLATFORM, defaultPlatform).toInt());
platform.mActMainWindow->setChecked(true);
mNetworkAccessManager = new QNetworkAccessManager(this);
connect(mNetworkAccessManager, &QNetworkAccessManager::finished,
this, &MainWindow::replyFinished);
mUI->mLabelInformation->setVisible(false);
mUI->mButtonHideInformation->setVisible(false);
connect(mUI->mButtonHideInformation, &QPushButton::clicked,
this, &MainWindow::hideInformation);
if (mSettings->value(SETTINGS_CHECK_FOR_UPDATES, false).toBool()) {
// Is there a new version?
if (isCppcheckPremium()) {
const QUrl url("https://files.cppchecksolutions.com/version.txt");
mNetworkAccessManager->get(QNetworkRequest(url));
} else {
const QUrl url("https://cppcheck.sourceforge.io/version.txt");
mNetworkAccessManager->get(QNetworkRequest(url));
}
} else {
delete mUI->mLayoutInformation;
}
changeReportType();
}
MainWindow::~MainWindow()
{
delete mProjectFile;
delete mScratchPad;
delete mUI;
}
void MainWindow::handleCLIParams(const QStringList ¶ms)
{
int index;
if (params.contains("-p")) {
index = params.indexOf("-p");
if ((index + 1) < params.length())
loadProjectFile(params[index + 1]);
} else if (params.contains("-l")) {
QString logFile;
index = params.indexOf("-l");
if ((index + 1) < params.length())
logFile = params[index + 1];
if (params.contains("-d")) {
QString checkedDir;
index = params.indexOf("-d");
if ((index + 1) < params.length())
checkedDir = params[index + 1];
loadResults(logFile, checkedDir);
} else {
loadResults(logFile);
}
} else if ((index = params.indexOf(QRegularExpression(".*\\.cppcheck$", QRegularExpression::CaseInsensitiveOption))) >= 0 && index < params.length() && QFile(params[index]).exists()) {
loadProjectFile(params[index]);
} else if ((index = params.indexOf(QRegularExpression(".*\\.xml$", QRegularExpression::CaseInsensitiveOption))) >= 0 && index < params.length() && QFile(params[index]).exists()) {
loadResults(params[index],QDir::currentPath());
} else
doAnalyzeFiles(params);
}
void MainWindow::loadSettings()
{
// Window/dialog sizes
if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) {
showMaximized();
} else {
resize(mSettings->value(SETTINGS_WINDOW_WIDTH, 800).toInt(),
mSettings->value(SETTINGS_WINDOW_HEIGHT, 600).toInt());
}
const ReportType reportType = (ReportType)mSettings->value(SETTINGS_REPORT_TYPE, (int)ReportType::normal).toInt();
mUI->mActionReportNormal->setChecked(reportType <= ReportType::normal);
mUI->mActionReportAutosar->setChecked(reportType == ReportType::autosar);
mUI->mActionReportCertC->setChecked(reportType == ReportType::certC);
mUI->mActionReportCertCpp->setChecked(reportType == ReportType::certCpp);
mUI->mActionReportMisraC->setChecked(reportType == ReportType::misraC);
mUI->mActionReportMisraCpp2008->setChecked(reportType == ReportType::misraCpp2008);
mUI->mActionReportMisraCpp2023->setChecked(reportType == ReportType::misraCpp2023);
const ShowTypes &types = mUI->mResults->getShowTypes();
mUI->mActionShowStyle->setChecked(types.isShown(ShowTypes::ShowStyle));
mUI->mActionShowErrors->setChecked(types.isShown(ShowTypes::ShowErrors));
mUI->mActionShowWarnings->setChecked(types.isShown(ShowTypes::ShowWarnings));
mUI->mActionShowPortability->setChecked(types.isShown(ShowTypes::ShowPortability));
mUI->mActionShowPerformance->setChecked(types.isShown(ShowTypes::ShowPerformance));
mUI->mActionShowInformation->setChecked(types.isShown(ShowTypes::ShowInformation));
mUI->mActionShowCppcheck->setChecked(true);
mUI->mActionShowClang->setChecked(true);
Standards standards;
standards.setC(mSettings->value(SETTINGS_STD_C, QString()).toString().toStdString());
mUI->mActionC89->setChecked(standards.c == Standards::C89);
mUI->mActionC99->setChecked(standards.c == Standards::C99);
mUI->mActionC11->setChecked(standards.c == Standards::C11);
//mUI->mActionC17->setChecked(standards.c == Standards::C17);
//mUI->mActionC23->setChecked(standards.c == Standards::C23);
standards.setCPP(mSettings->value(SETTINGS_STD_CPP, QString()).toString().toStdString());
mUI->mActionCpp03->setChecked(standards.cpp == Standards::CPP03);
mUI->mActionCpp11->setChecked(standards.cpp == Standards::CPP11);
mUI->mActionCpp14->setChecked(standards.cpp == Standards::CPP14);
mUI->mActionCpp17->setChecked(standards.cpp == Standards::CPP17);
mUI->mActionCpp20->setChecked(standards.cpp == Standards::CPP20);
//mUI->mActionCpp23->setChecked(standards.cpp == Standards::CPP23);
//mUI->mActionCpp26->setChecked(standards.cpp == Standards::CPP26);
// Main window settings
const bool showMainToolbar = mSettings->value(SETTINGS_TOOLBARS_MAIN_SHOW, true).toBool();
mUI->mActionToolBarMain->setChecked(showMainToolbar);
mUI->mToolBarMain->setVisible(showMainToolbar);
const bool showViewToolbar = mSettings->value(SETTINGS_TOOLBARS_VIEW_SHOW, true).toBool();
mUI->mActionToolBarView->setChecked(showViewToolbar);
mUI->mToolBarView->setVisible(showViewToolbar);
const bool showFilterToolbar = mSettings->value(SETTINGS_TOOLBARS_FILTER_SHOW, true).toBool();
mUI->mActionToolBarFilter->setChecked(showFilterToolbar);
mUI->mToolBarFilter->setVisible(showFilterToolbar);
const Standards::Language enforcedLanguage = (Standards::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
if (enforcedLanguage == Standards::Language::CPP)
mUI->mActionEnforceCpp->setChecked(true);
else if (enforcedLanguage == Standards::Language::C)
mUI->mActionEnforceC->setChecked(true);
else
mUI->mActionAutoDetectLanguage->setChecked(true);
const bool succeeded = mApplications->loadSettings();
if (!succeeded) {
const QString msg = tr("There was a problem with loading the editor application settings.\n\n"
"This is probably because the settings were changed between the Cppcheck versions. "
"Please check (and fix) the editor application settings, otherwise the editor "
"program might not start correctly.");
QMessageBox msgBox(QMessageBox::Warning,
tr("Cppcheck"),
msg,
QMessageBox::Ok,
this);
msgBox.exec();
}
const QString projectFile = mSettings->value(SETTINGS_OPEN_PROJECT, QString()).toString();
if (!projectFile.isEmpty() && QCoreApplication::arguments().size()==1) {
QFileInfo inf(projectFile);
if (inf.exists() && inf.isReadable()) {
setPath(SETTINGS_LAST_PROJECT_PATH, projectFile);
mProjectFile = new ProjectFile(this);
mProjectFile->setActiveProject();
mProjectFile->read(projectFile);
loadLastResults();
QDir::setCurrent(inf.absolutePath());
}
}
}
void MainWindow::saveSettings() const
{
// Window/dialog sizes
mSettings->setValue(SETTINGS_WINDOW_WIDTH, size().width());
mSettings->setValue(SETTINGS_WINDOW_HEIGHT, size().height());
mSettings->setValue(SETTINGS_WINDOW_MAXIMIZED, isMaximized());
const ReportType reportType = mUI->mActionReportAutosar->isChecked() ? ReportType::autosar :
mUI->mActionReportCertC->isChecked() ? ReportType::certC :
mUI->mActionReportCertCpp->isChecked() ? ReportType::certCpp :
mUI->mActionReportMisraC->isChecked() ? ReportType::misraC :
mUI->mActionReportMisraCpp2008->isChecked() ? ReportType::misraCpp2008 :
mUI->mActionReportMisraCpp2023->isChecked() ? ReportType::misraCpp2023 :
ReportType::normal;
mSettings->setValue(SETTINGS_REPORT_TYPE, (int)reportType);
// Show * states
mSettings->setValue(SETTINGS_SHOW_STYLE, mUI->mActionShowStyle->isChecked());
mSettings->setValue(SETTINGS_SHOW_ERRORS, mUI->mActionShowErrors->isChecked());
mSettings->setValue(SETTINGS_SHOW_WARNINGS, mUI->mActionShowWarnings->isChecked());
mSettings->setValue(SETTINGS_SHOW_PORTABILITY, mUI->mActionShowPortability->isChecked());
mSettings->setValue(SETTINGS_SHOW_PERFORMANCE, mUI->mActionShowPerformance->isChecked());
mSettings->setValue(SETTINGS_SHOW_INFORMATION, mUI->mActionShowInformation->isChecked());
if (mUI->mActionC89->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C89");
if (mUI->mActionC99->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C99");
if (mUI->mActionC11->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C11");
//if (mUI->mActionC17->isChecked())
// mSettings->setValue(SETTINGS_STD_C, "C17");
//if (mUI->mActionC23->isChecked())
// mSettings->setValue(SETTINGS_STD_C, "C23");
if (mUI->mActionCpp03->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++03");
if (mUI->mActionCpp11->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++11");
if (mUI->mActionCpp14->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++14");
if (mUI->mActionCpp17->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++17");
if (mUI->mActionCpp20->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++20");
//if (mUI.mActionCpp23->isChecked())
// mSettings->setValue(SETTINGS_STD_CPP, "C++23");
//if (mUI.mActionCpp26->isChecked())
// mSettings->setValue(SETTINGS_STD_CPP, "C++26");
// Main window settings
mSettings->setValue(SETTINGS_TOOLBARS_MAIN_SHOW, mUI->mToolBarMain->isVisible());
mSettings->setValue(SETTINGS_TOOLBARS_VIEW_SHOW, mUI->mToolBarView->isVisible());
mSettings->setValue(SETTINGS_TOOLBARS_FILTER_SHOW, mUI->mToolBarFilter->isVisible());
if (mUI->mActionEnforceCpp->isChecked())
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::CPP);
else if (mUI->mActionEnforceC->isChecked())
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::C);
else
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::None);
mApplications->saveSettings();
mSettings->setValue(SETTINGS_LANGUAGE, mTranslation->getCurrentLanguage());
mSettings->setValue(SETTINGS_OPEN_PROJECT, mProjectFile ? mProjectFile->getFilename() : QString());
mUI->mResults->saveSettings(mSettings);
}
void MainWindow::doAnalyzeProject(ImportProject p, const bool checkLibrary, const bool checkConfiguration)
{
QPair<bool,Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
Settings& checkSettings = checkSettingsPair.second;
clearResults();
mIsLogfileLoaded = false;
if (mProjectFile) {
std::vector<std::string> v;
const QStringList excluded = mProjectFile->getExcludedPaths();
std::transform(excluded.cbegin(), excluded.cend(), std::back_inserter(v), [](const QString& e) {
return e.toStdString();
});
p.ignorePaths(v);
if (!mProjectFile->getAnalyzeAllVsConfigs()) {
const Platform::Type platform = (Platform::Type) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt();
std::vector<std::string> configurations;
const QStringList configs = mProjectFile->getVsConfigurations();
std::transform(configs.cbegin(), configs.cend(), std::back_inserter(configurations), [](const QString& e) {
return e.toStdString();
});
p.selectVsConfigurations(platform, configurations);
}
} else {
enableProjectActions(false);
}
mUI->mResults->clear(true);
mThread->clearFiles();
mUI->mResults->checkingStarted(p.fileSettings.size());
QDir inf(mCurrentDirectory);
const QString checkPath = inf.canonicalPath();
setPath(SETTINGS_LAST_CHECK_PATH, checkPath);
checkLockDownUI(); // lock UI while checking
mUI->mResults->setCheckDirectory(checkPath);
checkSettings.force = false;
checkSettings.checkLibrary = checkLibrary;
checkSettings.checkConfiguration = checkConfiguration;
if (mProjectFile)
qDebug() << "Checking project file" << mProjectFile->getFilename();
if (!checkSettings.buildDir.empty()) {
checkSettings.loadSummaries();
std::list<std::string> sourcefiles;
AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, p.fileSettings);
}
//mThread->SetanalyzeProject(true);
if (mProjectFile) {
mThread->setAddonsAndTools(mProjectFile->getAddonsAndTools());
QString clangHeaders = mSettings->value(SETTINGS_VS_INCLUDE_PATHS).toString();
mThread->setClangIncludePaths(clangHeaders.split(";"));
mThread->setSuppressions(mProjectFile->getSuppressions());
}
mThread->setProject(p);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::doAnalyzeFiles(const QStringList &files, const bool checkLibrary, const bool checkConfiguration)
{
if (files.isEmpty())
return;
QPair<bool, Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
Settings& checkSettings = checkSettingsPair.second;
clearResults();
mIsLogfileLoaded = false;
FileList pathList;
pathList.addPathList(files);
if (mProjectFile) {
pathList.addExcludeList(mProjectFile->getExcludedPaths());
} else {
enableProjectActions(false);
}
QStringList fileNames = pathList.getFileList();
mUI->mResults->clear(true);
mThread->clearFiles();
if (fileNames.isEmpty()) {
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
tr("No suitable files found to analyze!"),
QMessageBox::Ok,
this);
msg.exec();
return;
}
mUI->mResults->checkingStarted(fileNames.count());
mThread->setFiles(fileNames);
if (mProjectFile && !checkConfiguration)
mThread->setAddonsAndTools(mProjectFile->getAddonsAndTools());
mThread->setSuppressions(mProjectFile ? mProjectFile->getCheckingSuppressions() : QList<SuppressionList::Suppression>());
QDir inf(mCurrentDirectory);
const QString checkPath = inf.canonicalPath();
setPath(SETTINGS_LAST_CHECK_PATH, checkPath);
checkLockDownUI(); // lock UI while checking
mUI->mResults->setCheckDirectory(checkPath);
checkSettings.checkLibrary = checkLibrary;
checkSettings.checkConfiguration = checkConfiguration;
if (mProjectFile)
qDebug() << "Checking project file" << mProjectFile->getFilename();
if (!checkSettings.buildDir.empty()) {
checkSettings.loadSummaries();
std::list<std::string> sourcefiles;
std::transform(fileNames.cbegin(), fileNames.cend(), std::back_inserter(sourcefiles), [](const QString& s) {
return s.toStdString();
});
AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, {});
}
mThread->setCheckFiles(true);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::analyzeCode(const QString& code, const QString& filename)
{
const QPair<bool, Settings>& checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Initialize dummy ThreadResult as ErrorLogger
ThreadResult result;
result.setFiles(QStringList(filename));
connect(&result, SIGNAL(progress(int,QString)),
mUI->mResults, SLOT(progress(int,QString)));
connect(&result, SIGNAL(error(ErrorItem)),
mUI->mResults, SLOT(error(ErrorItem)));
connect(&result, SIGNAL(log(QString)),
mUI->mResults, SLOT(log(QString)));
connect(&result, SIGNAL(debugError(ErrorItem)),
mUI->mResults, SLOT(debugError(ErrorItem)));
// Create CppCheck instance
CppCheck cppcheck(result, true, nullptr);
cppcheck.settings() = checkSettings;
// Check
checkLockDownUI();
clearResults();
mUI->mResults->checkingStarted(1);
cppcheck.check(FileWithDetails(filename.toStdString()), code.toStdString());
analysisDone();
// Expand results
if (mUI->mResults->hasVisibleResults())
mUI->mResults->expandAllResults();
}
QStringList MainWindow::selectFilesToAnalyze(QFileDialog::FileMode mode)
{
if (mProjectFile) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("You must close the project file before selecting new files or directories!"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return QStringList();
}
QStringList selected;
// NOTE: we use QFileDialog::getOpenFileNames() and
// QFileDialog::getExistingDirectory() because they show native Windows
// selection dialog which is a lot more usable than Qt:s own dialog.
if (mode == QFileDialog::ExistingFiles) {
QMap<QString,QString> filters;
filters[tr("C/C++ Source")] = FileList::getDefaultFilters().join(" ");
filters[tr("Compile database")] = compile_commands_json;
filters[tr("Visual Studio")] = "*.sln *.vcxproj";
filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString lastFilter = mSettings->value(SETTINGS_LAST_ANALYZE_FILES_FILTER).toString();
selected = QFileDialog::getOpenFileNames(this,
tr("Select files to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH),
toFilterString(filters),
&lastFilter);
mSettings->setValue(SETTINGS_LAST_ANALYZE_FILES_FILTER, lastFilter);
if (selected.isEmpty())
mCurrentDirectory.clear();
else {
QFileInfo inf(selected[0]);
mCurrentDirectory = inf.absolutePath();
}
formatAndSetTitle();
} else if (mode == QFileDialog::Directory) {
QString dir = QFileDialog::getExistingDirectory(this,
tr("Select directory to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH));
if (!dir.isEmpty()) {
qDebug() << "Setting current directory to: " << dir;
mCurrentDirectory = dir;
selected.append(dir);
dir = QDir::toNativeSeparators(dir);
formatAndSetTitle(dir);
}
}
if (!mCurrentDirectory.isEmpty())
setPath(SETTINGS_LAST_CHECK_PATH, mCurrentDirectory);
return selected;
}
void MainWindow::analyzeFiles()
{
Settings::terminate(false);
QStringList selected = selectFilesToAnalyze(QFileDialog::ExistingFiles);
const QString file0 = (!selected.empty() ? selected[0].toLower() : QString());
if (file0.endsWith(".sln")
|| file0.endsWith(".vcxproj")
|| file0.endsWith(compile_commands_json)
|| file0.endsWith(".bpr")) {
ImportProject p;
p.import(selected[0].toStdString());
if (file0.endsWith(".sln")) {
QStringList configs;
for (std::list<FileSettings>::const_iterator it = p.fileSettings.cbegin(); it != p.fileSettings.cend(); ++it) {
const QString cfg(QString::fromStdString(it->cfg));
if (!configs.contains(cfg))
configs.push_back(cfg);
}
configs.sort();
bool ok = false;
const QString cfg = QInputDialog::getItem(this, tr("Select configuration"), tr("Select the configuration that will be analyzed"), configs, 0, false, &ok);
if (!ok)
return;
p.ignoreOtherConfigs(cfg.toStdString());
}
doAnalyzeProject(p);
return;
}
doAnalyzeFiles(selected);
}
void MainWindow::analyzeDirectory()
{
QStringList dir = selectFilesToAnalyze(QFileDialog::Directory);
if (dir.isEmpty())
return;
QDir checkDir(dir[0]);
QStringList filters;
filters << "*.cppcheck";
checkDir.setFilter(QDir::Files | QDir::Readable);
checkDir.setNameFilters(filters);
QStringList projFiles = checkDir.entryList();
if (!projFiles.empty()) {
if (projFiles.size() == 1) {
// If one project file found, suggest loading it
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Found project file: %1\n\nDo you want to "
"load this project file instead?").arg(projFiles[0]));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
QString path = checkDir.canonicalPath();
if (!path.endsWith("/"))
path += "/";
path += projFiles[0];
loadProjectFile(path);
} else {
doAnalyzeFiles(dir);
}
} else {
// If multiple project files found inform that there are project
// files also available.
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Found project files from the directory.\n\n"
"Do you want to proceed analysis without "
"using any of these project files?"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
doAnalyzeFiles(dir);
}
}
} else {
doAnalyzeFiles(dir);
}
}
void MainWindow::addIncludeDirs(const QStringList &includeDirs, Settings &result)
{
for (const QString& dir : includeDirs) {
QString incdir;
if (!QDir::isAbsolutePath(dir))
incdir = mCurrentDirectory + "/";
incdir += dir;
incdir = QDir::cleanPath(incdir);
// include paths must end with '/'
if (!incdir.endsWith("/"))
incdir += "/";
result.includePaths.push_back(incdir.toStdString());
}
}
Library::Error MainWindow::loadLibrary(Library &library, const QString &filename)
{
Library::Error ret;
// Try to load the library from the project folder..
if (mProjectFile) {
QString path = QFileInfo(mProjectFile->getFilename()).canonicalPath();
QString libpath = path+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
// Try to load the library from the application folder..
const QString appPath = QFileInfo(QCoreApplication::applicationFilePath()).canonicalPath();
QString libpath = appPath+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = appPath+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
#ifdef FILESDIR
// Try to load the library from FILESDIR/cfg..
const QString filesdir = FILESDIR;
if (!filesdir.isEmpty()) {
libpath = filesdir+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = filesdir+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
#endif
// Try to load the library from the cfg subfolder..
const QString datadir = getDataDir();
if (!datadir.isEmpty()) {
libpath = datadir+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = datadir+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
qDebug().noquote() << "library not found: '" + filename + "'";
return ret;
}
bool MainWindow::tryLoadLibrary(Library &library, const QString& filename)
{
const Library::Error error = loadLibrary(library, filename);
if (error.errorcode != Library::ErrorCode::OK) {
if (error.errorcode == Library::ErrorCode::UNKNOWN_ELEMENT) {
QMessageBox::information(this, tr("Information"), tr("The library '%1' contains unknown elements:\n%2").arg(filename).arg(error.reason.c_str()));
return true;
}
QString errmsg;
switch (error.errorcode) {
case Library::ErrorCode::OK:
break;
case Library::ErrorCode::FILE_NOT_FOUND:
errmsg = tr("File not found");
break;
case Library::ErrorCode::BAD_XML:
errmsg = tr("Bad XML");
break;
case Library::ErrorCode::MISSING_ATTRIBUTE:
errmsg = tr("Missing attribute");
break;
case Library::ErrorCode::BAD_ATTRIBUTE_VALUE:
errmsg = tr("Bad attribute value");
break;
case Library::ErrorCode::UNSUPPORTED_FORMAT:
errmsg = tr("Unsupported format");
break;
case Library::ErrorCode::DUPLICATE_PLATFORM_TYPE:
errmsg = tr("Duplicate platform type");
break;
case Library::ErrorCode::PLATFORM_TYPE_REDEFINED:
errmsg = tr("Platform type redefined");
break;
case Library::ErrorCode::DUPLICATE_DEFINE:
errmsg = tr("Duplicate define");
break;
case Library::ErrorCode::UNKNOWN_ELEMENT:
errmsg = tr("Unknown element");
break;
default:
errmsg = tr("Unknown issue");
break;
}
if (!error.reason.empty())
errmsg += " '" + QString::fromStdString(error.reason) + "'";
QMessageBox::information(this, tr("Information"), tr("Failed to load the selected library '%1'.\n%2").arg(filename).arg(errmsg));
return false;
}
return true;
}
QString MainWindow::loadAddon(Settings &settings, const QString &filesDir, const QString &pythonCmd, const QString& addon)
{
const QString addonFilePath = fromNativePath(ProjectFile::getAddonFilePath(filesDir, addon));
if (addonFilePath.isEmpty())
return tr("File not found: '%1'").arg(addon);
picojson::object obj;
obj["script"] = picojson::value(addonFilePath.toStdString());
if (!pythonCmd.isEmpty())
obj["python"] = picojson::value(pythonCmd.toStdString());
if (!isCppcheckPremium() && addon == "misra") {
const QString misraFile = fromNativePath(mSettings->value(SETTINGS_MISRA_FILE).toString());
if (!misraFile.isEmpty()) {
QString arg;
picojson::array arr;
if (misraFile.endsWith(".pdf", Qt::CaseInsensitive))
arg = "--misra-pdf=" + misraFile;
else
arg = "--rule-texts=" + misraFile;
arr.emplace_back(arg.toStdString());
obj["args"] = picojson::value(arr);
}
}
const std::string& json_str = picojson::value(obj).serialize();
AddonInfo addonInfo;
const std::string errmsg = addonInfo.getAddonInfo(json_str, settings.exename);
if (!errmsg.empty())
return tr("Failed to load/setup addon %1: %2").arg(addon, QString::fromStdString(errmsg));
settings.addonInfos.emplace_back(std::move(addonInfo));
settings.addons.emplace(json_str);
return "";
}
QPair<bool,Settings> MainWindow::getCppcheckSettings()
{
saveSettings(); // Save settings
Settings::terminate(true);
Settings result;
result.exename = QCoreApplication::applicationFilePath().toStdString();
// default to --check-level=normal for GUI for now
result.setCheckLevel(Settings::CheckLevel::normal);
const bool std = tryLoadLibrary(result.library, "std.cfg");
if (!std) {
QMessageBox::critical(this, tr("Error"), tr("Failed to load %1. Your Cppcheck installation is broken. You can use --data-dir=<directory> at the command line to specify where this file is located. Please note that --data-dir is supposed to be used by installation scripts and therefore the GUI does not start when it is used, all that happens is that the setting is configured.\n\nAnalysis is aborted.").arg("std.cfg"));
return {false, {}};
}
const QString filesDir(getDataDir());
const QString pythonCmd = fromNativePath(mSettings->value(SETTINGS_PYTHON_PATH).toString());
{
const QString cfgErr = QString::fromStdString(Settings::loadCppcheckCfg(result, result.supprs));
if (!cfgErr.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("Failed to load %1 - %2\n\nAnalysis is aborted.").arg("cppcheck.cfg").arg(cfgErr));
return {false, {}};
}
const auto cfgAddons = result.addons;
result.addons.clear();
for (const std::string& addon : cfgAddons) {
// TODO: support addons which are a script and not a file
const QString addonError = loadAddon(result, filesDir, pythonCmd, QString::fromStdString(addon));
if (!addonError.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("%1\n\nAnalysis is aborted.").arg(addonError));
return {false, {}};
}
}
}
// If project file loaded, read settings from it
if (mProjectFile) {
QStringList dirs = mProjectFile->getIncludeDirs();
addIncludeDirs(dirs, result);
result.inlineSuppressions = mProjectFile->getInlineSuppression();
const QStringList defines = mProjectFile->getDefines();
for (const QString& define : defines) {
if (!result.userDefines.empty())
result.userDefines += ";";
result.userDefines += define.toStdString();
}
result.clang = mProjectFile->clangParser;
const QStringList undefines = mProjectFile->getUndefines();
for (const QString& undefine : undefines)
result.userUndefs.insert(undefine.toStdString());
const QStringList libraries = mProjectFile->getLibraries();
for (const QString& library : libraries) {
result.libraries.emplace_back(library.toStdString());
const QString filename = library + ".cfg";
tryLoadLibrary(result.library, filename);
}
for (const SuppressionList::Suppression &suppression : mProjectFile->getCheckingSuppressions()) {
result.supprs.nomsg.addSuppression(suppression);
}
// Only check the given -D configuration
if (!defines.isEmpty())
result.maxConfigs = 1;
// If importing a project, only check the given configuration
if (!mProjectFile->getImportProject().isEmpty())
result.checkAllConfigurations = false;
const QString &buildDir = fromNativePath(mProjectFile->getBuildDir());
if (!buildDir.isEmpty()) {
if (QDir(buildDir).isAbsolute()) {
result.buildDir = buildDir.toStdString();
} else {
QString prjpath = QFileInfo(mProjectFile->getFilename()).absolutePath();
result.buildDir = (prjpath + '/' + buildDir).toStdString();
}
}
const QString platform = mProjectFile->getPlatform();
if (platform.endsWith(".xml")) {
const QString applicationFilePath = QCoreApplication::applicationFilePath();
result.platform.loadFromFile(applicationFilePath.toStdString().c_str(), platform.toStdString());
} else {
for (int i = Platform::Type::Native; i <= Platform::Type::Unix64; i++) {
const auto p = (Platform::Type)i;
if (platform == Platform::toString(p)) {
result.platform.set(p);
break;
}
}
}
result.maxCtuDepth = mProjectFile->getMaxCtuDepth();
result.maxTemplateRecursion = mProjectFile->getMaxTemplateRecursion();
if (mProjectFile->isCheckLevelExhaustive())
result.setCheckLevel(Settings::CheckLevel::exhaustive);
else
result.setCheckLevel(Settings::CheckLevel::normal);
result.checkHeaders = mProjectFile->getCheckHeaders();
result.checkUnusedTemplates = mProjectFile->getCheckUnusedTemplates();
result.safeChecks.classes = mProjectFile->safeChecks.classes;
result.safeChecks.externalFunctions = mProjectFile->safeChecks.externalFunctions;
result.safeChecks.internalFunctions = mProjectFile->safeChecks.internalFunctions;
result.safeChecks.externalVariables = mProjectFile->safeChecks.externalVariables;
for (const QString& s : mProjectFile->getCheckUnknownFunctionReturn())
result.checkUnknownFunctionReturn.insert(s.toStdString());
for (const QString& addon : mProjectFile->getAddons()) {
const QString addonError = loadAddon(result, filesDir, pythonCmd, addon);
if (!addonError.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("%1\n\nAnalysis is aborted.").arg(addonError));
return {false, {}};
}
}
if (isCppcheckPremium()) {
QString premiumArgs;
if (mProjectFile->getBughunting())
premiumArgs += " --bughunting";
if (mProjectFile->getCertIntPrecision() > 0)
premiumArgs += " --cert-c-int-precision=" + QString::number(mProjectFile->getCertIntPrecision());
for (const QString& c: mProjectFile->getCodingStandards())
premiumArgs += " --" + c;
if (!premiumArgs.contains("misra") && mProjectFile->getAddons().contains("misra"))
premiumArgs += " --misra-c-2012";
result.premiumArgs = premiumArgs.mid(1).toStdString();
result.setMisraRuleTexts(CheckThread::executeCommand);
}
}
else
result.inlineSuppressions = mSettings->value(SETTINGS_INLINE_SUPPRESSIONS, false).toBool();
// Include directories (and files) are searched in listed order.
// Global include directories must be added AFTER the per project include
// directories so per project include directories can override global ones.
const QString globalIncludes = mSettings->value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString();
if (!globalIncludes.isEmpty()) {
QStringList includes = globalIncludes.split(";");
addIncludeDirs(includes, result);
}
result.severity.enable(Severity::warning);
result.severity.enable(Severity::style);
result.severity.enable(Severity::performance);
result.severity.enable(Severity::portability);
result.severity.enable(Severity::information);
result.checks.enable(Checks::missingInclude);
if (!result.buildDir.empty())
result.checks.enable(Checks::unusedFunction);
result.debugwarnings = mSettings->value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool();
result.quiet = false;
result.verbose = true;
result.force = mSettings->value(SETTINGS_CHECK_FORCE, 1).toBool();
result.xml = false;
result.jobs = mSettings->value(SETTINGS_CHECK_THREADS, 1).toInt();
result.certainty.setEnabled(Certainty::inconclusive, mSettings->value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool());
if (!mProjectFile || result.platform.type == Platform::Type::Unspecified)
result.platform.set((Platform::Type) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt());
result.standards.setCPP(mSettings->value(SETTINGS_STD_CPP, QString()).toString().toStdString());
result.standards.setC(mSettings->value(SETTINGS_STD_C, QString()).toString().toStdString());
result.enforcedLang = (Standards::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
result.jobs = std::max(result.jobs, 1u);
Settings::terminate(false);
return {true, std::move(result)};
}
void MainWindow::analysisDone()
{
if (mExiting) {
close();
return;
}
mUI->mResults->checkingFinished();
enableCheckButtons(true);
mUI->mActionSettings->setEnabled(true);
mUI->mActionOpenXML->setEnabled(true);
if (mProjectFile) {
enableProjectActions(true);
} else if (mIsLogfileLoaded) {
mUI->mActionReanalyzeModified->setEnabled(false);
mUI->mActionReanalyzeAll->setEnabled(false);
}
enableProjectOpenActions(true);
mPlatformActions->setEnabled(true);
mCStandardActions->setEnabled(true);
mCppStandardActions->setEnabled(true);
mSelectLanguageActions->setEnabled(true);
mUI->mActionPosix->setEnabled(true);
if (mScratchPad)
mScratchPad->setEnabled(true);
mUI->mActionViewStats->setEnabled(true);
if (mProjectFile && !mProjectFile->getBuildDir().isEmpty()) {
const QString prjpath = QFileInfo(mProjectFile->getFilename()).absolutePath();
const QString buildDir = prjpath + '/' + mProjectFile->getBuildDir();
if (QDir(buildDir).exists()) {
mUI->mResults->saveStatistics(buildDir + "/statistics.txt");
mUI->mResults->updateFromOldReport(buildDir + "/lastResults.xml");
mUI->mResults->save(buildDir + "/lastResults.xml", Report::XMLV2, mCppcheckCfgProductName);
}
}
enableResultsButtons();
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
recentProjectAct->setEnabled(true);
}
// Notify user - if the window is not active - that check is ready
QApplication::alert(this, 3000);
if (mSettings->value(SETTINGS_SHOW_STATISTICS, false).toBool())
showStatistics();
}
void MainWindow::checkLockDownUI()
{
enableCheckButtons(false);
mUI->mActionSettings->setEnabled(false);
mUI->mActionOpenXML->setEnabled(false);
enableProjectActions(false);
enableProjectOpenActions(false);
mPlatformActions->setEnabled(false);
mCStandardActions->setEnabled(false);
mCppStandardActions->setEnabled(false);
mSelectLanguageActions->setEnabled(false);
mUI->mActionPosix->setEnabled(false);
if (mScratchPad)
mScratchPad->setEnabled(false);
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
recentProjectAct->setEnabled(false);
}
}
void MainWindow::programSettings()
{
SettingsDialog dialog(mApplications, mTranslation, isCppcheckPremium(), this);
if (dialog.exec() == QDialog::Accepted) {
dialog.saveSettingValues();
mSettings->sync();
mUI->mResults->updateSettings(dialog.showFullPath(),
dialog.saveFullPath(),
dialog.saveAllErrors(),
dialog.showNoErrorsMessage(),
dialog.showErrorId(),
dialog.showInconclusive());
mUI->mResults->updateStyleSetting(mSettings);
const QString newLang = mSettings->value(SETTINGS_LANGUAGE, "en").toString();
setLanguage(newLang);
}
}
void MainWindow::reAnalyzeModified()
{
reAnalyze(false);
}
void MainWindow::reAnalyzeAll()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList());
else
reAnalyze(true);
}
void MainWindow::checkLibrary()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList(), true);
}
void MainWindow::checkConfiguration()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList(), false, true);
}
void MainWindow::reAnalyzeSelected(const QStringList& files)
{
if (files.empty())
return;
if (mThread->isChecking())
return;
if (mProjectFile) {
// Clear details, statistics and progress
mUI->mResults->clear(false);
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clearRecheckFile(files[i]);
analyzeProject(mProjectFile, files);
return;
}
const QPair<bool, Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Clear details, statistics and progress
mUI->mResults->clear(false);
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clearRecheckFile(files[i]);
mCurrentDirectory = mUI->mResults->getCheckDirectory();
FileList pathList;
pathList.addPathList(files);
if (mProjectFile)
pathList.addExcludeList(mProjectFile->getExcludedPaths());
QStringList fileNames = pathList.getFileList();
checkLockDownUI(); // lock UI while checking
mUI->mResults->checkingStarted(fileNames.size());
mThread->setCheckFiles(fileNames);
// Saving last check start time, otherwise unchecked modified files will not be
// considered in "Modified Files Check" performed after "Selected Files Check"
// TODO: Should we store per file CheckStartTime?
QDateTime saveCheckStartTime = mThread->getCheckStartTime();
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
mThread->setCheckStartTime(std::move(saveCheckStartTime));
}
void MainWindow::reAnalyze(bool all)
{
const QStringList files = mThread->getReCheckFiles(all);
if (files.empty())
return;
const QPair<bool, Settings>& checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Clear details, statistics and progress
mUI->mResults->clear(all);
// Clear results for changed files
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clear(files[i]);
checkLockDownUI(); // lock UI while checking
mUI->mResults->checkingStarted(files.size());
if (mProjectFile)
qDebug() << "Rechecking project file" << mProjectFile->getFilename();
mThread->setCheckFiles(all);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::clearResults()
{
if (mProjectFile && !mProjectFile->getBuildDir().isEmpty()) {
QDir dir(QFileInfo(mProjectFile->getFilename()).absolutePath() + '/' + mProjectFile->getBuildDir());
for (const QString& f: dir.entryList(QDir::Files)) {
if (!f.endsWith("files.txt")) {
static const QRegularExpression rx("^.*.s[0-9]+$");
if (!rx.match(f).hasMatch())
dir.remove(f);
}
}
}
mUI->mResults->clear(true);
Q_ASSERT(false == mUI->mResults->hasResults());
enableResultsButtons();
}
void MainWindow::openResults()
{
if (mUI->mResults->hasResults()) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Current results will be cleared.\n\n"
"Opening a new XML file will clear current results.\n"
"Do you want to proceed?"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::No) {
return;
}
}
QString selectedFilter;
const QString filter(tr("XML files (*.xml)"));
QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Open the report file"),
getPath(SETTINGS_LAST_RESULT_PATH),
filter,
&selectedFilter);
if (!selectedFile.isEmpty()) {
loadResults(selectedFile);
}
}
void MainWindow::loadResults(const QString &selectedFile)
{
if (selectedFile.isEmpty())
return;
if (mProjectFile)
closeProjectFile();
mIsLogfileLoaded = true;
mUI->mResults->clear(true);
mUI->mActionReanalyzeModified->setEnabled(false);
mUI->mActionReanalyzeAll->setEnabled(false);
mUI->mResults->readErrorsXml(selectedFile);
setPath(SETTINGS_LAST_RESULT_PATH, selectedFile);
formatAndSetTitle(selectedFile);
}
void MainWindow::loadResults(const QString &selectedFile, const QString &sourceDirectory)
{
loadResults(selectedFile);
mUI->mResults->setCheckDirectory(sourceDirectory);
}
void MainWindow::enableCheckButtons(bool enable)
{
mUI->mActionStop->setEnabled(!enable);
mUI->mActionAnalyzeFiles->setEnabled(enable);
if (mProjectFile) {
mUI->mActionReanalyzeModified->setEnabled(enable);
mUI->mActionReanalyzeAll->setEnabled(enable);
} else if (!enable || mThread->hasPreviousFiles()) {
mUI->mActionReanalyzeModified->setEnabled(enable);
mUI->mActionReanalyzeAll->setEnabled(enable);
}
mUI->mActionAnalyzeDirectory->setEnabled(enable);
if (isCppcheckPremium()) {
mUI->mActionComplianceReport->setEnabled(enable && mProjectFile && (mProjectFile->getAddons().contains("misra") || !mProjectFile->getCodingStandards().empty()));
}
}
void MainWindow::enableResultsButtons()
{
const bool enabled = mUI->mResults->hasResults();
mUI->mActionClearResults->setEnabled(enabled);
mUI->mActionSave->setEnabled(enabled);
mUI->mActionPrint->setEnabled(enabled);
mUI->mActionPrintPreview->setEnabled(enabled);
}
void MainWindow::showStyle(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowStyle, checked);
}
void MainWindow::showErrors(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowErrors, checked);
}
void MainWindow::showWarnings(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowWarnings, checked);
}
void MainWindow::showPortability(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowPortability, checked);
}
void MainWindow::showPerformance(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowPerformance, checked);
}
void MainWindow::showInformation(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowInformation, checked);
}
void MainWindow::checkAll()
{
toggleAllChecked(true);
}
void MainWindow::uncheckAll()
{
toggleAllChecked(false);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// Check that we aren't checking files
if (!mThread->isChecking()) {
saveSettings();
event->accept();
} else {
const QString text(tr("Analyzer is running.\n\n" \
"Do you want to stop the analysis and exit Cppcheck?"));
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
text,
QMessageBox::Yes | QMessageBox::No,
this);
msg.setDefaultButton(QMessageBox::No);
const int rv = msg.exec();
if (rv == QMessageBox::Yes) {
// This isn't really very clean way to close threads but since the app is
// exiting it doesn't matter.
mThread->stop();
saveSettings();
mExiting = true;
}
event->ignore();
}
}
void MainWindow::toggleAllChecked(bool checked)
{
mUI->mActionShowStyle->setChecked(checked);
showStyle(checked);
mUI->mActionShowErrors->setChecked(checked);
showErrors(checked);
mUI->mActionShowWarnings->setChecked(checked);
showWarnings(checked);
mUI->mActionShowPortability->setChecked(checked);
showPortability(checked);
mUI->mActionShowPerformance->setChecked(checked);
showPerformance(checked);
mUI->mActionShowInformation->setChecked(checked);
showInformation(checked);
}
void MainWindow::about()
{
if (!mCppcheckCfgAbout.isEmpty()) {
QMessageBox msg(QMessageBox::Information,
tr("About"),
mCppcheckCfgAbout,
QMessageBox::Ok,
this);
msg.exec();
}
else {
auto *dlg = new AboutDialog(CppCheck::version(), CppCheck::extraVersion(), this);
dlg->exec();
}
}
void MainWindow::showLicense()
{
auto *dlg = new FileViewDialog(":COPYING", tr("License"), this);
dlg->resize(570, 400);
dlg->exec();
}
void MainWindow::showAuthors()
{
auto *dlg = new FileViewDialog(":AUTHORS", tr("Authors"), this);
dlg->resize(350, 400);
dlg->exec();
}
void MainWindow::performSelectedFilesCheck(const QStringList &selectedFilesList)
{
reAnalyzeSelected(selectedFilesList);
}
void MainWindow::save()
{
QString selectedFilter;
const QString filter(tr("XML files (*.xml);;Text files (*.txt);;CSV files (*.csv)"));
QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save the report file"),
getPath(SETTINGS_LAST_RESULT_PATH),
filter,
&selectedFilter);
if (!selectedFile.isEmpty()) {
Report::Type type = Report::TXT;
if (selectedFilter == tr("XML files (*.xml)")) {
type = Report::XMLV2;
if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive))
selectedFile += ".xml";
} else if (selectedFilter == tr("Text files (*.txt)")) {
type = Report::TXT;
if (!selectedFile.endsWith(".txt", Qt::CaseInsensitive))
selectedFile += ".txt";
} else if (selectedFilter == tr("CSV files (*.csv)")) {
type = Report::CSV;
if (!selectedFile.endsWith(".csv", Qt::CaseInsensitive))
selectedFile += ".csv";
} else {
if (selectedFile.endsWith(".xml", Qt::CaseInsensitive))
type = Report::XMLV2;
else if (selectedFile.endsWith(".txt", Qt::CaseInsensitive))
type = Report::TXT;
else if (selectedFile.endsWith(".csv", Qt::CaseInsensitive))
type = Report::CSV;
}
mUI->mResults->save(selectedFile, type, mCppcheckCfgProductName);
setPath(SETTINGS_LAST_RESULT_PATH, selectedFile);
}
}
void MainWindow::complianceReport()
{
if (!mUI->mResults->isSuccess()) {
QMessageBox m(QMessageBox::Critical,
"Cppcheck",
tr("Cannot generate a compliance report right now, an analysis must finish successfully. Try to reanalyze the code and ensure there are no critical errors."),
QMessageBox::Ok,
this);
m.exec();
return;
}
QTemporaryFile tempResults;
tempResults.open();
tempResults.close();
mUI->mResults->save(tempResults.fileName(), Report::XMLV2, mCppcheckCfgProductName);
ComplianceReportDialog dlg(mProjectFile, tempResults.fileName(), mUI->mResults->getStatistics()->getCheckersReport());
dlg.exec();
}
void MainWindow::resultsAdded()
{}
void MainWindow::toggleMainToolBar()
{
mUI->mToolBarMain->setVisible(mUI->mActionToolBarMain->isChecked());
}
void MainWindow::toggleViewToolBar()
{
mUI->mToolBarView->setVisible(mUI->mActionToolBarView->isChecked());
}
void MainWindow::toggleFilterToolBar()
{
mUI->mToolBarFilter->setVisible(mUI->mActionToolBarFilter->isChecked());
mLineEditFilter->clear(); // Clearing the filter also disables filtering
}
void MainWindow::formatAndSetTitle(const QString &text)
{
QString nameWithVersion = QString("Cppcheck %1").arg(CppCheck::version());
QString extraVersion = CppCheck::extraVersion();
if (!extraVersion.isEmpty()) {
nameWithVersion += " (" + extraVersion + ")";
}
if (!mCppcheckCfgProductName.isEmpty())
nameWithVersion = mCppcheckCfgProductName;
QString title;
if (text.isEmpty())
title = nameWithVersion;
else
title = QString("%1 - %2").arg(nameWithVersion, text);
setWindowTitle(title);
}
void MainWindow::setLanguage(const QString &code)
{
const QString currentLang = mTranslation->getCurrentLanguage();
if (currentLang == code)
return;
if (mTranslation->setLanguage(code)) {
//Translate everything that is visible here
mUI->retranslateUi(this);
mUI->mResults->translate();
mLineEditFilter->setPlaceholderText(QCoreApplication::translate("MainWindow", "Quick Filter:"));
if (mProjectFile)
formatAndSetTitle(tr("Project:") + ' ' + mProjectFile->getFilename());
if (mScratchPad)
mScratchPad->translate();
}
}
void MainWindow::aboutToShowViewMenu()
{
mUI->mActionToolBarMain->setChecked(mUI->mToolBarMain->isVisible());
mUI->mActionToolBarView->setChecked(mUI->mToolBarView->isVisible());
mUI->mActionToolBarFilter->setChecked(mUI->mToolBarFilter->isVisible());
}
void MainWindow::stopAnalysis()
{
mThread->stop();
mUI->mResults->stopAnalysis();
mUI->mResults->disableProgressbar();
const QString &lastResults = getLastResults();
if (!lastResults.isEmpty()) {
mUI->mResults->updateFromOldReport(lastResults);
}
}
void MainWindow::openHelpContents()
{
openOnlineHelp();
}
void MainWindow::openOnlineHelp()
{
auto *helpDialog = new HelpDialog;
helpDialog->showMaximized();
}
void MainWindow::openProjectFile()
{
const QString filter = tr("Project files (*.cppcheck);;All files(*.*)");
const QString filepath = QFileDialog::getOpenFileName(this,
tr("Select Project File"),
getPath(SETTINGS_LAST_PROJECT_PATH),
filter);
if (!filepath.isEmpty()) {
const QFileInfo fi(filepath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
setPath(SETTINGS_LAST_PROJECT_PATH, filepath);
loadProjectFile(filepath);
}
}
}
void MainWindow::showScratchpad()
{
if (!mScratchPad)
mScratchPad = new ScratchPad(*this);
mScratchPad->show();
if (!mScratchPad->isActiveWindow())
mScratchPad->activateWindow();
}
void MainWindow::loadProjectFile(const QString &filePath)
{
QFileInfo inf(filePath);
const QString filename = inf.fileName();
formatAndSetTitle(tr("Project:") + ' ' + filename);
addProjectMRU(filePath);
mIsLogfileLoaded = false;
mUI->mActionCloseProjectFile->setEnabled(true);
mUI->mActionEditProjectFile->setEnabled(true);
delete mProjectFile;
mProjectFile = new ProjectFile(filePath, this);
mProjectFile->setActiveProject();
if (!loadLastResults())
analyzeProject(mProjectFile, QStringList());
}
QString MainWindow::getLastResults() const
{
if (!mProjectFile || mProjectFile->getBuildDir().isEmpty())
return QString();
return QFileInfo(mProjectFile->getFilename()).absolutePath() + '/' + mProjectFile->getBuildDir() + "/lastResults.xml";
}
bool MainWindow::loadLastResults()
{
const QString &lastResults = getLastResults();
if (lastResults.isEmpty())
return false;
if (!QFileInfo::exists(lastResults))
return false;
mUI->mResults->clear(true);
mUI->mResults->readErrorsXml(lastResults);
mUI->mResults->setCheckDirectory(mSettings->value(SETTINGS_LAST_CHECK_PATH,QString()).toString());
mUI->mActionViewStats->setEnabled(true);
enableResultsButtons();
return true;
}
void MainWindow::analyzeProject(const ProjectFile *projectFile, const QStringList& recheckFiles, const bool checkLibrary, const bool checkConfiguration)
{
Settings::terminate(false);
QFileInfo inf(projectFile->getFilename());
const QString& rootpath = projectFile->getRootPath();
if (isCppcheckPremium() && !projectFile->getLicenseFile().isEmpty()) {
if (rootpath.isEmpty() || rootpath == ".")
QDir::setCurrent(inf.absolutePath());
else if (QDir(rootpath).isAbsolute())
QDir::setCurrent(rootpath);
else
QDir::setCurrent(inf.absolutePath() + "/" + rootpath);
QString licenseFile = projectFile->getLicenseFile();
if (!QFileInfo(licenseFile).isAbsolute() && !rootpath.isEmpty())
licenseFile = inf.absolutePath() + "/" + licenseFile;
#ifdef Q_OS_WIN
const QString premiumaddon = QCoreApplication::applicationDirPath() + "/premiumaddon.exe";
#else
const QString premiumaddon = QCoreApplication::applicationDirPath() + "/premiumaddon";
#endif
const std::vector<std::string> args{"--check-loc-license", licenseFile.toStdString()};
std::string output;
CheckThread::executeCommand(premiumaddon.toStdString(), args, "", output);
std::ofstream fout(inf.absolutePath().toStdString() + "/cppcheck-premium-loc");
fout << output;
}
QDir::setCurrent(inf.absolutePath());
mThread->setAddonsAndTools(projectFile->getAddonsAndTools());
// If the root path is not given or is not "current dir", use project
// file's location directory as root path
if (rootpath.isEmpty() || rootpath == ".")
mCurrentDirectory = inf.canonicalPath();
else if (rootpath.startsWith("./"))
mCurrentDirectory = inf.canonicalPath() + rootpath.mid(1);
else
mCurrentDirectory = rootpath;
if (!projectFile->getBuildDir().isEmpty()) {
QString buildDir = projectFile->getBuildDir();
if (!QDir::isAbsolutePath(buildDir))
buildDir = inf.canonicalPath() + '/' + buildDir;
if (!QDir(buildDir).exists()) {
QMessageBox msg(QMessageBox::Question,
tr("Cppcheck"),
tr("Build dir '%1' does not exist, create it?").arg(buildDir),
QMessageBox::Yes | QMessageBox::No,
this);
if (msg.exec() == QMessageBox::Yes) {
QDir().mkpath(buildDir);
} else if (!projectFile->getAddons().isEmpty()) {
QMessageBox m(QMessageBox::Critical,
tr("Cppcheck"),
tr("To check the project using addons, you need a build directory."),
QMessageBox::Ok,
this);
m.exec();
return;
}
}
}
if (!projectFile->getImportProject().isEmpty()) {
ImportProject p;
QString prjfile;
if (QFileInfo(projectFile->getImportProject()).isAbsolute()) {
prjfile = projectFile->getImportProject();
} else {
prjfile = inf.canonicalPath() + '/' + projectFile->getImportProject();
}
try {
const ImportProject::Type result = p.import(prjfile.toStdString());
QString errorMessage;
switch (result) {
case ImportProject::Type::COMPILE_DB:
case ImportProject::Type::VS_SLN:
case ImportProject::Type::VS_VCXPROJ:
case ImportProject::Type::BORLAND:
case ImportProject::Type::CPPCHECK_GUI:
// Loading was successful
break;
case ImportProject::Type::MISSING:
errorMessage = tr("Failed to open file");
break;
case ImportProject::Type::UNKNOWN:
errorMessage = tr("Unknown project file format");
break;
case ImportProject::Type::FAILURE:
errorMessage = tr("Failed to import project file");
break;
case ImportProject::Type::NONE:
// can never happen
break;
}
if (!errorMessage.isEmpty()) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Failed to import '%1': %2\n\nAnalysis is stopped.").arg(prjfile).arg(errorMessage),
QMessageBox::Ok,
this);
msg.exec();
return;
}
} catch (InternalError &e) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Failed to import '%1' (%2), analysis is stopped").arg(prjfile).arg(QString::fromStdString(e.errorMessage)),
QMessageBox::Ok,
this);
msg.exec();
return;
}
doAnalyzeProject(p, checkLibrary, checkConfiguration);
return;
}
QStringList paths = recheckFiles.isEmpty() ? projectFile->getCheckPaths() : recheckFiles;
// If paths not given then check the root path (which may be the project
// file's location, see above). This is to keep the compatibility with
// old "silent" project file loading when we checked the director where the
// project file was located.
if (paths.isEmpty()) {
paths << mCurrentDirectory;
}
doAnalyzeFiles(paths, checkLibrary, checkConfiguration);
}
void MainWindow::newProjectFile()
{
const QString filter = tr("Project files (*.cppcheck)");
QString filepath = QFileDialog::getSaveFileName(this,
tr("Select Project Filename"),
getPath(SETTINGS_LAST_PROJECT_PATH),
filter);
if (filepath.isEmpty())
return;
if (!filepath.endsWith(".cppcheck", Qt::CaseInsensitive))
filepath += ".cppcheck";
setPath(SETTINGS_LAST_PROJECT_PATH, filepath);
QFileInfo inf(filepath);
const QString filename = inf.fileName();
formatAndSetTitle(tr("Project:") + QString(" ") + filename);
delete mProjectFile;
mProjectFile = new ProjectFile(this);
mProjectFile->setActiveProject();
mProjectFile->setFilename(filepath);
mProjectFile->setProjectName(filename.left(filename.indexOf(".")));
mProjectFile->setBuildDir(filename.left(filename.indexOf(".")) + "-cppcheck-build-dir");
ProjectFileDialog dlg(mProjectFile, isCppcheckPremium(), this);
if (dlg.exec() == QDialog::Accepted) {
addProjectMRU(filepath);
analyzeProject(mProjectFile, QStringList());
} else {
closeProjectFile();
}
}
void MainWindow::closeProjectFile()
{
delete mProjectFile;
mProjectFile = nullptr;
mUI->mResults->clear(true);
enableProjectActions(false);
enableProjectOpenActions(true);
formatAndSetTitle();
}
void MainWindow::editProjectFile()
{
if (!mProjectFile) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("No project file loaded"),
QMessageBox::Ok,
this);
msg.exec();
return;
}
ProjectFileDialog dlg(mProjectFile, isCppcheckPremium(), this);
if (dlg.exec() == QDialog::Accepted) {
mProjectFile->write();
analyzeProject(mProjectFile, QStringList());
}
}
void MainWindow::showStatistics()
{
StatsDialog statsDialog(this);
// Show a dialog with the previous scan statistics and project information
statsDialog.setProject(mProjectFile);
statsDialog.setPathSelected(mCurrentDirectory);
statsDialog.setNumberOfFilesScanned(mThread->getPreviousFilesCount());
statsDialog.setScanDuration(mThread->getPreviousScanDuration() / 1000.0);
statsDialog.setStatistics(mUI->mResults->getStatistics());
statsDialog.exec();
}
void MainWindow::showLibraryEditor()
{
LibraryDialog libraryDialog(this);
libraryDialog.exec();
}
void MainWindow::filterResults()
{
mUI->mResults->filterResults(mLineEditFilter->text());
}
void MainWindow::enableProjectActions(bool enable)
{
mUI->mActionCloseProjectFile->setEnabled(enable);
mUI->mActionEditProjectFile->setEnabled(enable);
mUI->mActionCheckLibrary->setEnabled(enable);
mUI->mActionCheckConfiguration->setEnabled(enable);
}
void MainWindow::enableProjectOpenActions(bool enable)
{
mUI->mActionNewProjectFile->setEnabled(enable);
mUI->mActionOpenProjectFile->setEnabled(enable);
}
void MainWindow::openRecentProject()
{
auto *action = qobject_cast<QAction *>(sender());
if (!action)
return;
const QString project = action->data().toString();
QFileInfo inf(project);
if (inf.exists()) {
if (inf.suffix() == "xml")
loadResults(project);
else {
loadProjectFile(project);
loadLastResults();
}
} else {
const QString text(tr("The project file\n\n%1\n\n could not be found!\n\n"
"Do you want to remove the file from the recently "
"used projects -list?").arg(project));
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
text,
QMessageBox::Yes | QMessageBox::No,
this);
msg.setDefaultButton(QMessageBox::No);
const int rv = msg.exec();
if (rv == QMessageBox::Yes) {
removeProjectMRU(project);
}
}
}
void MainWindow::updateMRUMenuItems()
{
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
mUI->mMenuFile->removeAction(recentProjectAct);
}
QStringList projects = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
// Do a sanity check - remove duplicates and non-existing projects
int removed = projects.removeDuplicates();
for (int i = projects.size() - 1; i >= 0; i--) {
if (!QFileInfo::exists(projects[i])) {
projects.removeAt(i);
removed++;
}
}
if (removed)
mSettings->setValue(SETTINGS_MRU_PROJECTS, projects);
const int numRecentProjects = qMin(projects.size(), (int)MaxRecentProjects);
for (int i = 0; i < numRecentProjects; i++) {
const QString filename = QFileInfo(projects[i]).fileName();
const QString text = QString("&%1 %2").arg(i + 1).arg(filename);
mRecentProjectActs[i]->setText(text);
mRecentProjectActs[i]->setData(projects[i]);
mRecentProjectActs[i]->setVisible(true);
mUI->mMenuFile->insertAction(mUI->mActionProjectMRU, mRecentProjectActs[i]);
}
if (numRecentProjects > 1)
mRecentProjectActs[numRecentProjects] = mUI->mMenuFile->insertSeparator(mUI->mActionProjectMRU);
}
void MainWindow::addProjectMRU(const QString &project)
{
QStringList files = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
files.removeAll(project);
files.prepend(project);
while (files.size() > MaxRecentProjects)
files.removeLast();
mSettings->setValue(SETTINGS_MRU_PROJECTS, files);
updateMRUMenuItems();
}
void MainWindow::removeProjectMRU(const QString &project)
{
QStringList files = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
files.removeAll(project);
mSettings->setValue(SETTINGS_MRU_PROJECTS, files);
updateMRUMenuItems();
}
void MainWindow::selectPlatform()
{
auto *action = qobject_cast<QAction *>(sender());
if (action) {
const Platform::Type platform = (Platform::Type) action->data().toInt();
mSettings->setValue(SETTINGS_CHECKED_PLATFORM, platform);
}
}
void MainWindow::suppressIds(QStringList ids)
{
if (!mProjectFile)
return;
ids.removeDuplicates();
QList<SuppressionList::Suppression> suppressions = mProjectFile->getSuppressions();
for (const QString& id : ids) {
// Remove all matching suppressions
std::string id2 = id.toStdString();
for (int i = 0; i < suppressions.size();) {
if (suppressions[i].errorId == id2)
suppressions.removeAt(i);
else
++i;
}
SuppressionList::Suppression newSuppression;
newSuppression.errorId = id2;
suppressions << newSuppression;
}
mProjectFile->setSuppressions(suppressions);
mProjectFile->write();
}
static int getVersion(const QString& nameWithVersion) {
int ret = 0;
int v = 0;
int dot = 0;
for (const auto c: nameWithVersion) {
if (c == '\n' || c == '\r')
break;
if (c == ' ') {
if (ret > 0 && dot == 1 && nameWithVersion.endsWith(" dev"))
return (ret * 1000000) + (v * 1000) + 500;
dot = ret = v = 0;
}
else if (c == '.') {
++dot;
ret = ret * 1000 + v;
v = 0;
} else if (c >= '0' && c <= '9')
v = v * 10 + (c.toLatin1() - '0');
}
ret = ret * 1000 + v;
while (dot < 2) {
++dot;
ret *= 1000;
}
return ret;
}
void MainWindow::replyFinished(QNetworkReply *reply) {
reply->deleteLater();
if (reply->error()) {
mUI->mLayoutInformation->deleteLater();
qDebug() << "Response: ERROR";
return;
}
const QString str = reply->readAll();
qDebug() << "Response: " << str;
if (reply->url().fileName() == "version.txt") {
QString nameWithVersion = QString("Cppcheck %1").arg(CppCheck::version());
if (!mCppcheckCfgProductName.isEmpty())
nameWithVersion = mCppcheckCfgProductName;
const int appVersion = getVersion(nameWithVersion);
const int latestVersion = getVersion(str.trimmed());
if (appVersion < latestVersion) {
if (mSettings->value(SETTINGS_CHECK_VERSION, 0).toInt() != latestVersion) {
QString install;
if (isCppcheckPremium()) {
#ifdef Q_OS_WIN
const QString url("https://cppchecksolutions.com/cppcheck-premium-installation");
#else
const QString url("https://cppchecksolutions.com/cppcheck-premium-linux-installation");
#endif
install = "<a href=\"" + url + "\">" + tr("Install") + "</a>";
}
mUI->mButtonHideInformation->setVisible(true);
mUI->mLabelInformation->setVisible(true);
mUI->mLabelInformation->setText(tr("New version available: %1. %2").arg(str.trimmed()).arg(install));
}
}
}
if (!mUI->mLabelInformation->isVisible()) {
mUI->mLayoutInformation->deleteLater();
}
}
void MainWindow::hideInformation() {
int version = getVersion(mUI->mLabelInformation->text());
mSettings->setValue(SETTINGS_CHECK_VERSION, version);
mUI->mLabelInformation->setVisible(false);
mUI->mButtonHideInformation->setVisible(false);
mUI->mLayoutInformation->deleteLater();
}
bool MainWindow::isCppcheckPremium() const {
return mCppcheckCfgProductName.startsWith("Cppcheck Premium ");
}
void MainWindow::changeReportType() {
const ReportType reportType = mUI->mActionReportAutosar->isChecked() ? ReportType::autosar :
mUI->mActionReportCertC->isChecked() ? ReportType::certC :
mUI->mActionReportCertCpp->isChecked() ? ReportType::certCpp :
mUI->mActionReportMisraC->isChecked() ? ReportType::misraC :
mUI->mActionReportMisraCpp2008->isChecked() ? ReportType::misraCpp2008 :
mUI->mActionReportMisraCpp2023->isChecked() ? ReportType::misraCpp2023 :
ReportType::normal;
mUI->mResults->setReportType(reportType);
auto setTextAndHint = [](QAction* a, const QString& s) {
a->setVisible(!s.isEmpty());
a->setText(s);
a->setToolTip(s);
};
const QString showMandatory = tr("Show Mandatory");
const QString showRequired = tr("Show Required");
const QString showAdvisory = tr("Show Advisory");
const QString showDocument = tr("Show Document");
if (mUI->mActionReportAutosar->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, "");
setTextAndHint(mUI->mActionShowWarnings, showRequired);
setTextAndHint(mUI->mActionShowStyle, showAdvisory);
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, "");
} else if (mUI->mActionReportMisraC->isChecked() || mUI->mActionReportMisraCpp2008->isChecked() || mUI->mActionReportMisraCpp2023->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, mUI->mActionReportMisraCpp2008->isChecked() ? "" : showMandatory);
setTextAndHint(mUI->mActionShowWarnings, showRequired);
setTextAndHint(mUI->mActionShowStyle, showAdvisory);
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, mUI->mActionReportMisraCpp2008->isChecked() ? showDocument : QString());
} else if (mUI->mActionReportCertC->isChecked() || mUI->mActionReportCertCpp->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, tr("Show L1"));
setTextAndHint(mUI->mActionShowWarnings, tr("Show L2"));
setTextAndHint(mUI->mActionShowStyle, tr("Show L3"));
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, "");
} else {
setTextAndHint(mUI->mActionShowErrors, tr("Show errors"));
setTextAndHint(mUI->mActionShowWarnings, tr("Show warnings"));
setTextAndHint(mUI->mActionShowStyle, tr("Show style"));
setTextAndHint(mUI->mActionShowPortability, tr("Show portability"));
setTextAndHint(mUI->mActionShowPerformance, tr("Show performance"));
setTextAndHint(mUI->mActionShowInformation, tr("Show information"));
}
}
| 90,083
|
C++
|
.cpp
| 2,027
| 36.379872
| 427
| 0.659993
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,343
|
compliancereportdialog.cpp
|
danmar_cppcheck/gui/compliancereportdialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "compliancereportdialog.h"
#include "ui_compliancereportdialog.h"
#include "errortypes.h"
#include "filelist.h"
#include "filesettings.h"
#include "importproject.h"
#include "projectfile.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <string>
#include <utility>
#include <vector>
#include <QByteArray>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDialogButtonBox>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QIODevice>
#include <QLineEdit>
#include <QList>
#include <QMessageBox>
#include <QProcess>
#include <QRegularExpression>
#include <QSet>
#include <QStringList>
#include <QTemporaryFile>
#include <QTextStream>
static void addHeaders(const QString& file1, QSet<QString> &allFiles) {
if (allFiles.contains(file1))
return;
QFile file(file1);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
allFiles << file1;
const QRegularExpression re("^#include[ ]*\"([^\">]+)\".*");
QTextStream in(&file);
QString line = in.readLine();
while (!in.atEnd()) {
if (line.startsWith("#include")) {
const QRegularExpressionMatch match = re.match(line);
if (match.hasMatch()) {
QString hfile = match.captured(1);
if (file1.contains("/"))
hfile = file1.mid(0,file1.lastIndexOf("/") + 1) + hfile;
addHeaders(hfile, allFiles);
}
}
line = in.readLine();
}
}
static std::vector<std::string> toStdStringList(const QStringList& from) {
std::vector<std::string> ret;
std::transform(from.cbegin(), from.cend(), std::back_inserter(ret), [](const QString& e) {
return e.toStdString();
});
return ret;
}
ComplianceReportDialog::ComplianceReportDialog(ProjectFile* projectFile, QString resultsFile, QString checkersReport)
: QDialog(nullptr),
mUI(new Ui::ComplianceReportDialog),
mProjectFile(projectFile),
mResultsFile(std::move(resultsFile)),
mCheckersReport(std::move(checkersReport))
{
mUI->setupUi(this);
mUI->mEditProjectName->setText(projectFile->getProjectName());
connect(mUI->buttonBox, &QDialogButtonBox::clicked, this, &ComplianceReportDialog::buttonClicked);
mUI->mCodingStandard->clear();
if (!projectFile->getCodingStandards().contains("misra-c-2023") && projectFile->getAddons().contains("misra"))
mUI->mCodingStandard->addItem("Misra C 2012");
for (QString std: projectFile->getCodingStandards()) {
std[0] = std[0].toUpper();
std = std.replace("-", " ").replace(" c ", " C ").replace(" cpp ", " C++ ").replace(" c++ ", " C++ ");
mUI->mCodingStandard->addItem(std);
}
}
ComplianceReportDialog::~ComplianceReportDialog()
{
delete mUI;
}
void ComplianceReportDialog::buttonClicked(QAbstractButton* button)
{
switch (mUI->buttonBox->standardButton(button)) {
case QDialogButtonBox::StandardButton::Save:
save();
break;
case QDialogButtonBox::StandardButton::Close:
close();
break;
default:
break;
};
}
void ComplianceReportDialog::save()
{
const QString std(mUI->mCodingStandard->currentText().toLower().replace(" ", "-"));
const QString outFile = QFileDialog::getSaveFileName(this,
tr("Compliance report"),
QDir::homePath() + "/" + std + "-compliance-report.html",
tr("HTML files (*.html)"));
if (outFile.isEmpty())
return;
close();
const QString& projectName = mUI->mEditProjectName->text();
const QString& projectVersion = mUI->mEditProjectVersion->text();
const bool files = mUI->mCheckFiles->isChecked();
if (projectName != mProjectFile->getProjectName()) {
mProjectFile->setProjectName(projectName);
mProjectFile->write();
}
QTemporaryFile tempCheckersReport;
if (tempCheckersReport.open()) {
QTextStream out(&tempCheckersReport);
out << mCheckersReport << "\n";
tempCheckersReport.close();
}
QTemporaryFile tempFiles;
if (files && tempFiles.open()) {
QTextStream out(&tempFiles);
FileList fileList;
fileList.addPathList(mProjectFile->getCheckPaths());
if (!mProjectFile->getImportProject().isEmpty()) {
QFileInfo inf(mProjectFile->getFilename());
QString prjfile;
if (QFileInfo(mProjectFile->getImportProject()).isAbsolute())
prjfile = mProjectFile->getImportProject();
else
prjfile = inf.canonicalPath() + '/' + mProjectFile->getImportProject();
ImportProject p;
try {
p.import(prjfile.toStdString());
} catch (InternalError &e) {
QMessageBox msg(QMessageBox::Critical,
tr("Save compliance report"),
tr("Failed to import '%1' (%2), can not show files in compliance report").arg(prjfile).arg(QString::fromStdString(e.errorMessage)),
QMessageBox::Ok,
this);
msg.exec();
return;
}
p.ignorePaths(toStdStringList(mProjectFile->getExcludedPaths()));
QDir dir(inf.absoluteDir());
for (const FileSettings& fs: p.fileSettings)
fileList.addFile(dir.relativeFilePath(QString::fromStdString(fs.filename())));
}
QSet<QString> allFiles;
for (const QString &sourcefile: fileList.getFileList())
addHeaders(sourcefile, allFiles);
for (const QString& fileName: allFiles) {
QFile f(fileName);
if (f.open(QFile::ReadOnly)) {
QCryptographicHash hash(QCryptographicHash::Algorithm::Md5);
if (hash.addData(&f)) {
for (auto b: hash.result())
out << QString::number((unsigned char)b,16);
out << " " << fileName << "\n";
}
}
}
tempFiles.close();
}
QStringList suppressions;
for (const auto& suppression: mProjectFile->getSuppressions()) {
if (!suppression.errorId.empty())
suppressions.append(QString::fromStdString(suppression.errorId));
}
QStringList args{"--project-name=" + projectName,
"--project-version=" + projectVersion,
"--output-file=" + outFile,
"--checkers-report=" + tempCheckersReport.fileName()};
if (!suppressions.isEmpty())
args << "--suppressions=" + suppressions.join(",");
args << ("--" + std);
if (files)
args << "--files=" + tempFiles.fileName();
args << mResultsFile;
const QString appPath = QFileInfo(QCoreApplication::applicationFilePath()).canonicalPath();
QProcess process;
#ifdef Q_OS_WIN
process.start(appPath + "/compliance-report.exe", args);
#else
process.start(appPath + "/compliance-report", args);
#endif
process.waitForFinished();
const QString output = process.readAll();
if (!output.isEmpty()) {
QMessageBox msg(QMessageBox::Critical,
tr("Save compliance report"),
output,
QMessageBox::Ok,
this);
msg.exec();
}
}
| 8,366
|
C++
|
.cpp
| 217
| 30.373272
| 163
| 0.620367
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,345
|
csvreport.cpp
|
danmar_cppcheck/gui/csvreport.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "csvreport.h"
#include "erroritem.h"
#include "report.h"
#include <QDir>
#include <QFile>
#include <QList>
#include <QtGlobal>
CsvReport::CsvReport(const QString &filename) :
Report(filename)
{}
bool CsvReport::create()
{
if (Report::create()) {
mTxtWriter.setDevice(Report::getFile());
return true;
}
return false;
}
void CsvReport::writeHeader()
{
// Added 5 columns to the header.
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << "File, Line, Severity, Id, Summary" << Qt::endl;
#else
mTxtWriter << "File, Line, Severity, Id, Summary" << endl;
#endif
}
void CsvReport::writeFooter()
{
// No footer for CSV report
}
void CsvReport::writeError(const ErrorItem &error)
{
/*
Error as CSV line
gui/test.cpp,23,error,Mismatching allocation and deallocation: k
*/
const QString file = QDir::toNativeSeparators(error.errorPath.back().file);
QString line = QString("%1,%2,").arg(file).arg(error.errorPath.back().line);
line += QString("%1,%2,%3").arg(GuiSeverity::toString(error.severity)).arg(error.errorId).arg(error.summary);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << line << Qt::endl;
#else
mTxtWriter << line << endl;
#endif
}
| 2,016
|
C++
|
.cpp
| 63
| 29.15873
| 113
| 0.707305
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,346
|
librarydialog.cpp
|
danmar_cppcheck/gui/librarydialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "librarydialog.h"
#include "common.h"
#include "libraryaddfunctiondialog.h"
#include "libraryeditargdialog.h"
#include "path.h"
#include "utils.h"
#include "ui_librarydialog.h"
#include <QCheckBox>
#include <QComboBox>
#include <QFile>
#include <QFileDialog>
#include <QFlags>
#include <QIODevice>
#include <QLineEdit>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QRegularExpression>
#include <QTextStream>
#include <Qt>
class QWidget;
// TODO: get/compare functions from header
namespace {
class FunctionListItem : public QListWidgetItem {
public:
FunctionListItem(QListWidget *view,
CppcheckLibraryData::Function *function,
bool selected)
: QListWidgetItem(view), function(function) {
setText(function->name);
setFlags(flags() | Qt::ItemIsEditable);
setSelected(selected);
}
CppcheckLibraryData::Function *function;
};
}
LibraryDialog::LibraryDialog(QWidget *parent) :
QDialog(parent),
mUi(new Ui::LibraryDialog)
{
mUi->setupUi(this);
mUi->buttonSave->setEnabled(false);
mUi->buttonSaveAs->setEnabled(false);
mUi->sortFunctions->setEnabled(false);
mUi->filter->setEnabled(false);
mUi->addFunction->setEnabled(false);
//As no function selected, this disables function editing widgets
selectFunction();
}
LibraryDialog::~LibraryDialog()
{
delete mUi;
}
CppcheckLibraryData::Function *LibraryDialog::currentFunction()
{
QList<QListWidgetItem *> selitems = mUi->functions->selectedItems();
if (selitems.count() != 1)
return nullptr;
return dynamic_cast<FunctionListItem *>(selitems.first())->function;
}
void LibraryDialog::openCfg()
{
const QString datadir = getDataDir();
QString selectedFilter;
const QString filter(tr("Library files (*.cfg)"));
const QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Open library file"),
datadir,
filter,
&selectedFilter);
if (selectedFile.isEmpty())
return;
QFile file(selectedFile);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Cannot open file %1.").arg(selectedFile),
QMessageBox::Ok,
this);
msg.exec();
return;
}
CppcheckLibraryData tempdata;
const QString errmsg = tempdata.open(file);
if (!errmsg.isNull()) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Failed to load %1. %2.").arg(selectedFile).arg(errmsg),
QMessageBox::Ok,
this);
msg.exec();
return;
}
mIgnoreChanges = true;
mData.swap(tempdata);
mFileName = selectedFile;
mUi->buttonSave->setEnabled(false);
mUi->buttonSaveAs->setEnabled(true);
mUi->filter->clear();
mUi->functions->clear();
for (CppcheckLibraryData::Function &function : mData.functions) {
mUi->functions->addItem(new FunctionListItem(mUi->functions,
&function,
false));
}
mUi->sortFunctions->setEnabled(!mData.functions.empty());
mUi->filter->setEnabled(!mData.functions.empty());
mUi->addFunction->setEnabled(true);
mIgnoreChanges = false;
}
void LibraryDialog::saveCfg()
{
if (mFileName.isNull())
return;
QFile file(mFileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream ts(&file);
ts << mData.toString() << '\n';
mUi->buttonSave->setEnabled(false);
} else {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Cannot save file %1.").arg(mFileName),
QMessageBox::Ok,
this);
msg.exec();
}
}
void LibraryDialog::saveCfgAs()
{
const QString filter(tr("Library files (*.cfg)"));
const QString path = Path::getPathFromFilename(mFileName.toStdString()).c_str();
QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save the library as"),
path,
filter);
if (selectedFile.isEmpty())
return;
if (!selectedFile.endsWith(".cfg", Qt::CaseInsensitive))
selectedFile += ".cfg";
mFileName = selectedFile;
saveCfg();
}
void LibraryDialog::addFunction()
{
auto *d = new LibraryAddFunctionDialog;
if (d->exec() == QDialog::Accepted && !d->functionName().isEmpty()) {
CppcheckLibraryData::Function f;
f.name = d->functionName();
const int args = d->numberOfArguments();
for (int i = 1; i <= args; i++) {
CppcheckLibraryData::Function::Arg arg;
arg.nr = i;
f.args.append(arg);
}
mData.functions.append(f);
mUi->functions->addItem(new FunctionListItem(mUi->functions, &mData.functions.back(), false));
mUi->buttonSave->setEnabled(true);
mUi->sortFunctions->setEnabled(!mData.functions.empty());
mUi->filter->setEnabled(!mData.functions.empty());
}
delete d;
}
void LibraryDialog::editFunctionName(QListWidgetItem* item)
{
if (mIgnoreChanges)
return;
QString functionName = item->text();
CppcheckLibraryData::Function * const function = dynamic_cast<FunctionListItem*>(item)->function;
if (functionName != function->name) {
const QRegularExpressionMatch matchRes = QRegularExpression("^" NAMES "$").match(functionName);
if (matchRes.hasMatch()) {
function->name = functionName;
mUi->buttonSave->setEnabled(true);
} else {
mIgnoreChanges = true;
item->setText(function->name);
mIgnoreChanges = false;
}
}
}
void LibraryDialog::selectFunction()
{
const CppcheckLibraryData::Function * const function = currentFunction();
if (function == nullptr) {
mUi->comments->clear();
mUi->comments->setEnabled(false);
mUi->noreturn->setCurrentIndex(0);
mUi->noreturn->setEnabled(false);
mUi->useretval->setChecked(false);
mUi->useretval->setEnabled(false);
mUi->leakignore->setChecked(false);
mUi->leakignore->setEnabled(false);
mUi->arguments->clear();
mUi->arguments->setEnabled(false);
mUi->editArgButton->setEnabled(false);
return;
}
mIgnoreChanges = true;
mUi->comments->setPlainText(function->comments);
mUi->comments->setEnabled(true);
mUi->noreturn->setCurrentIndex(function->noreturn);
mUi->noreturn->setEnabled(true);
mUi->useretval->setChecked(function->useretval);
mUi->useretval->setEnabled(true);
mUi->leakignore->setChecked(function->leakignore);
mUi->leakignore->setEnabled(true);
updateArguments(*function);
mUi->arguments->setEnabled(true);
mUi->editArgButton->setEnabled(true);
mIgnoreChanges = false;
}
void LibraryDialog::sortFunctions(bool sort)
{
if (sort) {
mUi->functions->sortItems();
} else {
mIgnoreChanges = true;
const CppcheckLibraryData::Function* selfunction = currentFunction();
mUi->functions->clear();
for (CppcheckLibraryData::Function &function : mData.functions) {
mUi->functions->addItem(new FunctionListItem(mUi->functions,
&function,
selfunction == &function));
}
if (!mUi->filter->text().isEmpty())
filterFunctions(mUi->filter->text());
mIgnoreChanges = false;
}
}
void LibraryDialog::filterFunctions(const QString& filter)
{
QList<QListWidgetItem *> allItems = mUi->functions->findItems(QString(), Qt::MatchContains);
if (filter.isEmpty()) {
for (QListWidgetItem *item : allItems) {
item->setHidden(false);
}
} else {
for (QListWidgetItem *item : allItems) {
item->setHidden(!item->text().startsWith(filter));
}
}
}
void LibraryDialog::changeFunction()
{
if (mIgnoreChanges)
return;
CppcheckLibraryData::Function *function = currentFunction();
if (!function)
return;
function->comments = mUi->comments->toPlainText();
function->noreturn = (CppcheckLibraryData::Function::TrueFalseUnknown)mUi->noreturn->currentIndex();
function->useretval = mUi->useretval->isChecked();
function->leakignore = mUi->leakignore->isChecked();
mUi->buttonSave->setEnabled(true);
}
void LibraryDialog::editArg()
{
CppcheckLibraryData::Function *function = currentFunction();
if (!function)
return;
if (mUi->arguments->selectedItems().count() != 1)
return;
CppcheckLibraryData::Function::Arg &arg = function->args[mUi->arguments->row(mUi->arguments->selectedItems().first())];
LibraryEditArgDialog d(nullptr, arg);
if (d.exec() == QDialog::Accepted) {
const unsigned number = arg.nr;
arg = d.getArg();
arg.nr = number;
mUi->arguments->selectedItems().first()->setText(getArgText(arg));
}
mUi->buttonSave->setEnabled(true);
}
QString LibraryDialog::getArgText(const CppcheckLibraryData::Function::Arg &arg)
{
QString s("arg");
if (arg.nr != CppcheckLibraryData::Function::Arg::ANY)
s += QString::number(arg.nr);
s += "\n not bool: " + QString(bool_to_string(arg.notbool));
s += "\n not null: " + QString(bool_to_string(arg.notnull));
s += "\n not uninit: " + QString(bool_to_string(arg.notuninit));
s += "\n format string: " + QString(bool_to_string(arg.formatstr));
s += "\n strz: " + QString(bool_to_string(arg.strz));
s += "\n valid: " + (arg.valid.isEmpty() ? "any" : arg.valid);
for (const CppcheckLibraryData::Function::Arg::MinSize &minsize : arg.minsizes) {
s += "\n minsize: " + minsize.type + " " + minsize.arg + " " + minsize.arg2;
}
return s;
}
void LibraryDialog::updateArguments(const CppcheckLibraryData::Function &function)
{
mUi->arguments->clear();
for (const CppcheckLibraryData::Function::Arg &arg : function.args) {
mUi->arguments->addItem(getArgText(arg));
}
}
| 11,709
|
C++
|
.cpp
| 316
| 28.911392
| 123
| 0.617969
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,347
|
codeeditorstyle.cpp
|
danmar_cppcheck/gui/codeeditorstyle.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "codeeditorstyle.h"
#include <QSettings>
#include <QVariant>
CodeEditorStyle::CodeEditorStyle(
// cppcheck-suppress naming-varname - TODO: fix this
QColor CtrlFGColor, QColor CtrlBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor HiLiBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor LnNumFGColor, QColor LnNumBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor KeyWdFGColor, QFont::Weight KeyWdWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor ClsFGColor, QFont::Weight ClsWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor QteFGColor, QFont::Weight QteWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor CmtFGColor, QFont::Weight CmtWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor SymbFGColor, QColor SymbBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QFont::Weight SymbWeight) :
widgetFGColor(CtrlFGColor),
widgetBGColor(CtrlBGColor),
highlightBGColor(HiLiBGColor),
lineNumFGColor(LnNumFGColor),
lineNumBGColor(LnNumBGColor),
keywordColor(KeyWdFGColor),
keywordWeight(KeyWdWeight),
classColor(ClsFGColor),
classWeight(ClsWeight),
quoteColor(QteFGColor),
quoteWeight(QteWeight),
commentColor(CmtFGColor),
commentWeight(CmtWeight),
symbolFGColor(SymbFGColor),
symbolBGColor(SymbBGColor),
symbolWeight(SymbWeight)
{}
bool CodeEditorStyle::operator==(const CodeEditorStyle& rhs) const
{
if (mSystemTheme != rhs.mSystemTheme) return false;
if (widgetFGColor != rhs.widgetFGColor) return false;
if (widgetBGColor != rhs.widgetBGColor) return false;
if (highlightBGColor != rhs.highlightBGColor) return false;
if (lineNumFGColor != rhs.lineNumFGColor) return false;
if (lineNumBGColor != rhs.lineNumBGColor) return false;
if (keywordColor != rhs.keywordColor) return false;
if (keywordWeight != rhs.keywordWeight) return false;
if (classColor != rhs.classColor) return false;
if (classWeight != rhs.classWeight) return false;
if (quoteColor != rhs.quoteColor) return false;
if (quoteWeight != rhs.quoteWeight) return false;
if (commentColor != rhs.commentColor) return false;
if (commentWeight != rhs.commentWeight) return false;
if (symbolFGColor != rhs.symbolFGColor) return false;
if (symbolBGColor != rhs.symbolBGColor) return false;
if (symbolWeight != rhs.symbolWeight) return false;
return true;
}
bool CodeEditorStyle::operator!=(const CodeEditorStyle& rhs) const
{
return !(*this == rhs);
}
CodeEditorStyle CodeEditorStyle::getSystemTheme()
{
CodeEditorStyle theStyle(defaultStyleLight);
theStyle.mSystemTheme = true;
return theStyle;
}
CodeEditorStyle CodeEditorStyle::loadSettings(QSettings *settings)
{
CodeEditorStyle theStyle(CodeEditorStyle::getSystemTheme());
if (!settings)
return theStyle;
if (!settings->childGroups().contains(SETTINGS_STYLE_GROUP))
return theStyle;
// style section exists - load values
settings->beginGroup(SETTINGS_STYLE_GROUP);
QString type = settings->value(
SETTINGS_STYLE_TYPE,
QVariant(SETTINGS_STYLE_TYPE_LIGHT)
).toString();
if (type == SETTINGS_STYLE_TYPE_LIGHT) {
settings->endGroup();
return theStyle;
}
if (type == SETTINGS_STYLE_TYPE_DARK) {
theStyle = defaultStyleDark;
settings->endGroup();
return theStyle;
}
if (type == SETTINGS_STYLE_TYPE_CUSTOM) {
theStyle.widgetFGColor = settings->value(
SETTINGS_STYLE_WIDGETFG,
QVariant(defaultStyleLight.widgetFGColor)).value<QColor>();
theStyle.widgetBGColor = settings->value(
SETTINGS_STYLE_WIDGETBG,
QVariant(defaultStyleLight.widgetBGColor)).value<QColor>();
theStyle.highlightBGColor = settings->value(
SETTINGS_STYLE_HILIFG,
QVariant(defaultStyleLight.highlightBGColor)).value<QColor>();
theStyle.lineNumFGColor = settings->value(
SETTINGS_STYLE_LINENUMFG,
QVariant(defaultStyleLight.lineNumFGColor)).value<QColor>();
theStyle.lineNumBGColor = settings->value(
SETTINGS_STYLE_LINENUMBG,
QVariant(defaultStyleLight.lineNumBGColor)).value<QColor>();
theStyle.keywordColor = settings->value(
SETTINGS_STYLE_KEYWORDFG,
QVariant(defaultStyleLight.keywordColor)).value<QColor>();
QVariant defKeyWWt(static_cast<int>(defaultStyleLight.keywordWeight));
theStyle.keywordWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_KEYWORDWT, defKeyWWt).toInt());
theStyle.classColor = settings->value(
SETTINGS_STYLE_CLASSFG,
QVariant(defaultStyleLight.classColor)).value<QColor>();
QVariant defClsWt(static_cast<int>(defaultStyleLight.classWeight));
theStyle.classWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_CLASSWT, defClsWt).toInt());
theStyle.quoteColor = settings->value(
SETTINGS_STYLE_QUOTEFG,
QVariant(defaultStyleLight.quoteColor)).value<QColor>();
QVariant defQteWt(static_cast<int>(defaultStyleLight.quoteWeight));
theStyle.quoteWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_QUOTEWT, defQteWt).toInt());
theStyle.commentColor = settings->value(
SETTINGS_STYLE_COMMENTFG,
QVariant(defaultStyleLight.commentColor)).value<QColor>();
QVariant defCmtWt(static_cast<int>(defaultStyleLight.commentWeight));
theStyle.commentWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_COMMENTWT, defCmtWt).toInt());
theStyle.symbolFGColor = settings->value(
SETTINGS_STYLE_SYMBOLFG,
QVariant(defaultStyleLight.symbolFGColor)).value<QColor>();
theStyle.symbolBGColor = settings->value(
SETTINGS_STYLE_SYMBOLBG,
QVariant(defaultStyleLight.symbolBGColor)).value<QColor>();
QVariant defSymWt(static_cast<int>(defaultStyleLight.symbolWeight));
theStyle.symbolWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_SYMBOLWT, defSymWt).toInt());
}
settings->endGroup();
return theStyle;
}
void CodeEditorStyle::saveSettings(QSettings *settings,
const CodeEditorStyle& theStyle)
{
if (!settings)
return;
if (settings->childGroups().contains(SETTINGS_STYLE_GROUP)) {
settings->remove(SETTINGS_STYLE_GROUP);
if (theStyle.isSystemTheme())
return;
}
settings->beginGroup(SETTINGS_STYLE_GROUP);
const bool isDefaultLight = (defaultStyleLight == theStyle);
const bool isDefaultDark = (defaultStyleDark == theStyle);
if (isDefaultLight && !isDefaultDark) {
settings->setValue(SETTINGS_STYLE_TYPE,
SETTINGS_STYLE_TYPE_LIGHT);
} else if (!isDefaultLight && isDefaultDark) {
settings->setValue(SETTINGS_STYLE_TYPE,
SETTINGS_STYLE_TYPE_DARK);
} else {
settings->setValue(SETTINGS_STYLE_TYPE,
SETTINGS_STYLE_TYPE_CUSTOM);
settings->setValue(SETTINGS_STYLE_WIDGETFG,
QVariant(theStyle.widgetFGColor));
settings->setValue(SETTINGS_STYLE_WIDGETBG,
QVariant(theStyle.widgetBGColor));
settings->setValue(SETTINGS_STYLE_HILIFG,
QVariant(theStyle.highlightBGColor));
settings->setValue(SETTINGS_STYLE_LINENUMFG,
QVariant(theStyle.lineNumFGColor));
settings->setValue(SETTINGS_STYLE_LINENUMBG,
QVariant(theStyle.lineNumBGColor));
settings->setValue(SETTINGS_STYLE_KEYWORDFG,
QVariant(theStyle.keywordColor));
settings->setValue(SETTINGS_STYLE_KEYWORDWT,
QVariant(static_cast<int>(theStyle.keywordWeight)));
settings->setValue(SETTINGS_STYLE_CLASSFG,
QVariant(theStyle.classColor));
settings->setValue(SETTINGS_STYLE_CLASSWT,
QVariant(static_cast<int>(theStyle.classWeight)));
settings->setValue(SETTINGS_STYLE_QUOTEFG,
QVariant(theStyle.quoteColor));
settings->setValue(SETTINGS_STYLE_QUOTEWT,
QVariant(static_cast<int>(theStyle.quoteWeight)));
settings->setValue(SETTINGS_STYLE_COMMENTFG,
QVariant(theStyle.commentColor));
settings->setValue(SETTINGS_STYLE_COMMENTWT,
QVariant(static_cast<int>(theStyle.commentWeight)));
settings->setValue(SETTINGS_STYLE_SYMBOLFG,
QVariant(theStyle.symbolFGColor));
settings->setValue(SETTINGS_STYLE_SYMBOLBG,
QVariant(theStyle.symbolBGColor));
settings->setValue(SETTINGS_STYLE_SYMBOLWT,
QVariant(static_cast<int>(theStyle.symbolWeight)));
}
settings->endGroup();
}
| 10,082
|
C++
|
.cpp
| 219
| 37.456621
| 79
| 0.680439
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,348
|
xmlreportv2.cpp
|
danmar_cppcheck/gui/xmlreportv2.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xmlreportv2.h"
#include "cppcheck.h"
#include "erroritem.h"
#include "report.h"
#include "settings.h"
#include "xmlreport.h"
#include <utility>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QXmlStreamAttributes>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QStringRef>
#endif
static const QString ResultElementName = "results";
static const QString CppcheckElementName = "cppcheck";
static const QString ErrorElementName = "error";
static const QString ErrorsElementName = "errors";
static const QString LocationElementName = "location";
static const QString CWEAttribute = "cwe";
static const QString HashAttribute = "hash";
static const QString SinceDateAttribute = "sinceDate";
static const QString TagsAttribute = "tag";
static const QString FilenameAttribute = "file";
static const QString IncludedFromFilenameAttribute = "file0";
static const QString InconclusiveAttribute = "inconclusive";
static const QString RemarkAttribute = "remark";
static const QString InfoAttribute = "info";
static const QString LineAttribute = "line";
static const QString ColumnAttribute = "column";
static const QString IdAttribute = "id";
static const QString SeverityAttribute = "severity";
static const QString MsgAttribute = "msg";
static const QString VersionAttribute = "version";
static const QString ProductNameAttribute = "product-name";
static const QString VerboseAttribute = "verbose";
XmlReportV2::XmlReportV2(const QString &filename, QString productName) :
XmlReport(filename),
mProductName(std::move(productName)),
mXmlReader(nullptr),
mXmlWriter(nullptr)
{}
XmlReportV2::~XmlReportV2()
{
delete mXmlReader;
delete mXmlWriter;
}
bool XmlReportV2::create()
{
if (Report::create()) {
mXmlWriter = new QXmlStreamWriter(Report::getFile());
return true;
}
return false;
}
bool XmlReportV2::open()
{
if (Report::open()) {
mXmlReader = new QXmlStreamReader(Report::getFile());
return true;
}
return false;
}
void XmlReportV2::writeHeader()
{
const auto nameAndVersion = Settings::getNameAndVersion(mProductName.toStdString());
const QString name = QString::fromStdString(nameAndVersion.first);
const QString version = nameAndVersion.first.empty() ? CppCheck::version() : QString::fromStdString(nameAndVersion.second);
mXmlWriter->setAutoFormatting(true);
mXmlWriter->writeStartDocument();
mXmlWriter->writeStartElement(ResultElementName);
mXmlWriter->writeAttribute(VersionAttribute, QString::number(2));
mXmlWriter->writeStartElement(CppcheckElementName);
if (!name.isEmpty())
mXmlWriter->writeAttribute(ProductNameAttribute, name);
mXmlWriter->writeAttribute(VersionAttribute, version);
mXmlWriter->writeEndElement();
mXmlWriter->writeStartElement(ErrorsElementName);
}
void XmlReportV2::writeFooter()
{
mXmlWriter->writeEndElement(); // errors
mXmlWriter->writeEndElement(); // results
mXmlWriter->writeEndDocument();
}
void XmlReportV2::writeError(const ErrorItem &error)
{
/*
Error example from the core program in xml
<error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k"
verbose="Mismatching allocation and deallocation: k">
<location file="..\..\test\test.cxx" line="16"/>
<location file="..\..\test\test.cxx" line="32"/>
</error>
*/
mXmlWriter->writeStartElement(ErrorElementName);
mXmlWriter->writeAttribute(IdAttribute, error.errorId);
// Don't localize severity so we can read these files
mXmlWriter->writeAttribute(SeverityAttribute, GuiSeverity::toString(error.severity));
const QString summary = XmlReport::quoteMessage(error.summary);
mXmlWriter->writeAttribute(MsgAttribute, summary);
const QString message = XmlReport::quoteMessage(error.message);
mXmlWriter->writeAttribute(VerboseAttribute, message);
if (error.inconclusive)
mXmlWriter->writeAttribute(InconclusiveAttribute, "true");
if (!error.remark.isEmpty())
mXmlWriter->writeAttribute(RemarkAttribute, error.remark);
if (error.cwe > 0)
mXmlWriter->writeAttribute(CWEAttribute, QString::number(error.cwe));
if (error.hash > 0)
mXmlWriter->writeAttribute(HashAttribute, QString::number(error.hash));
if (!error.file0.isEmpty())
mXmlWriter->writeAttribute(IncludedFromFilenameAttribute, quoteMessage(error.file0));
if (!error.sinceDate.isEmpty())
mXmlWriter->writeAttribute(SinceDateAttribute, error.sinceDate);
if (!error.tags.isEmpty())
mXmlWriter->writeAttribute(TagsAttribute, error.tags);
for (int i = error.errorPath.count() - 1; i >= 0; i--) {
mXmlWriter->writeStartElement(LocationElementName);
QString file = QDir::toNativeSeparators(error.errorPath[i].file);
mXmlWriter->writeAttribute(FilenameAttribute, XmlReport::quoteMessage(file));
mXmlWriter->writeAttribute(LineAttribute, QString::number(error.errorPath[i].line));
if (error.errorPath[i].column > 0)
mXmlWriter->writeAttribute(ColumnAttribute, QString::number(error.errorPath[i].column));
if (error.errorPath.count() > 1)
mXmlWriter->writeAttribute(InfoAttribute, XmlReport::quoteMessage(error.errorPath[i].info));
mXmlWriter->writeEndElement();
}
mXmlWriter->writeEndElement();
}
QList<ErrorItem> XmlReportV2::read()
{
QList<ErrorItem> errors;
bool insideResults = false;
if (!mXmlReader) {
qDebug() << "You must Open() the file before reading it!";
return errors;
}
while (!mXmlReader->atEnd()) {
switch (mXmlReader->readNext()) {
case QXmlStreamReader::StartElement:
if (mXmlReader->name() == ResultElementName)
insideResults = true;
// Read error element from inside result element
if (insideResults && mXmlReader->name() == ErrorElementName) {
ErrorItem item = readError(mXmlReader);
errors.append(item);
}
break;
case QXmlStreamReader::EndElement:
if (mXmlReader->name() == ResultElementName)
insideResults = false;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
}
return errors;
}
ErrorItem XmlReportV2::readError(const QXmlStreamReader *reader)
{
/*
Error example from the core program in xml
<error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k"
verbose="Mismatching allocation and deallocation: k">
<location file="..\..\test\test.cxx" line="16"/>
<location file="..\..\test\test.cxx" line="32"/>
</error>
*/
ErrorItem item;
// Read error element from inside errors element
if (mXmlReader->name() == ErrorElementName) {
QXmlStreamAttributes attribs = reader->attributes();
item.errorId = attribs.value(QString(), IdAttribute).toString();
item.severity = GuiSeverity::fromString(attribs.value(QString(), SeverityAttribute).toString());
const QString summary = attribs.value(QString(), MsgAttribute).toString();
item.summary = XmlReport::unquoteMessage(summary);
const QString message = attribs.value(QString(), VerboseAttribute).toString();
item.message = XmlReport::unquoteMessage(message);
if (attribs.hasAttribute(QString(), InconclusiveAttribute))
item.inconclusive = true;
if (attribs.hasAttribute(QString(), RemarkAttribute))
item.remark = attribs.value(QString(), RemarkAttribute).toString();
if (attribs.hasAttribute(QString(), CWEAttribute))
item.cwe = attribs.value(QString(), CWEAttribute).toInt();
if (attribs.hasAttribute(QString(), HashAttribute))
item.hash = attribs.value(QString(), HashAttribute).toULongLong();
if (attribs.hasAttribute(QString(), IncludedFromFilenameAttribute))
item.file0 = attribs.value(QString(), IncludedFromFilenameAttribute).toString();
if (attribs.hasAttribute(QString(), SinceDateAttribute))
item.sinceDate = attribs.value(QString(), SinceDateAttribute).toString();
if (attribs.hasAttribute(QString(), TagsAttribute))
item.tags = attribs.value(QString(), TagsAttribute).toString();
}
bool errorRead = false;
while (!errorRead && !mXmlReader->atEnd()) {
switch (mXmlReader->readNext()) {
case QXmlStreamReader::StartElement:
// Read location element from inside error element
if (mXmlReader->name() == LocationElementName) {
QXmlStreamAttributes attribs = mXmlReader->attributes();
QString file0 = attribs.value(QString(), IncludedFromFilenameAttribute).toString();
if (!file0.isEmpty())
item.file0 = XmlReport::unquoteMessage(file0);
QErrorPathItem loc;
loc.file = XmlReport::unquoteMessage(attribs.value(QString(), FilenameAttribute).toString());
loc.line = attribs.value(QString(), LineAttribute).toString().toUInt();
if (attribs.hasAttribute(QString(), ColumnAttribute))
loc.column = attribs.value(QString(), ColumnAttribute).toString().toInt();
if (attribs.hasAttribute(QString(), InfoAttribute))
loc.info = XmlReport::unquoteMessage(attribs.value(QString(), InfoAttribute).toString());
item.errorPath.push_front(loc);
}
break;
case QXmlStreamReader::EndElement:
if (mXmlReader->name() == ErrorElementName)
errorRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
}
if (item.errorPath.size() == 1 && item.errorPath[0].info.isEmpty())
item.errorPath[0].info = item.message;
return item;
}
| 11,599
|
C++
|
.cpp
| 263
| 37.425856
| 127
| 0.697425
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,350
|
libraryaddfunctiondialog.cpp
|
danmar_cppcheck/gui/libraryaddfunctiondialog.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libraryaddfunctiondialog.h"
#include "ui_libraryaddfunctiondialog.h"
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QSpinBox>
class QWidget;
LibraryAddFunctionDialog::LibraryAddFunctionDialog(QWidget *parent) :
QDialog(parent),
mUi(new Ui::LibraryAddFunctionDialog)
{
mUi->setupUi(this);
static const QRegularExpression rx(NAMES);
QValidator *validator = new QRegularExpressionValidator(rx, this);
mUi->functionName->setValidator(validator);
}
LibraryAddFunctionDialog::~LibraryAddFunctionDialog()
{
delete mUi;
}
QString LibraryAddFunctionDialog::functionName() const
{
return mUi->functionName->text();
}
int LibraryAddFunctionDialog::numberOfArguments() const
{
return mUi->numberOfArguments->value();
}
| 1,565
|
C++
|
.cpp
| 45
| 32.422222
| 72
| 0.778954
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,351
|
applicationlist.cpp
|
danmar_cppcheck/gui/applicationlist.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "applicationlist.h"
#include "application.h"
#include "common.h"
#include <QFileInfo>
#include <QSettings>
#include <QStringList>
#include <QVariant>
ApplicationList::ApplicationList(QObject *parent) :
QObject(parent)
{
//ctor
}
ApplicationList::~ApplicationList()
{
clear();
}
bool ApplicationList::loadSettings()
{
QSettings settings;
QStringList names = settings.value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList();
QStringList paths = settings.value(SETTINGS_APPLICATION_PATHS, QStringList()).toStringList();
QStringList params = settings.value(SETTINGS_APPLICATION_PARAMS, QStringList()).toStringList();
int defapp = settings.value(SETTINGS_APPLICATION_DEFAULT, -1).toInt();
// Params will be empty first time starting with the new setting.
// Return false and inform user about problem with application settings.
bool succeeded = true;
if (!names.empty() && !paths.empty() && params.empty()) {
for (int i = 0; i < paths.length(); i++)
params << QString();
succeeded = false;
}
if (names.empty() && paths.empty() && params.empty()) {
#ifndef _WIN32
// use as default for gnome environments
if (QFileInfo("/usr/bin/gedit").isExecutable()) {
Application app;
app.setName("gedit");
app.setPath("/usr/bin/gedit");
app.setParameters("+(line) (file)");
addApplication(app);
defapp = 0;
}
checkAndAddApplication("/usr/bin/geany","geany","+(line) (file)");
checkAndAddApplication("/usr/bin/qtcreator","Qt Creator","-client (file):(line)");
// use as default for kde environments
if (QFileInfo("/usr/bin/kate").isExecutable()) {
Application app;
app.setName("kate");
app.setPath("/usr/bin/kate");
app.setParameters("-l(line) (file)");
addApplication(app);
defapp = 0;
}
#else
if (findDefaultWindowsEditor()) {
defapp = 0;
}
#endif
} else if (names.size() == paths.size()) {
for (int i = 0; i < names.size(); i++) {
const Application app(names[i], paths[i], params[i]);
addApplication(app);
}
}
if (defapp == -1)
mDefaultApplicationIndex = 0;
else if (defapp < names.size())
mDefaultApplicationIndex = defapp;
else
mDefaultApplicationIndex = 0;
return succeeded;
}
void ApplicationList::saveSettings() const
{
QSettings settings;
QStringList names;
QStringList paths;
QStringList params;
for (int i = 0; i < getApplicationCount(); i++) {
const Application& app = getApplication(i);
names << app.getName();
paths << app.getPath();
params << app.getParameters();
}
settings.setValue(SETTINGS_APPLICATION_NAMES, names);
settings.setValue(SETTINGS_APPLICATION_PATHS, paths);
settings.setValue(SETTINGS_APPLICATION_PARAMS, params);
settings.setValue(SETTINGS_APPLICATION_DEFAULT, mDefaultApplicationIndex);
}
int ApplicationList::getApplicationCount() const
{
return mApplications.size();
}
Application& ApplicationList::getApplication(const int index)
{
if (index >= 0 && index < mApplications.size()) {
return mApplications[index];
}
static Application dummy; // TODO: Throw exception instead?
return dummy;
}
const Application& ApplicationList::getApplication(const int index) const
{
if (index >= 0 && index < mApplications.size()) {
return mApplications[index];
}
static const Application dummy; // TODO: Throw exception instead?
return dummy;
}
void ApplicationList::addApplication(const Application &app)
{
if (app.getName().isEmpty() || app.getPath().isEmpty()) {
return;
}
mApplications << app;
}
void ApplicationList::removeApplication(const int index)
{
mApplications.removeAt(index);
}
void ApplicationList::setDefault(const int index)
{
if (index < mApplications.size() && index >= 0) {
mDefaultApplicationIndex = index;
}
}
void ApplicationList::copy(const ApplicationList *list)
{
if (!list) {
return;
}
clear();
for (int i = 0; i < list->getApplicationCount(); i++) {
const Application& app = list->getApplication(i);
addApplication(app);
}
mDefaultApplicationIndex = list->getDefaultApplication();
}
void ApplicationList::clear()
{
mApplications.clear();
mDefaultApplicationIndex = -1;
}
bool ApplicationList::checkAndAddApplication(const QString& appPath, const QString& name, const QString& parameters)
{
if (QFileInfo::exists(appPath) && QFileInfo(appPath).isExecutable()) {
Application app;
app.setName(name);
app.setPath("\"" + appPath + "\"");
app.setParameters(parameters);
addApplication(app);
return true;
}
return false;
}
#ifdef _WIN32
bool ApplicationList::findDefaultWindowsEditor()
{
bool foundOne = false;
#ifdef WIN64 // As long as we do support 32-bit XP, we cannot be sure that the environment variable "ProgramFiles(x86)" exists
const QString appPathx86(getenv("ProgramFiles(x86)"));
#else
const QString appPathx86(getenv("ProgramFiles"));
#endif
const QString appPathx64(getenv("ProgramW6432"));
const QString windowsPath(getenv("windir"));
if (checkAndAddApplication(appPathx86 + "\\Notepad++\\notepad++.exe", "Notepad++", "-n(line) (file)"))
foundOne = true;
else if (checkAndAddApplication(appPathx64 + "\\Notepad++\\notepad++.exe", "Notepad++", "-n(line) (file)"))
foundOne = true;
if (checkAndAddApplication(appPathx86 + "\\Notepad2\\Notepad2.exe", "Notepad2", "/g (line) (file)"))
foundOne = true;
else if (checkAndAddApplication(appPathx64 + "\\Notepad2\\Notepad2.exe", "Notepad2", "/g (line) (file)"))
foundOne = true;
if (checkAndAddApplication(windowsPath + "\\system32\\notepad.exe", "Notepad", "(file)"))
foundOne = true;
QString regPath = "HKEY_CLASSES_ROOT\\Applications\\QtProject.QtCreator.pro\\shell\\Open\\command";
QSettings registry(regPath, QSettings::NativeFormat);
QString qtCreatorRegistry = registry.value("Default", QString()).toString();
QString qtCreatorPath = qtCreatorRegistry.left(qtCreatorRegistry.indexOf(".exe") + 4);
if (!qtCreatorRegistry.isEmpty() && checkAndAddApplication(qtCreatorPath, "Qt Creator", "-client (file):(line)")) {
foundOne = true;
}
const QString regPathUEdit32 = "HKEY_CLASSES_ROOT\\Applications\\Uedit32.exe\\shell\\open\\Command";
const QSettings registryUEdit32(regPathUEdit32, QSettings::NativeFormat);
const QString uedit32Registry = registryUEdit32.value("Default", QString()).toString();
if (!uedit32Registry.isEmpty()) {
// Extract path to executable and make sure there is no single quotation mark at the beginning
const QString uedit32Path = uedit32Registry.left(uedit32Registry.indexOf(".exe") + 4).replace("\"", "");
if (checkAndAddApplication(uedit32Path, "UltraEdit 32", "(file)/(line)")) {
foundOne = true;
}
}
const QString regPathUEdit64 = "HKEY_CLASSES_ROOT\\Applications\\uedit64.exe\\shell\\open\\Command";
const QSettings registryUEdit64(regPathUEdit64, QSettings::NativeFormat);
const QString uedit64Registry = registryUEdit64.value("Default", QString()).toString();
if (!uedit64Registry.isEmpty()) {
// Extract path to executable and make sure there is no single quotation mark at the beginning
const QString uedit64Path = uedit64Registry.left(uedit64Registry.indexOf(".exe") + 4).replace("\"", "");
if (checkAndAddApplication(uedit64Path, "UltraEdit 64", "(file)/(line)")) {
foundOne = true;
}
}
const QString regPathMSVSCode = "HKEY_CLASSES_ROOT\\Applications\\Code.exe\\shell\\open\\command";
const QSettings registryMSVSCode(regPathMSVSCode, QSettings::NativeFormat);
const QString msvscodeRegistry = registryMSVSCode.value("Default", QString()).toString();
if (!msvscodeRegistry.isEmpty()) {
const QString msvscodePath = msvscodeRegistry.left(msvscodeRegistry.indexOf(".exe") + 4).replace("\"", "");
if (checkAndAddApplication(msvscodePath, "Microsoft VS Code", "-g (file):(line)")) {
foundOne = true;
}
}
return foundOne;
}
#endif
| 9,235
|
C++
|
.cpp
| 232
| 34.331897
| 126
| 0.679563
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,353
|
codeeditor.cpp
|
danmar_cppcheck/gui/codeeditor.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "codeeditor.h"
#include "codeeditorstyle.h"
#include <QChar>
#include <QColor>
#include <QFont>
#include <QFontMetrics>
#include <QKeySequence>
#include <QLatin1Char>
#include <QList>
#include <QPainter>
#include <QPaintEvent>
#include <QRect>
#include <QRegularExpressionMatchIterator>
#include <QShortcut>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextEdit>
#include <QTextFormat>
class QTextDocument;
Highlighter::Highlighter(QTextDocument *parent,
CodeEditorStyle *widgetStyle) :
QSyntaxHighlighter(parent),
mWidgetStyle(widgetStyle)
{
HighlightingRule rule;
mKeywordFormat.setForeground(mWidgetStyle->keywordColor);
mKeywordFormat.setFontWeight(mWidgetStyle->keywordWeight);
QStringList keywordPatterns;
// TODO: use Keywords::getX()
keywordPatterns << "alignas"
<< "alignof"
<< "asm"
<< "auto"
<< "bool"
<< "break"
<< "case"
<< "catch"
<< "char"
<< "char8_t"
<< "char16_t"
<< "char32_t"
<< "class"
<< "concept"
<< "const"
<< "consteval"
<< "constexpr"
<< "constinit"
<< "const_cast"
<< "continue"
<< "co_await"
<< "co_return"
<< "co_yield"
<< "decltype"
<< "default"
<< "delete"
<< "do"
<< "double"
<< "dynamic_cast"
<< "else"
<< "enum"
<< "explicit"
<< "export"
<< "extern"
<< "false"
<< "final"
<< "float"
<< "for"
<< "friend"
<< "goto"
<< "if"
<< "import"
<< "inline"
<< "int"
<< "long"
<< "module"
<< "mutable"
<< "namespace"
<< "new"
<< "noexcept"
<< "nullptr"
<< "operator"
<< "override"
<< "private"
<< "protected"
<< "public"
<< "reinterpret_cast"
<< "requires"
<< "return"
<< "short"
<< "signed"
<< "static"
<< "static_assert"
<< "static_cast"
<< "struct"
<< "switch"
<< "template"
<< "this"
<< "thread_local"
<< "throw"
<< "true"
<< "try"
<< "typedef"
<< "typeid"
<< "typename"
<< "union"
<< "unsigned"
<< "virtual"
<< "void"
<< "volatile"
<< "wchar_t"
<< "while";
for (const QString &pattern : keywordPatterns) {
rule.pattern = QRegularExpression("\\b" + pattern + "\\b");
rule.format = mKeywordFormat;
rule.ruleRole = RuleRole::Keyword;
mHighlightingRules.append(rule);
}
mClassFormat.setForeground(mWidgetStyle->classColor);
mClassFormat.setFontWeight(mWidgetStyle->classWeight);
rule.pattern = QRegularExpression("\\bQ[A-Za-z]+\\b");
rule.format = mClassFormat;
rule.ruleRole = RuleRole::Class;
mHighlightingRules.append(rule);
mQuotationFormat.setForeground(mWidgetStyle->quoteColor);
mQuotationFormat.setFontWeight(mWidgetStyle->quoteWeight);
// We use lazy `*?` instead greed `*` quantifier to find the real end of the c-string.
// We use negative lookbehind assertion `(?<!\)` to ignore `\"` sequence in the c-string.
rule.pattern = QRegularExpression("\".*?(?<!\\\\)\"");
rule.format = mQuotationFormat;
rule.ruleRole = RuleRole::Quote;
mHighlightingRules.append(rule);
mSingleLineCommentFormat.setForeground(mWidgetStyle->commentColor);
mSingleLineCommentFormat.setFontWeight(mWidgetStyle->commentWeight);
rule.pattern = QRegularExpression("//[^\n]*");
rule.format = mSingleLineCommentFormat;
rule.ruleRole = RuleRole::Comment;
mHighlightingRules.append(rule);
mHighlightingRulesWithSymbols = mHighlightingRules;
mMultiLineCommentFormat.setForeground(mWidgetStyle->commentColor);
mMultiLineCommentFormat.setFontWeight(mWidgetStyle->commentWeight);
mSymbolFormat.setForeground(mWidgetStyle->symbolFGColor);
mSymbolFormat.setBackground(mWidgetStyle->symbolBGColor);
mSymbolFormat.setFontWeight(mWidgetStyle->symbolWeight);
// We use negative lookbehind assertion `(?<!/)`
// to ignore case: single line comment and line of asterisk
mCommentStartExpression = QRegularExpression("(?<!/)/\\*");
mCommentEndExpression = QRegularExpression("\\*/");
}
void Highlighter::setSymbols(const QStringList &symbols)
{
mHighlightingRulesWithSymbols = mHighlightingRules;
for (const QString &sym : symbols) {
HighlightingRule rule;
rule.pattern = QRegularExpression("\\b" + sym + "\\b");
rule.format = mSymbolFormat;
rule.ruleRole = RuleRole::Symbol;
mHighlightingRulesWithSymbols.append(rule);
}
}
void Highlighter::setStyle(const CodeEditorStyle &newStyle)
{
mKeywordFormat.setForeground(newStyle.keywordColor);
mKeywordFormat.setFontWeight(newStyle.keywordWeight);
mClassFormat.setForeground(newStyle.classColor);
mClassFormat.setFontWeight(newStyle.classWeight);
mSingleLineCommentFormat.setForeground(newStyle.commentColor);
mSingleLineCommentFormat.setFontWeight(newStyle.commentWeight);
mMultiLineCommentFormat.setForeground(newStyle.commentColor);
mMultiLineCommentFormat.setFontWeight(newStyle.commentWeight);
mQuotationFormat.setForeground(newStyle.quoteColor);
mQuotationFormat.setFontWeight(newStyle.quoteWeight);
mSymbolFormat.setForeground(newStyle.symbolFGColor);
mSymbolFormat.setBackground(newStyle.symbolBGColor);
mSymbolFormat.setFontWeight(newStyle.symbolWeight);
for (HighlightingRule& rule : mHighlightingRules) {
applyFormat(rule);
}
for (HighlightingRule& rule : mHighlightingRulesWithSymbols) {
applyFormat(rule);
}
}
void Highlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule &rule : mHighlightingRulesWithSymbols) {
QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
while (matchIterator.hasNext()) {
QRegularExpressionMatch match = matchIterator.next();
setFormat(match.capturedStart(), match.capturedLength(), rule.format);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(mCommentStartExpression);
while (startIndex >= 0) {
QRegularExpressionMatch match = mCommentEndExpression.match(text, startIndex);
const int endIndex = match.capturedStart();
int commentLength = 0;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ match.capturedLength();
}
setFormat(startIndex, commentLength, mMultiLineCommentFormat);
startIndex = text.indexOf(mCommentStartExpression, startIndex + commentLength);
}
}
void Highlighter::applyFormat(HighlightingRule &rule)
{
switch (rule.ruleRole) {
case RuleRole::Keyword:
rule.format = mKeywordFormat;
break;
case RuleRole::Class:
rule.format = mClassFormat;
break;
case RuleRole::Comment:
rule.format = mSingleLineCommentFormat;
break;
case RuleRole::Quote:
rule.format = mQuotationFormat;
break;
case RuleRole::Symbol:
rule.format = mSymbolFormat;
break;
}
}
CodeEditor::CodeEditor(QWidget *parent) :
QPlainTextEdit(parent),
mWidgetStyle(new CodeEditorStyle(defaultStyleLight))
{
mLineNumberArea = new LineNumberArea(this);
mHighlighter = new Highlighter(document(), mWidgetStyle);
mErrorPosition = -1;
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
setFont(font);
mLineNumberArea->setFont(font);
// set widget coloring by overriding widget style sheet
setObjectName("CodeEditor");
setStyleSheet(generateStyleString());
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
auto *copyText = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_C),this);
auto *allText = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_A),this);
#else
const auto *copyText = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_C),this);
const auto *allText = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_A),this);
#endif
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(copyText, SIGNAL(activated()), this, SLOT(copy()));
connect(allText, SIGNAL(activated()), this, SLOT(selectAll()));
updateLineNumberAreaWidth(0);
}
CodeEditor::~CodeEditor()
{
// NOTE: not a Qt Object - delete manually
delete mWidgetStyle;
}
static int getPos(const QString &fileData, int lineNumber)
{
if (lineNumber <= 1)
return 0;
for (int pos = 0, line = 1; pos < fileData.size(); ++pos) {
if (fileData[pos] != '\n')
continue;
++line;
if (line >= lineNumber)
return pos + 1;
}
return fileData.size();
}
void CodeEditor::setStyle(const CodeEditorStyle& newStyle)
{
*mWidgetStyle = newStyle;
// apply new styling
setStyleSheet(generateStyleString());
mHighlighter->setStyle(newStyle);
mHighlighter->rehighlight();
highlightErrorLine();
}
void CodeEditor::setError(const QString &code, int errorLine, const QStringList &symbols)
{
mHighlighter->setSymbols(symbols);
setPlainText(code);
mErrorPosition = getPos(code, errorLine);
QTextCursor tc = textCursor();
tc.setPosition(mErrorPosition);
setTextCursor(tc);
centerCursor();
highlightErrorLine();
}
void CodeEditor::setError(int errorLine, const QStringList &symbols)
{
mHighlighter->setSymbols(symbols);
mErrorPosition = getPos(toPlainText(), errorLine);
QTextCursor tc = textCursor();
tc.setPosition(mErrorPosition);
setTextCursor(tc);
centerCursor();
highlightErrorLine();
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
const int space = 3 + (fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits);
#else
const int space = 3 + (fontMetrics().width(QLatin1Char('9')) * digits);
#endif
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
mLineNumberArea->scroll(0, dy);
else
mLineNumberArea->update(0, rect.y(), mLineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *event)
{
QPlainTextEdit::resizeEvent(event);
QRect cr = contentsRect();
mLineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightErrorLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
QTextEdit::ExtraSelection selection;
selection.format.setBackground(mWidgetStyle->highlightBGColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = QTextCursor(document());
if (mErrorPosition >= 0) {
selection.cursor.setPosition(mErrorPosition);
} else {
selection.cursor.setPosition(0);
}
selection.cursor.clearSelection();
extraSelections.append(selection);
setExtraSelections(extraSelections);
}
void CodeEditor::lineNumberAreaPaintEvent(const QPaintEvent *event)
{
QPainter painter(mLineNumberArea);
painter.fillRect(event->rect(), mWidgetStyle->lineNumBGColor);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(mWidgetStyle->lineNumFGColor);
painter.drawText(0, top, mLineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
QString CodeEditor::generateStyleString()
{
QString bgcolor = QString("background:rgb(%1,%2,%3);")
.arg(mWidgetStyle->widgetBGColor.red())
.arg(mWidgetStyle->widgetBGColor.green())
.arg(mWidgetStyle->widgetBGColor.blue());
QString fgcolor = QString("color:rgb(%1,%2,%3);")
.arg(mWidgetStyle->widgetFGColor.red())
.arg(mWidgetStyle->widgetFGColor.green())
.arg(mWidgetStyle->widgetFGColor.blue());
QString style = QString("%1 %2")
.arg(bgcolor)
.arg(fgcolor);
return style;
}
| 15,224
|
C++
|
.cpp
| 407
| 28.791155
| 97
| 0.61887
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,354
|
erroritem.cpp
|
danmar_cppcheck/gui/erroritem.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "erroritem.h"
#include "common.h"
#include <list>
QErrorPathItem::QErrorPathItem(const ErrorMessage::FileLocation &loc)
: file(QString::fromStdString(loc.getfile(false)))
, line(loc.line)
, column(loc.column)
, info(QString::fromStdString(loc.getinfo()))
{}
bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2)
{
return i1.file == i2.file && i1.column == i2.column && i1.line == i2.line && i1.info == i2.info;
}
ErrorItem::ErrorItem()
: severity(Severity::none)
, inconclusive(false)
, cwe(-1)
, hash(0)
{}
ErrorItem::ErrorItem(const ErrorMessage &errmsg)
: file0(QString::fromStdString(errmsg.file0))
, errorId(QString::fromStdString(errmsg.id))
, severity(errmsg.severity)
, inconclusive(errmsg.certainty == Certainty::inconclusive)
, summary(QString::fromStdString(errmsg.shortMessage()))
, message(QString::fromStdString(errmsg.verboseMessage()))
, cwe(errmsg.cwe.id)
, hash(errmsg.hash)
, symbolNames(QString::fromStdString(errmsg.symbolNames()))
, remark(QString::fromStdString(errmsg.remark))
{
for (const auto& loc: errmsg.callStack)
errorPath << QErrorPathItem(loc);
}
QString ErrorItem::tool() const
{
if (errorId == CLANG_ANALYZER)
return CLANG_ANALYZER;
if (errorId.startsWith(CLANG_TIDY))
return CLANG_TIDY;
if (errorId.startsWith("clang-"))
return "clang";
return "cppcheck";
}
QString ErrorItem::toString() const
{
QString str = errorPath.back().file + " - " + errorId + " - ";
if (inconclusive)
str += "inconclusive ";
str += GuiSeverity::toString(severity) +"\n";
str += summary + "\n";
str += message + "\n";
for (const QErrorPathItem& i : errorPath) {
str += " " + i.file + ": " + QString::number(i.line) + "\n";
}
return str;
}
bool ErrorItem::sameCID(const ErrorItem &errorItem1, const ErrorItem &errorItem2)
{
if (errorItem1.hash || errorItem2.hash)
return errorItem1.hash == errorItem2.hash;
// fallback
return errorItem1.errorId == errorItem2.errorId &&
errorItem1.errorPath == errorItem2.errorPath &&
errorItem1.file0 == errorItem2.file0 &&
errorItem1.message == errorItem2.message &&
errorItem1.inconclusive == errorItem2.inconclusive &&
errorItem1.severity == errorItem2.severity;
}
| 3,147
|
C++
|
.cpp
| 86
| 32.360465
| 100
| 0.690492
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,356
|
threadresult.cpp
|
danmar_cppcheck/gui/threadresult.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "threadresult.h"
#include "common.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "importproject.h"
#include <numeric>
#include <QFile>
void ThreadResult::reportOut(const std::string &outmsg, Color /*c*/)
{
emit log(QString::fromStdString(outmsg));
}
void ThreadResult::fileChecked(const QString &file)
{
std::lock_guard<std::mutex> locker(mutex);
mProgress += QFile(file).size();
mFilesChecked++;
if (mMaxProgress > 0) {
const int value = static_cast<int>(PROGRESS_MAX * mProgress / mMaxProgress);
const QString description = tr("%1 of %2 files checked").arg(mFilesChecked).arg(mTotalFiles);
emit progress(value, description);
}
}
void ThreadResult::reportErr(const ErrorMessage &msg)
{
std::lock_guard<std::mutex> locker(mutex);
const ErrorItem item(msg);
if (msg.severity != Severity::debug)
emit error(item);
else
emit debugError(item);
}
QString ThreadResult::getNextFile()
{
std::lock_guard<std::mutex> locker(mutex);
if (mFiles.isEmpty()) {
return QString();
}
return mFiles.takeFirst();
}
void ThreadResult::getNextFileSettings(const FileSettings*& fs)
{
std::lock_guard<std::mutex> locker(mutex);
fs = nullptr;
if (mItNextFileSettings == mFileSettings.cend()) {
return;
}
fs = &(*mItNextFileSettings);
++mItNextFileSettings;
}
void ThreadResult::setFiles(const QStringList &files)
{
std::lock_guard<std::mutex> locker(mutex);
mFiles = files;
mProgress = 0;
mFilesChecked = 0;
mTotalFiles = files.size();
// Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate
quint64 sizeOfFiles = std::accumulate(files.begin(), files.end(), 0, [](quint64 total, const QString& file) {
return total + QFile(file).size();
});
mMaxProgress = sizeOfFiles;
}
void ThreadResult::setProject(const ImportProject &prj)
{
std::lock_guard<std::mutex> locker(mutex);
mFiles.clear();
mFileSettings = prj.fileSettings;
mItNextFileSettings = mFileSettings.cbegin();
mProgress = 0;
mFilesChecked = 0;
mTotalFiles = prj.fileSettings.size();
// Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate
mMaxProgress = std::accumulate(prj.fileSettings.begin(), prj.fileSettings.end(), quint64{ 0 }, [](quint64 v, const FileSettings& fs) {
return v + QFile(QString::fromStdString(fs.filename())).size();
});
}
void ThreadResult::clearFiles()
{
std::lock_guard<std::mutex> locker(mutex);
mFiles.clear();
mFileSettings.clear();
mItNextFileSettings = mFileSettings.cend();
mFilesChecked = 0;
mTotalFiles = 0;
}
int ThreadResult::getFileCount() const
{
std::lock_guard<std::mutex> locker(mutex);
return mFiles.size() + mFileSettings.size();
}
| 3,700
|
C++
|
.cpp
| 110
| 29.881818
| 138
| 0.705405
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,357
|
txtreport.cpp
|
danmar_cppcheck/gui/txtreport.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "txtreport.h"
#include "erroritem.h"
#include <QDir>
#include <QFile>
#include <QList>
#include <QtGlobal>
TxtReport::TxtReport(const QString &filename) :
Report(filename)
{}
bool TxtReport::create()
{
if (Report::create()) {
mTxtWriter.setDevice(Report::getFile());
return true;
}
return false;
}
void TxtReport::writeHeader()
{
// No header for txt report
}
void TxtReport::writeFooter()
{
// No footer for txt report
}
void TxtReport::writeError(const ErrorItem &error)
{
/*
Error example from the core program in text
[gui/test.cpp:23] -> [gui/test.cpp:14]: (error) Mismatching allocation and deallocation: k
*/
QString line;
for (int i = 0; i < error.errorPath.size(); i++) {
const QString file = QDir::toNativeSeparators(error.errorPath[i].file);
line += QString("[%1:%2]").arg(file).arg(error.errorPath[i].line);
if (i < error.errorPath.size() - 1) {
line += " -> ";
}
if (i == error.errorPath.size() - 1) {
line += ": ";
}
}
QString temp = "(%1";
if (error.inconclusive) {
temp += ", ";
temp += tr("inconclusive");
}
temp += ") ";
line += temp.arg(GuiSeverity::toString(error.severity));
line += error.summary;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << line << Qt::endl;
#else
mTxtWriter << line << endl;
#endif
}
| 2,207
|
C++
|
.cpp
| 73
| 26.178082
| 97
| 0.6541
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,360
|
testresultstree.cpp
|
danmar_cppcheck/gui/test/resultstree/testresultstree.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testresultstree.h"
#include "resultstree.h"
// headers that declare mocked functions/variables
#include "applicationlist.h"
#include "common.h"
#include "threadhandler.h"
#include "projectfile.h"
#include "xmlreportv2.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "path.h"
#include "settings.h"
#include <utility>
#include <QtTest>
class TestReport : public Report {
public:
explicit TestReport(QString format) : Report(QString()), format(std::move(format)) {}
void writeHeader() override {
output.clear();
}
void writeFooter() override {}
void writeError(const ErrorItem &error) override {
QString line = format;
line.replace("{id}", error.errorId);
line.replace("{classification}", error.classification);
line.replace("{guideline}", error.guideline);
output += (output.isEmpty() ? "" : "\n") + line;
}
QString format;
QString output;
};
// Mock GUI...
ProjectFile *ProjectFile::mActiveProject;
void ProjectFile::addSuppression(const SuppressionList::Suppression & /*unused*/) {}
QString ProjectFile::getWarningTags(std::size_t /*unused*/) const {
return QString();
}
void ProjectFile::setWarningTags(std::size_t /*unused*/, const QString& /*unused*/) {}
bool ProjectFile::write(const QString & /*unused*/) {
return true;
}
std::string severityToString(Severity severity) {
return std::to_string((int)severity);
}
int ApplicationList::getApplicationCount() const {
return 0;
}
bool ThreadHandler::isChecking() const {
return false;
}
Application& ApplicationList::getApplication(const int /*unused*/) {
throw 1;
}
const Application& ApplicationList::getApplication(const int index) const {
return mApplications.at(index);
}
QString getPath(const QString &type) {
return "/" + type;
}
void setPath(const QString & /*unused*/, const QString & /*unused*/) {}
QString XmlReport::quoteMessage(const QString &message) {
return message;
}
QString XmlReport::unquoteMessage(const QString &message) {
return message;
}
XmlReport::XmlReport(const QString& filename) : Report(filename) {}
// Mock LIB...
bool Path::isHeader(std::string const& /*unused*/) {
return false;
}
const std::set<std::string> ErrorLogger::mCriticalErrorIds;
std::string ErrorMessage::FileLocation::getfile(bool /*unused*/) const {
return std::string();
}
const char* CppCheck::version() {
return "1.0";
}
std::pair<std::string, std::string> Settings::getNameAndVersion(const std::string& /*unused*/) {
throw 1;
}
Severity severityFromString(const std::string& severity) {
return (Severity)std::stoi(severity);
}
// Test...
void TestResultsTree::test1() const
{
// #12772 : GUI: information messages are shown even though information tool button is deselected
ResultsTree tree(nullptr);
tree.showResults(ShowTypes::ShowType::ShowInformation, false);
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem();
errorItem.severity = Severity::information;
tree.addErrorItem(errorItem);
QCOMPARE(tree.isRowHidden(0,QModelIndex()), true); // Added item is hidden
tree.showResults(ShowTypes::ShowType::ShowInformation, true);
QCOMPARE(tree.isRowHidden(0,QModelIndex()), false); // Show item
}
void TestResultsTree::testReportType() const
{
TestReport report("{id},{classification},{guideline}");
int msgCount = 0;
auto createErrorItem = [&msgCount](const Severity severity, const QString& errorId) -> ErrorItem {
++msgCount;
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem(ErrorMessage::FileLocation("file1.c", msgCount, 1));
errorItem.severity = severity;
errorItem.errorId = errorId;
errorItem.summary = "test summary " + QString::number(msgCount);
return errorItem;
};
// normal report with 2 errors
ResultsTree tree(nullptr);
tree.updateSettings(false, false, false, false, false);
tree.addErrorItem(createErrorItem(Severity::style, "id1"));
tree.addErrorItem(createErrorItem(Severity::style, "unusedVariable")); // Misra C 2.8
tree.saveResults(&report);
QCOMPARE(report.output, "id1,,\nunusedVariable,,");
// switch to Misra C report and check that "id1" is not shown
tree.setReportType(ReportType::misraC);
tree.saveResults(&report);
QCOMPARE(report.output, "unusedVariable,Advisory,2.8");
// add "missingReturn" and check that it is added properly
tree.addErrorItem(createErrorItem(Severity::warning, "missingReturn")); // Misra C 17.4
tree.saveResults(&report);
QCOMPARE(report.output,
"unusedVariable,Advisory,2.8\n"
"missingReturn,Mandatory,17.4");
}
void TestResultsTree::testGetGuidelineError() const
{
TestReport report("{id},{classification},{guideline}");
int msgCount = 0;
auto createErrorItem = [&msgCount](const Severity severity, const QString& errorId) -> ErrorItem {
++msgCount;
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem(ErrorMessage::FileLocation("file1.c", msgCount, 1));
errorItem.severity = severity;
errorItem.errorId = errorId;
errorItem.summary = "test summary " + QString::number(msgCount);
return errorItem;
};
// normal report with 2 errors
ResultsTree tree(nullptr);
tree.setReportType(ReportType::misraC);
tree.addErrorItem(createErrorItem(Severity::error, "id1")); // error severity => guideline 1.3
tree.saveResults(&report);
QCOMPARE(report.output, "id1,Required,1.3");
}
QTEST_MAIN(TestResultsTree)
| 6,354
|
C++
|
.cpp
| 167
| 34.227545
| 102
| 0.719753
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,361
|
testprojectfile.cpp
|
danmar_cppcheck/gui/test/projectfile/testprojectfile.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testprojectfile.h"
#include "importproject.h"
#include "platform.h"
#include "projectfile.h"
#include "settings.h"
#include "suppressions.h"
#include <string>
#include <QFile>
#include <QIODevice>
#include <QList>
#include <QStringList>
#include <QTemporaryDir>
#include <QtTest>
// Mock...
const char Settings::SafeChecks::XmlRootName[] = "safe-checks";
const char Settings::SafeChecks::XmlClasses[] = "class-public";
const char Settings::SafeChecks::XmlExternalFunctions[] = "external-functions";
const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions";
const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables";
Settings::Settings() : maxCtuDepth(10) {}
Platform::Platform() = default;
Library::Library() = default;
Library::~Library() = default;
struct Library::LibraryData {};
bool ImportProject::sourceFileExists(const std::string & /*file*/) {
return true;
}
void TestProjectFile::loadInexisting() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/foo.cppcheck");
ProjectFile pfile(filepath);
QCOMPARE(pfile.read(), false);
}
void TestProjectFile::loadSimple() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString("../.."));
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
// Test that project file with old 'ignore' element works
void TestProjectFile::loadSimpleWithIgnore() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple_ignore.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString("../.."));
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
void TestProjectFile::loadSimpleNoroot() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple_noroot.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString());
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
void TestProjectFile::getAddonFilePath() const
{
QTemporaryDir tempdir;
QVERIFY(tempdir.isValid());
const QString filepath(tempdir.path() + "/addon.py");
QFile file(filepath);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.close();
// Relative path to addon
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), "addon"), filepath);
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), "not exist"), QString());
// Absolute path to addon
QCOMPARE(ProjectFile::getAddonFilePath("/not/exist", filepath), filepath);
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), filepath), filepath);
}
void TestProjectFile::getInlineSuppressionDefaultValue() const
{
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
QCOMPARE(projectFile.getInlineSuppression(), true);
}
void TestProjectFile::getInlineSuppression() const
{
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setInlineSuppression(false);
QCOMPARE(projectFile.getInlineSuppression(), false);
}
void TestProjectFile::getCheckingSuppressionsRelative() const
{
const SuppressionList::Suppression suppression("*", "externals/*");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "/some/path/externals/*");
}
void TestProjectFile::getCheckingSuppressionsAbsolute() const
{
const SuppressionList::Suppression suppression("*", "/some/path/1.h");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/other/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "/some/path/1.h");
}
void TestProjectFile::getCheckingSuppressionsStar() const
{
const SuppressionList::Suppression suppression("*", "*.cpp");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "*.cpp");
}
QTEST_MAIN(TestProjectFile)
| 6,889
|
C++
|
.cpp
| 170
| 37.076471
| 93
| 0.735781
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,362
|
testcppchecklibrarydata.cpp
|
danmar_cppcheck/gui/test/cppchecklibrarydata/testcppchecklibrarydata.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testcppchecklibrarydata.h"
#include <QDir>
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QList>
#include <QPair>
#include <QStringList>
#include <QTextStream>
#include <QtTest>
const QString TestCppcheckLibraryData::TempCfgFile = "./tmp.cfg";
void TestCppcheckLibraryData::init()
{
result.clear();
libraryData.clear();
fileLibraryData.clear();
}
void TestCppcheckLibraryData::xmlReaderError()
{
loadCfgFile(":/files/xml_reader_error.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::unhandledElement()
{
loadCfgFile(":/files/unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/platform_type_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/memory_resource_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/container_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/reflection_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/markup_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::mandatoryAttributeMissing()
{
loadCfgFile(":/files/mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/reflection_mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/markup_mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::podtypeValid()
{
// Load library data from file
loadCfgFile(":/files/podtype_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.podtypes.size(), 2);
QCOMPARE(libraryData.podtypes[0].name, QString("bool"));
QCOMPARE(libraryData.podtypes[0].stdtype.isEmpty(), true);
QCOMPARE(libraryData.podtypes[0].sign.isEmpty(), true);
QCOMPARE(libraryData.podtypes[0].size.isEmpty(), true);
QCOMPARE(libraryData.podtypes[1].name, QString("ulong"));
QCOMPARE(libraryData.podtypes[1].stdtype, QString("uint32_t"));
QCOMPARE(libraryData.podtypes[1].sign, QString("u"));
QCOMPARE(libraryData.podtypes[1].size, QString("4"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.podtypes.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.podtypes.size(), fileLibraryData.podtypes.size());
QCOMPARE(libraryData.podtypes.size(), 2);
for (int i=0; i < libraryData.podtypes.size(); i++) {
QCOMPARE(libraryData.podtypes[i].name, fileLibraryData.podtypes[i].name);
QCOMPARE(libraryData.podtypes[i].stdtype, fileLibraryData.podtypes[i].stdtype);
QCOMPARE(libraryData.podtypes[i].sign, fileLibraryData.podtypes[i].sign);
QCOMPARE(libraryData.podtypes[i].size, fileLibraryData.podtypes[i].size);
}
}
void TestCppcheckLibraryData::typechecksValid()
{
// Load library data from file
loadCfgFile(":/files/typechecks_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.typeChecks.size(), 3);
CppcheckLibraryData::TypeChecks check = libraryData.typeChecks[0];
QCOMPARE(check.size(), 2);
QCOMPARE(check[0].first, QString("suppress"));
QCOMPARE(check[0].second, QString("std::insert_iterator"));
QCOMPARE(check[1].first, QString("check"));
QCOMPARE(check[1].second, QString("std::pair"));
check = libraryData.typeChecks[1];
QCOMPARE(check.isEmpty(), true);
check = libraryData.typeChecks[2];
QCOMPARE(check.size(), 1);
QCOMPARE(check[0].first, QString("check"));
QCOMPARE(check[0].second, QString("std::tuple"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.typeChecks.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.typeChecks.size(), fileLibraryData.typeChecks.size());
QCOMPARE(libraryData.typeChecks.size(), 3);
for (int idx=0; idx < libraryData.typeChecks.size(); idx++) {
CppcheckLibraryData::TypeChecks lhs = libraryData.typeChecks[idx];
CppcheckLibraryData::TypeChecks rhs = fileLibraryData.typeChecks[idx];
QCOMPARE(lhs.size(), rhs.size());
QCOMPARE(lhs, rhs);
}
}
void TestCppcheckLibraryData::smartPointerValid()
{
// Load library data from file
loadCfgFile(":/files/smartptr_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.smartPointers.size(), 3);
QCOMPARE(libraryData.smartPointers[0].name, QString("wxObjectDataPtr"));
QCOMPARE(libraryData.smartPointers[0].unique, false);
QCOMPARE(libraryData.smartPointers[1].name, QString("wxScopedArray"));
QCOMPARE(libraryData.smartPointers[1].unique, true);
QCOMPARE(libraryData.smartPointers[2].name, QString("wxScopedPtr"));
QCOMPARE(libraryData.smartPointers[2].unique, false);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.smartPointers.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.smartPointers.size(), fileLibraryData.smartPointers.size());
QCOMPARE(libraryData.smartPointers.size(), 3);
for (int idx=0; idx < libraryData.smartPointers.size(); idx++) {
QCOMPARE(libraryData.smartPointers[idx].name, fileLibraryData.smartPointers[idx].name);
QCOMPARE(libraryData.smartPointers[idx].unique, fileLibraryData.smartPointers[idx].unique);
}
}
void TestCppcheckLibraryData::platformTypeValid()
{
// Load library data from file
loadCfgFile(":/files/platform_type_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.platformTypes.size(), 3);
QCOMPARE(libraryData.platformTypes[0].name, QString("platform"));
QCOMPARE(libraryData.platformTypes[0].value, QString("with attribute and empty"));
QCOMPARE(libraryData.platformTypes[0].types.size(), 0);
QCOMPARE(libraryData.platformTypes[0].platforms.size(), 2);
QCOMPARE(libraryData.platformTypes[0].platforms[0], QString("win64"));
QCOMPARE(libraryData.platformTypes[0].platforms[1].isEmpty(), true);
QCOMPARE(libraryData.platformTypes[1].name, QString("types"));
QCOMPARE(libraryData.platformTypes[1].value, QString("all"));
QCOMPARE(libraryData.platformTypes[1].types.size(), 5);
QCOMPARE(libraryData.platformTypes[1].types,
QStringList({"unsigned", "long", "pointer", "const_ptr", "ptr_ptr"}));
QCOMPARE(libraryData.platformTypes[1].platforms.isEmpty(), true);
QCOMPARE(libraryData.platformTypes[2].name, QString("types and platform"));
QCOMPARE(libraryData.platformTypes[2].value.isEmpty(), true);
QCOMPARE(libraryData.platformTypes[2].types.size(), 2);
QCOMPARE(libraryData.platformTypes[2].types, QStringList({"pointer", "ptr_ptr"}));
QCOMPARE(libraryData.platformTypes[2].platforms.size(), 1);
QCOMPARE(libraryData.platformTypes[2].platforms[0], QString("win32"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.platformTypes.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.platformTypes.size(), fileLibraryData.platformTypes.size());
QCOMPARE(libraryData.platformTypes.size(), 3);
for (int idx=0; idx < libraryData.platformTypes.size(); idx++) {
CppcheckLibraryData::PlatformType lhs = libraryData.platformTypes[idx];
CppcheckLibraryData::PlatformType rhs = fileLibraryData.platformTypes[idx];
QCOMPARE(lhs.name, rhs.name);
QCOMPARE(lhs.value, rhs.value);
QCOMPARE(lhs.types.size(), rhs.types.size());
QCOMPARE(lhs.types, rhs.types);
QCOMPARE(lhs.platforms.size(), rhs.platforms.size());
QCOMPARE(lhs.platforms, rhs.platforms);
}
}
void TestCppcheckLibraryData::memoryResourceValid()
{
// Load library data from file
loadCfgFile(":/files/memory_resource_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.memoryresource.size(), 2);
QCOMPARE(libraryData.memoryresource[0].type, QString("memory"));
QCOMPARE(libraryData.memoryresource[0].alloc.size(), 4);
QCOMPARE(libraryData.memoryresource[0].dealloc.size(), 1);
QCOMPARE(libraryData.memoryresource[0].use.size(), 0);
QCOMPARE(libraryData.memoryresource[0].alloc[0].name, QString("malloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[0].bufferSize, QString("malloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[0].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[0].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[0].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[0].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[1].name, QString("calloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[1].bufferSize, QString("calloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[1].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[1].init, true);
QCOMPARE(libraryData.memoryresource[0].alloc[1].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[1].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[2].name, QString("realloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[2].bufferSize, QString("malloc:2"));
QCOMPARE(libraryData.memoryresource[0].alloc[2].isRealloc, true);
QCOMPARE(libraryData.memoryresource[0].alloc[2].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[2].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[2].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[3].name, QString("UuidToString"));
QCOMPARE(libraryData.memoryresource[0].alloc[3].bufferSize.isEmpty(), true);
QCOMPARE(libraryData.memoryresource[0].alloc[3].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[3].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[3].arg, 2);
QCOMPARE(libraryData.memoryresource[0].alloc[3].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].dealloc[0].name, QString("HeapFree"));
QCOMPARE(libraryData.memoryresource[0].dealloc[0].arg, 3);
QCOMPARE(libraryData.memoryresource[1].type, QString("resource"));
QCOMPARE(libraryData.memoryresource[1].alloc.size(), 1);
QCOMPARE(libraryData.memoryresource[1].dealloc.size(), 1);
QCOMPARE(libraryData.memoryresource[1].use.size(), 0);
QCOMPARE(libraryData.memoryresource[1].alloc[0].name, QString("_wfopen_s"));
QCOMPARE(libraryData.memoryresource[1].alloc[0].bufferSize.isEmpty(), true);
QCOMPARE(libraryData.memoryresource[1].alloc[0].isRealloc, false);
QCOMPARE(libraryData.memoryresource[1].alloc[0].init, true);
QCOMPARE(libraryData.memoryresource[1].alloc[0].arg, 1);
QCOMPARE(libraryData.memoryresource[1].alloc[0].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[1].dealloc[0].name, QString("fclose"));
QCOMPARE(libraryData.memoryresource[1].dealloc[0].arg, -1);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.memoryresource.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.memoryresource.size(), fileLibraryData.memoryresource.size());
QCOMPARE(libraryData.memoryresource.size(), 2);
for (int idx=0; idx < libraryData.memoryresource.size(); idx++) {
CppcheckLibraryData::MemoryResource lhs = libraryData.memoryresource[idx];
CppcheckLibraryData::MemoryResource rhs = fileLibraryData.memoryresource[idx];
QCOMPARE(lhs.type, rhs.type);
QCOMPARE(lhs.alloc.size(), rhs.alloc.size());
QCOMPARE(lhs.dealloc.size(), rhs.dealloc.size());
QCOMPARE(lhs.use, rhs.use);
for (int num=0; num < lhs.alloc.size(); num++) {
QCOMPARE(lhs.alloc[num].name, rhs.alloc[num].name);
QCOMPARE(lhs.alloc[num].bufferSize, rhs.alloc[num].bufferSize);
QCOMPARE(lhs.alloc[num].isRealloc, rhs.alloc[num].isRealloc);
QCOMPARE(lhs.alloc[num].init, rhs.alloc[num].init);
QCOMPARE(lhs.alloc[num].arg, rhs.alloc[num].arg);
QCOMPARE(lhs.alloc[num].reallocArg, rhs.alloc[num].reallocArg);
}
for (int num=0; num < lhs.dealloc.size(); num++) {
QCOMPARE(lhs.dealloc[num].name, rhs.dealloc[num].name);
QCOMPARE(lhs.dealloc[num].arg, rhs.dealloc[num].arg);
}
}
}
void TestCppcheckLibraryData::defineValid()
{
// Load library data from file
loadCfgFile(":/files/define_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.defines.size(), 2);
QCOMPARE(libraryData.defines[0].name, QString("INT8_MIN"));
QCOMPARE(libraryData.defines[0].value, QString("-128"));
QCOMPARE(libraryData.defines[1].name.isEmpty(), true);
QCOMPARE(libraryData.defines[1].value.isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.defines.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.defines.size(), fileLibraryData.defines.size());
QCOMPARE(libraryData.defines.size(), 2);
for (int idx=0; idx < libraryData.defines.size(); idx++) {
QCOMPARE(libraryData.defines[idx].name, fileLibraryData.defines[idx].name);
QCOMPARE(libraryData.defines[idx].value, fileLibraryData.defines[idx].value);
}
}
void TestCppcheckLibraryData::undefineValid()
{
// Load library data from file
loadCfgFile(":/files/undefine_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.undefines.size(), 2);
QCOMPARE(libraryData.undefines[0], QString("INT8_MIN"));
QCOMPARE(libraryData.undefines[1].isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.undefines.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.undefines.size(), fileLibraryData.undefines.size());
QCOMPARE(libraryData.undefines.size(), 2);
QCOMPARE(libraryData.undefines, fileLibraryData.undefines);
}
void TestCppcheckLibraryData::reflectionValid()
{
// Load library data from file
loadCfgFile(":/files/reflection_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.reflections.size(), 2);
QCOMPARE(libraryData.reflections[0].calls.size(), 2);
QCOMPARE(libraryData.reflections[0].calls[0].arg, 2);
QCOMPARE(libraryData.reflections[0].calls[0].name, QString("invokeMethod"));
QCOMPARE(libraryData.reflections[0].calls[1].arg, 1);
QCOMPARE(libraryData.reflections[0].calls[1].name, QString("callFunction"));
QCOMPARE(libraryData.reflections[1].calls.isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.reflections.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.reflections.size(), fileLibraryData.reflections.size());
QCOMPARE(libraryData.reflections.size(), 2);
for (int idx=0; idx < libraryData.reflections.size(); idx++) {
CppcheckLibraryData::Reflection lhs = libraryData.reflections[idx];
CppcheckLibraryData::Reflection rhs = fileLibraryData.reflections[idx];
QCOMPARE(lhs.calls.size(), rhs.calls.size());
for (int num=0; num < lhs.calls.size(); num++) {
QCOMPARE(lhs.calls[num].arg, rhs.calls[num].arg);
QCOMPARE(lhs.calls[num].name, rhs.calls[num].name);
}
}
}
void TestCppcheckLibraryData::markupValid()
{
// Load library data from file
loadCfgFile(":/files/markup_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.markups.size(), 1);
QCOMPARE(libraryData.markups[0].ext, QString(".qml"));
QCOMPARE(libraryData.markups[0].reportErrors, false);
QCOMPARE(libraryData.markups[0].afterCode, true);
QCOMPARE(libraryData.markups[0].keywords.size(), 4);
QCOMPARE(libraryData.markups[0].keywords, QStringList({"if", "while", "typeof", "for"}));
QCOMPARE(libraryData.markups[0].importer.size(), 1);
QCOMPARE(libraryData.markups[0].importer, QStringList("connect"));
QCOMPARE(libraryData.markups[0].exporter.size(), 1);
QCOMPARE(libraryData.markups[0].exporter[0].prefix, QString("Q_PROPERTY"));
QCOMPARE(libraryData.markups[0].exporter[0].suffixList.size(), 1);
QCOMPARE(libraryData.markups[0].exporter[0].suffixList, QStringList("READ"));
QCOMPARE(libraryData.markups[0].exporter[0].prefixList.size(), 3);
QCOMPARE(libraryData.markups[0].exporter[0].prefixList, QStringList({"READ", "WRITE", "NOTIFY"}));
QCOMPARE(libraryData.markups[0].codeBlocks.size(), 2);
QCOMPARE(libraryData.markups[0].codeBlocks[0].blocks.size(), 5);
QCOMPARE(libraryData.markups[0].codeBlocks[0].blocks, QStringList({"onClicked", "onFinished", "onTriggered", "onPressed", "onTouch"}));
QCOMPARE(libraryData.markups[0].codeBlocks[0].offset, 3);
QCOMPARE(libraryData.markups[0].codeBlocks[0].start, QString("{"));
QCOMPARE(libraryData.markups[0].codeBlocks[0].end, QString("}"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].blocks.size(), 1);
QCOMPARE(libraryData.markups[0].codeBlocks[1].blocks, QStringList("function"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].offset, 2);
QCOMPARE(libraryData.markups[0].codeBlocks[1].start, QString("{"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].end, QString("}"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.markups.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.markups.size(), fileLibraryData.markups.size());
for (int idx=0; idx < libraryData.markups.size(); idx++) {
CppcheckLibraryData::Markup lhs = libraryData.markups[idx];
CppcheckLibraryData::Markup rhs = fileLibraryData.markups[idx];
QCOMPARE(lhs.ext, rhs.ext);
QCOMPARE(lhs.reportErrors, rhs.reportErrors);
QCOMPARE(lhs.afterCode, rhs.afterCode);
QCOMPARE(lhs.keywords, rhs.keywords);
QCOMPARE(lhs.importer, rhs.importer);
for (int num=0; num < lhs.exporter.size(); num++) {
QCOMPARE(lhs.exporter[num].prefix, rhs.exporter[num].prefix);
QCOMPARE(lhs.exporter[num].suffixList, rhs.exporter[num].suffixList);
QCOMPARE(lhs.exporter[num].prefixList, rhs.exporter[num].prefixList);
}
for (int num=0; num < lhs.codeBlocks.size(); num++) {
QCOMPARE(lhs.codeBlocks[num].blocks, rhs.codeBlocks[num].blocks);
QCOMPARE(lhs.codeBlocks[num].offset, rhs.codeBlocks[num].offset);
QCOMPARE(lhs.codeBlocks[num].start, rhs.codeBlocks[num].start);
QCOMPARE(lhs.codeBlocks[num].end, rhs.codeBlocks[num].end);
}
}
}
void TestCppcheckLibraryData::containerValid()
{
// Load library data from file
loadCfgFile(":/files/container_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.containers.size(), 1);
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList.size(), 2);
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[0].name, QString("first"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[0].templateParameter, QString("0"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[1].name, QString("second"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[1].templateParameter, QString("1"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.containers.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.containers.size(), fileLibraryData.containers.size());
for (int idx=0; idx < libraryData.containers.size(); idx++) {
CppcheckLibraryData::Container lhs = libraryData.containers[idx];
CppcheckLibraryData::Container rhs = fileLibraryData.containers[idx];
for (int num=0; num < lhs.rangeItemRecordTypeList.size(); num++) {
QCOMPARE(lhs.rangeItemRecordTypeList[num].name, rhs.rangeItemRecordTypeList[num].name);
QCOMPARE(lhs.rangeItemRecordTypeList[num].templateParameter, rhs.rangeItemRecordTypeList[num].templateParameter);
}
}
}
void TestCppcheckLibraryData::loadCfgFile(const QString &filename, CppcheckLibraryData &data, QString &res, bool removeFile)
{
QFile file(filename);
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
res = data.open(file);
file.close();
if (removeFile) {
file.remove();
}
}
void TestCppcheckLibraryData::saveCfgFile(const QString &filename, CppcheckLibraryData &data)
{
QFile file(filename);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream textStream(&file);
textStream << data.toString() << '\n';
file.close();
}
void TestCppcheckLibraryData::validateAllCfg()
{
const QDir dir(QString(SRCDIR) + "/../../../cfg/");
const QStringList files = dir.entryList(QStringList() << "*.cfg",QDir::Files);
QVERIFY(!files.empty());
bool error = false;
for (const QString& f : files) {
loadCfgFile(dir.absolutePath() + "/" + f, fileLibraryData, result);
if (!result.isNull()) {
error = true;
qDebug() << f << " - " << result;
}
}
QCOMPARE(error, false);
}
QTEST_MAIN(TestCppcheckLibraryData)
| 26,195
|
C++
|
.cpp
| 520
| 44.982692
| 139
| 0.720305
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
26,363
|
testtranslationhandler.cpp
|
danmar_cppcheck/gui/test/translationhandler/testtranslationhandler.cpp
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testtranslationhandler.h"
#include "translationhandler.h"
#include <QList>
#include <QStringList>
#include <QtTest>
static QStringList getTranslationNames(const TranslationHandler& handler)
{
QStringList names;
for (const TranslationInfo& translation : handler.getTranslations()) {
names.append(translation.mName);
}
return names;
}
void TestTranslationHandler::construct() const
{
TranslationHandler handler;
QCOMPARE(getTranslationNames(handler).size(), 13); // 12 translations + english
QCOMPARE(handler.getCurrentLanguage(), QString("en"));
}
QTEST_MAIN(TestTranslationHandler)
| 1,385
|
C++
|
.cpp
| 37
| 34.864865
| 84
| 0.764531
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,365
|
good.cpp
|
danmar_cppcheck/samples/accessMoved/good.cpp
|
void foo(std::string);
int main()
{
std::string s = "test";
foo(s);
std::cout << s << std::endl;
}
| 113
|
C++
|
.cpp
| 7
| 13.142857
| 32
| 0.538462
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,366
|
bad.cpp
|
danmar_cppcheck/samples/accessMoved/bad.cpp
|
void foo(std::string);
int main()
{
std::string s = "test";
foo(std::move(s));
std::cout << s << std::endl;
}
| 124
|
C++
|
.cpp
| 7
| 14.714286
| 32
| 0.547826
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,369
|
good.cpp
|
danmar_cppcheck/samples/passedByValue_1/good.cpp
|
class C
{
public:
explicit C(std::string s)
: _s(std::move(s))
{
}
void foo();
private:
std::string _s;
};
| 130
|
C++
|
.cpp
| 11
| 8.727273
| 29
| 0.533333
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,370
|
bad.cpp
|
danmar_cppcheck/samples/passedByValue_1/bad.cpp
|
class C
{
public:
explicit C(std::string s)
: _s(s)
{
}
void foo();
private:
std::string _s;
};
| 119
|
C++
|
.cpp
| 11
| 7.727273
| 29
| 0.522936
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,371
|
good.cpp
|
danmar_cppcheck/samples/unreadVariable/good.cpp
|
void foo(const std::string&, const std::string&);
int main()
{
std::string s1 = "test1", s2 = "test2";
foo(s1, s2);
}
| 127
|
C++
|
.cpp
| 6
| 18.666667
| 49
| 0.6
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,372
|
bad.cpp
|
danmar_cppcheck/samples/unreadVariable/bad.cpp
|
void foo(const std::string&, const std::string&);
int main()
{
std::string s1 = "test1", s2 = "test2";
foo(s1, s1);
}
| 127
|
C++
|
.cpp
| 6
| 18.666667
| 49
| 0.6
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,373
|
good.cpp
|
danmar_cppcheck/samples/passedByValue_2/good.cpp
|
bool foo(const std::string& s)
{
return s.empty();
}
int main()
{
std::string s;
foo(s);
}
| 104
|
C++
|
.cpp
| 9
| 9.111111
| 30
| 0.585106
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,374
|
bad.cpp
|
danmar_cppcheck/samples/passedByValue_2/bad.cpp
|
bool foo(std::string s)
{
return s.empty();
}
int main()
{
std::string s;
foo(s);
}
| 97
|
C++
|
.cpp
| 9
| 8.333333
| 23
| 0.574713
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,375
|
misra-ctu-test.h
|
danmar_cppcheck/addons/test/misra/misra-ctu-test.h
|
typedef int MISRA_2_3_A;
typedef int MISRA_2_3_B;
typedef int MISRA_2_3_VIOLATION; // cppcheck-suppress misra-c2012-2.3
// cppcheck-suppress misra-c2012-2.4
struct misra_2_4_violation_t {
int x;
};
static inline void misra_5_9_exception(void) {}
void misra_8_7_external(void);
#define MISRA_2_5_OK_1 1
#define MISRA_2_5_OK_2 2
// cppcheck-suppress misra-c2012-2.5
#define MISRA_2_5_VIOLATION 0
// #12362
extern void misra_8_7_compliant( void );
| 457
|
C++
|
.h
| 15
| 28.666667
| 69
| 0.746544
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,376
|
misra-test.h
|
danmar_cppcheck/addons/test/misra/misra-test.h
|
#ifndef MISRA_TEST_H
#define MISRA_TEST_H
struct misra_h_s { int foo; };
bool test(char *a); // OK
int misra_8_2_no_fp(int a);
void misra_8_4_bar(void);
// #12978
typedef struct m8_4_stErrorDef
{
uint8_t ubReturnVal;
} m8_4_stErrorDef;
extern const m8_4_stErrorDef * m8_4_pubTestPointer;
#endif // MISRA_TEST_H
| 315
|
C++
|
.h
| 13
| 22.923077
| 51
| 0.725166
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,377
|
y2038-inc.h
|
danmar_cppcheck/addons/test/y2038/y2038-inc.h
|
#ifndef __INC2038
#define _INC2038
/*
* This file defines _USE_TIME_BITS64.
* It plays the role of a Y2038-proof glibc.
*/
#define _USE_TIME_BITS64
/*
* Declare just enough for clock_gettime
*/
typedef int clockid_t;
typedef int __time_t;
typedef long int __syscall_slong_t;
struct timespec
{
__time_t tv_sec; /* Seconds. */
__syscall_slong_t tv_nsec; /* Nanoseconds. */
};
extern int clock_gettime(clockid_t clk_id, struct timespec *tp);
#define CLOCK_REALTIME 0
#endif /* INC2038 */
| 511
|
C++
|
.h
| 21
| 22.238095
| 64
| 0.708333
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,378
|
version.h
|
danmar_cppcheck/lib/version.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// For a release version x.y.z the MAJOR should be x and both MINOR and DEVMINOR should be y.
// After a release the DEVMINOR is incremented. MAJOR=x MINOR=y, DEVMINOR=y+1
#ifndef versionH
#define versionH
#define CPPCHECK_MAJOR_VERSION 2
#define CPPCHECK_MINOR_VERSION 16
#define CPPCHECK_DEVMINOR_VERSION 17
#define CPPCHECK_BUGFIX_VERSION 99
#define STRINGIFY(x) STRING(x)
#define STRING(VER) #VER
#if CPPCHECK_BUGFIX_VERSION < 99
#define CPPCHECK_VERSION_STRING STRINGIFY(CPPCHECK_MAJOR_VERSION) "." STRINGIFY(CPPCHECK_MINOR_VERSION) "." STRINGIFY(CPPCHECK_BUGFIX_VERSION)
#define CPPCHECK_VERSION CPPCHECK_MAJOR_VERSION,CPPCHECK_MINOR_VERSION,CPPCHECK_BUGFIX_VERSION,0
#else
#define CPPCHECK_VERSION_STRING STRINGIFY(CPPCHECK_MAJOR_VERSION) "." STRINGIFY(CPPCHECK_DEVMINOR_VERSION) " dev"
#define CPPCHECK_VERSION CPPCHECK_MAJOR_VERSION,CPPCHECK_MINOR_VERSION,99,0
#endif
#define LEGALCOPYRIGHT L"Copyright (C) 2007-2024 Cppcheck team."
#endif
| 1,716
|
C++
|
.h
| 36
| 46.083333
| 142
| 0.781493
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,379
|
token.h
|
danmar_cppcheck/lib/token.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef tokenH
#define tokenH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include "templatesimplifier.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <functional>
#include <list>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
struct Enumerator;
class Function;
class Scope;
class Settings;
class Type;
class ValueType;
class Variable;
class ConstTokenRange;
class Token;
struct TokensFrontBack;
struct ScopeInfo2 {
ScopeInfo2(std::string name_, const Token *bodyEnd_, std::set<std::string> usingNamespaces_ = std::set<std::string>()) : name(std::move(name_)), bodyEnd(bodyEnd_), usingNamespaces(std::move(usingNamespaces_)) {}
std::string name;
const Token* const bodyEnd{};
std::set<std::string> usingNamespaces;
};
enum class TokenDebug : std::uint8_t { None, ValueFlow, ValueType };
struct TokenImpl {
nonneg int mVarId{};
nonneg int mFileIndex{};
nonneg int mLineNumber{};
nonneg int mColumn{};
nonneg int mExprId{};
/**
* A value from 0-100 that provides a rough idea about where in the token
* list this token is located.
*/
nonneg int mProgressValue{};
/**
* Token index. Position in token list
*/
nonneg int mIndex{};
/** Bitfield bit count. */
unsigned char mBits{};
// AST..
Token* mAstOperand1{};
Token* mAstOperand2{};
Token* mAstParent{};
// symbol database information
const Scope* mScope{};
union {
const Function *mFunction;
const Variable *mVariable;
const ::Type* mType;
const Enumerator *mEnumerator;
};
// original name like size_t
std::string* mOriginalName{};
// If this token came from a macro replacement list, this is the name of that macro
std::string mMacroName;
// ValueType
ValueType* mValueType{};
// ValueFlow
std::list<ValueFlow::Value>* mValues{};
static const std::list<ValueFlow::Value> mEmptyValueList;
// Pointer to a template in the template simplifier
std::set<TemplateSimplifier::TokenAndName*>* mTemplateSimplifierPointers{};
// Pointer to the object representing this token's scope
std::shared_ptr<ScopeInfo2> mScopeInfo;
// __cppcheck_in_range__
struct CppcheckAttributes {
enum Type : std::uint8_t { LOW, HIGH } type = LOW;
MathLib::bigint value{};
CppcheckAttributes* next{};
};
CppcheckAttributes* mCppcheckAttributes{};
// alignas expressions
std::unique_ptr<std::vector<std::string>> mAttributeAlignas;
void addAttributeAlignas(const std::string& a) {
if (!mAttributeAlignas)
mAttributeAlignas = std::unique_ptr<std::vector<std::string>>(new std::vector<std::string>());
if (std::find(mAttributeAlignas->cbegin(), mAttributeAlignas->cend(), a) == mAttributeAlignas->cend())
mAttributeAlignas->push_back(a);
}
std::string mAttributeCleanup;
// For memoization, to speed up parsing of huge arrays #8897
enum class Cpp11init : std::uint8_t { UNKNOWN, CPP11INIT, NOINIT } mCpp11init = Cpp11init::UNKNOWN;
TokenDebug mDebug{};
void setCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint value);
bool getCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint &value) const;
TokenImpl() : mFunction(nullptr) {}
~TokenImpl();
};
/// @addtogroup Core
/// @{
/**
* @brief The token list that the TokenList generates is a linked-list of this class.
*
* Tokens are stored as strings. The "if", "while", etc are stored in plain text.
* The reason the Token class is needed (instead of using the string class) is that some extra functionality is also needed for tokens:
* - location of the token is stored (fileIndex, linenr, column)
* - functions for classifying the token (isName, isNumber, isBoolean, isStandardType)
*
* The Token class also has other functions for management of token list, matching tokens, etc.
*/
class CPPCHECKLIB Token {
friend class TestToken;
private:
TokensFrontBack& mTokensFrontBack;
public:
Token(const Token &) = delete;
Token& operator=(const Token &) = delete;
enum Type : std::uint8_t {
eVariable, eType, eFunction, eKeyword, eName, // Names: Variable (varId), Type (typeId, later), Function (FuncId, later), Language keyword, Name (unknown identifier)
eNumber, eString, eChar, eBoolean, eLiteral, eEnumerator, // Literals: Number, String, Character, Boolean, User defined literal (C++11), Enumerator
eArithmeticalOp, eComparisonOp, eAssignmentOp, eLogicalOp, eBitOp, eIncDecOp, eExtendedOp, // Operators: Arithmetical, Comparison, Assignment, Logical, Bitwise, ++/--, Extended
eBracket, // {, }, <, >: < and > only if link() is set. Otherwise they are comparison operators.
eLambda, // A function without a name
eEllipsis, // "..."
eOther,
eNone
};
explicit Token(TokensFrontBack &tokensFrontBack);
// for usage in CheckIO::ArgumentInfo only
explicit Token(const Token *tok);
~Token();
ConstTokenRange until(const Token * t) const;
template<typename T>
void str(T&& s) {
mStr = s;
mImpl->mVarId = 0;
update_property_info();
}
/**
* Concatenate two (quoted) strings. Automatically cuts of the last/first character.
* Example: "hello ""world" -> "hello world". Used by the token simplifier.
*/
void concatStr(std::string const& b);
const std::string &str() const {
return mStr;
}
/**
* Unlink and delete the next 'count' tokens.
*/
void deleteNext(nonneg int count = 1);
/**
* Unlink and delete the previous 'count' tokens.
*/
void deletePrevious(nonneg int count = 1);
/**
* Swap the contents of this token with the next token.
*/
void swapWithNext();
/**
* @return token in given index, related to this token.
* For example index 1 would return next token, and 2
* would return next from that one.
*/
const Token *tokAt(int index) const
{
return tokAtImpl(this, index);
}
Token *tokAt(int index)
{
return tokAtImpl(this, index);
}
/**
* @return the link to the token in given index, related to this token.
* For example index 1 would return the link to next token.
*/
const Token *linkAt(int index) const
{
return linkAtImpl(this, index);
}
Token *linkAt(int index)
{
return linkAtImpl(this, index);
}
/**
* @return String of the token in given index, related to this token.
* If that token does not exist, an empty string is being returned.
*/
const std::string &strAt(int index) const
{
const Token *tok = this->tokAt(index);
return tok ? tok->mStr : emptyString;
}
/**
* Match given token (or list of tokens) to a pattern list.
*
* Possible patterns
* "someRandomText" If token contains "someRandomText".
* @note Use Match() if you want to use flags in patterns
*
* The patterns can be also combined to compare to multiple tokens at once
* by separating tokens with a space, e.g.
* ") void {" will return true if first token is ')' next token
* is "void" and token after that is '{'. If even one of the tokens does
* not match its pattern, false is returned.
*
* @param tok List of tokens to be compared to the pattern
* @param pattern The pattern against which the tokens are compared,
* e.g. "const" or ") void {".
* @return true if given token matches with given pattern
* false if given token does not match with given pattern
*/
template<size_t count>
static bool simpleMatch(const Token *tok, const char (&pattern)[count]) {
return simpleMatch(tok, pattern, count-1);
}
static bool simpleMatch(const Token *tok, const char pattern[], size_t pattern_len);
/**
* Match given token (or list of tokens) to a pattern list.
*
* Possible patterns
* - "%any%" any token
* - "%assign%" a assignment operand
* - "%bool%" true or false
* - "%char%" Any token enclosed in '-character.
* - "%comp%" Any token such that isComparisonOp() returns true.
* - "%cop%" Any token such that isConstOp() returns true.
* - "%name%" any token which is a name, variable or type e.g. "hello" or "int". Also matches keywords.
* - "%num%" Any numeric token, e.g. "23"
* - "%op%" Any token such that isOp() returns true.
* - "%or%" A bitwise-or operator '|'
* - "%oror%" A logical-or operator '||'
* - "%type%" Anything that can be a variable type, e.g. "int". Also matches keywords.
* - "%str%" Any token starting with "-character (C-string).
* - "%var%" Match with token with varId > 0
* - "%varid%" Match with parameter varid
* - "[abc]" Any of the characters 'a' or 'b' or 'c'
* - "int|void|char" Any of the strings, int, void or char
* - "int|void|char|" Any of the strings, int, void or char or no token
* - "!!else" No tokens or any token that is not "else".
* - "someRandomText" If token contains "someRandomText".
*
* multi-compare patterns such as "int|void|char" can contain %%or%, %%oror% and %%op%
* it is recommended to put such an %%cmd% as the first pattern.
* For example: "%var%|%num%|)" means yes to a variable, a number or ')'.
*
* The patterns can be also combined to compare to multiple tokens at once
* by separating tokens with a space, e.g.
* ") const|void {" will return true if first token is ')' next token is either
* "const" or "void" and token after that is '{'. If even one of the tokens does not
* match its pattern, false is returned.
*
* @param tok List of tokens to be compared to the pattern
* @param pattern The pattern against which the tokens are compared,
* e.g. "const" or ") const|volatile| {".
* @param varid if %%varid% is given in the pattern the Token::varId
* will be matched against this argument
* @return true if given token matches with given pattern
* false if given token does not match with given pattern
*/
static bool Match(const Token *tok, const char pattern[], nonneg int varid = 0);
/**
* @return length of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
**/
static nonneg int getStrLength(const Token *tok);
/**
* @return array length of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
**/
static nonneg int getStrArraySize(const Token *tok);
/**
* @return sizeof of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
* @param settings Settings
**/
static nonneg int getStrSize(const Token *tok, const Settings & settings);
const ValueType *valueType() const {
return mImpl->mValueType;
}
void setValueType(ValueType *vt);
const ValueType *argumentType() const;
Token::Type tokType() const {
return mTokType;
}
void tokType(Token::Type t) {
mTokType = t;
const bool memoizedIsName = (mTokType == eName || mTokType == eType || mTokType == eVariable ||
mTokType == eFunction || mTokType == eKeyword || mTokType == eBoolean ||
mTokType == eEnumerator); // TODO: "true"/"false" aren't really a name...
setFlag(fIsName, memoizedIsName);
const bool memoizedIsLiteral = (mTokType == eNumber || mTokType == eString || mTokType == eChar ||
mTokType == eBoolean || mTokType == eLiteral || mTokType == eEnumerator);
setFlag(fIsLiteral, memoizedIsLiteral);
}
bool isKeyword() const {
return mTokType == eKeyword;
}
bool isName() const {
return getFlag(fIsName);
}
bool isNameOnly() const {
return mFlags == fIsName && mTokType == eName;
}
bool isUpperCaseName() const;
bool isLiteral() const {
return getFlag(fIsLiteral);
}
bool isNumber() const {
return mTokType == eNumber;
}
bool isEnumerator() const {
return mTokType == eEnumerator;
}
bool isVariable() const {
return mTokType == eVariable;
}
bool isOp() const {
return (isConstOp() ||
isAssignmentOp() ||
mTokType == eIncDecOp);
}
bool isConstOp() const {
return (isArithmeticalOp() ||
mTokType == eLogicalOp ||
mTokType == eComparisonOp ||
mTokType == eBitOp);
}
bool isExtendedOp() const {
return isConstOp() ||
mTokType == eExtendedOp;
}
bool isArithmeticalOp() const {
return mTokType == eArithmeticalOp;
}
bool isComparisonOp() const {
return mTokType == eComparisonOp;
}
bool isAssignmentOp() const {
return mTokType == eAssignmentOp;
}
bool isBoolean() const {
return mTokType == eBoolean;
}
bool isIncDecOp() const {
return mTokType == eIncDecOp;
}
bool isBinaryOp() const {
return astOperand1() != nullptr && astOperand2() != nullptr;
}
bool isUnaryOp(const std::string &s) const {
return s == mStr && astOperand1() != nullptr && astOperand2() == nullptr;
}
bool isUnaryPreOp() const;
uint64_t flags() const {
return mFlags;
}
void flags(const uint64_t flags_) {
mFlags = flags_;
}
bool isUnsigned() const {
return getFlag(fIsUnsigned);
}
void isUnsigned(const bool sign) {
setFlag(fIsUnsigned, sign);
}
bool isSigned() const {
return getFlag(fIsSigned);
}
void isSigned(const bool sign) {
setFlag(fIsSigned, sign);
}
// cppcheck-suppress unusedFunction
bool isPointerCompare() const {
return getFlag(fIsPointerCompare);
}
void isPointerCompare(const bool b) {
setFlag(fIsPointerCompare, b);
}
bool isLong() const {
return getFlag(fIsLong);
}
void isLong(bool size) {
setFlag(fIsLong, size);
}
bool isStandardType() const {
return getFlag(fIsStandardType);
}
void isStandardType(const bool b) {
setFlag(fIsStandardType, b);
}
bool isExpandedMacro() const {
return !mImpl->mMacroName.empty();
}
bool isCast() const {
return getFlag(fIsCast);
}
void isCast(bool c) {
setFlag(fIsCast, c);
}
bool isAttributeConstructor() const {
return getFlag(fIsAttributeConstructor);
}
void isAttributeConstructor(const bool ac) {
setFlag(fIsAttributeConstructor, ac);
}
bool isAttributeDestructor() const {
return getFlag(fIsAttributeDestructor);
}
void isAttributeDestructor(const bool value) {
setFlag(fIsAttributeDestructor, value);
}
bool isAttributeUnused() const {
return getFlag(fIsAttributeUnused);
}
void isAttributeUnused(bool unused) {
setFlag(fIsAttributeUnused, unused);
}
bool isAttributeUsed() const {
return getFlag(fIsAttributeUsed);
}
void isAttributeUsed(const bool unused) {
setFlag(fIsAttributeUsed, unused);
}
bool isAttributePure() const {
return getFlag(fIsAttributePure);
}
void isAttributePure(const bool value) {
setFlag(fIsAttributePure, value);
}
bool isAttributeConst() const {
return getFlag(fIsAttributeConst);
}
void isAttributeConst(bool value) {
setFlag(fIsAttributeConst, value);
}
bool isAttributeNoreturn() const {
return getFlag(fIsAttributeNoreturn);
}
void isAttributeNoreturn(const bool value) {
setFlag(fIsAttributeNoreturn, value);
}
bool isAttributeNothrow() const {
return getFlag(fIsAttributeNothrow);
}
void isAttributeNothrow(const bool value) {
setFlag(fIsAttributeNothrow, value);
}
bool isAttributeExport() const {
return getFlag(fIsAttributeExport);
}
void isAttributeExport(const bool value) {
setFlag(fIsAttributeExport, value);
}
bool isAttributePacked() const {
return getFlag(fIsAttributePacked);
}
void isAttributePacked(const bool value) {
setFlag(fIsAttributePacked, value);
}
bool isAttributeNodiscard() const {
return getFlag(fIsAttributeNodiscard);
}
void isAttributeNodiscard(const bool value) {
setFlag(fIsAttributeNodiscard, value);
}
bool isAttributeMaybeUnused() const {
return getFlag(fIsAttributeMaybeUnused);
}
void isAttributeMaybeUnused(const bool value) {
setFlag(fIsAttributeMaybeUnused, value);
}
std::vector<std::string> getAttributeAlignas() const {
return mImpl->mAttributeAlignas ? *mImpl->mAttributeAlignas : std::vector<std::string>();
}
bool hasAttributeAlignas() const {
return !!mImpl->mAttributeAlignas;
}
void addAttributeAlignas(const std::string& a) {
mImpl->addAttributeAlignas(a);
}
void addAttributeCleanup(const std::string& funcname) {
mImpl->mAttributeCleanup = funcname;
}
const std::string& getAttributeCleanup() const {
return mImpl->mAttributeCleanup;
}
bool hasAttributeCleanup() const {
return !mImpl->mAttributeCleanup.empty();
}
void setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint value) {
mImpl->setCppcheckAttribute(type, value);
}
bool getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint &value) const {
return mImpl->getCppcheckAttribute(type, value);
}
// cppcheck-suppress unusedFunction
bool hasCppcheckAttributes() const {
return nullptr != mImpl->mCppcheckAttributes;
}
bool isControlFlowKeyword() const {
return getFlag(fIsControlFlowKeyword);
}
bool isOperatorKeyword() const {
return getFlag(fIsOperatorKeyword);
}
void isOperatorKeyword(const bool value) {
setFlag(fIsOperatorKeyword, value);
}
bool isComplex() const {
return getFlag(fIsComplex);
}
void isComplex(const bool value) {
setFlag(fIsComplex, value);
}
bool isEnumType() const {
return getFlag(fIsEnumType);
}
void isEnumType(const bool value) {
setFlag(fIsEnumType, value);
}
bool isAtAddress() const {
return getFlag(fAtAddress);
}
void isAtAddress(bool b) {
setFlag(fAtAddress, b);
}
bool isIncompleteVar() const {
return getFlag(fIncompleteVar);
}
void isIncompleteVar(bool b) {
setFlag(fIncompleteVar, b);
}
bool isSimplifiedTypedef() const {
return getFlag(fIsSimplifiedTypedef);
}
void isSimplifiedTypedef(bool b) {
setFlag(fIsSimplifiedTypedef, b);
}
bool isIncompleteConstant() const {
return getFlag(fIsIncompleteConstant);
}
void isIncompleteConstant(bool b) {
setFlag(fIsIncompleteConstant, b);
}
bool isConstexpr() const {
return getFlag(fConstexpr);
}
void isConstexpr(bool b) {
setFlag(fConstexpr, b);
}
bool isExternC() const {
return getFlag(fExternC);
}
void isExternC(bool b) {
setFlag(fExternC, b);
}
bool isSplittedVarDeclComma() const {
return getFlag(fIsSplitVarDeclComma);
}
void isSplittedVarDeclComma(bool b) {
setFlag(fIsSplitVarDeclComma, b);
}
bool isSplittedVarDeclEq() const {
return getFlag(fIsSplitVarDeclEq);
}
void isSplittedVarDeclEq(bool b) {
setFlag(fIsSplitVarDeclEq, b);
}
bool isImplicitInt() const {
return getFlag(fIsImplicitInt);
}
void isImplicitInt(bool b) {
setFlag(fIsImplicitInt, b);
}
bool isInline() const {
return getFlag(fIsInline);
}
void isInline(bool b) {
setFlag(fIsInline, b);
}
bool isAtomic() const {
return getFlag(fIsAtomic);
}
void isAtomic(bool b) {
setFlag(fIsAtomic, b);
}
bool isRestrict() const {
return getFlag(fIsRestrict);
}
void isRestrict(bool b) {
setFlag(fIsRestrict, b);
}
bool isRemovedVoidParameter() const {
return getFlag(fIsRemovedVoidParameter);
}
void setRemovedVoidParameter(bool b) {
setFlag(fIsRemovedVoidParameter, b);
}
bool isTemplate() const {
return getFlag(fIsTemplate);
}
void isTemplate(bool b) {
setFlag(fIsTemplate, b);
}
bool isSimplifiedScope() const {
return getFlag(fIsSimplifedScope);
}
void isSimplifiedScope(bool b) {
setFlag(fIsSimplifedScope, b);
}
bool isFinalType() const {
return getFlag(fIsFinalType);
}
void isFinalType(bool b) {
setFlag(fIsFinalType, b);
}
bool isInitComma() const {
return getFlag(fIsInitComma);
}
void isInitComma(bool b) {
setFlag(fIsInitComma, b);
}
// cppcheck-suppress unusedFunction
bool isBitfield() const {
return mImpl->mBits > 0;
}
unsigned char bits() const {
return mImpl->mBits;
}
const std::set<TemplateSimplifier::TokenAndName*>* templateSimplifierPointers() const {
return mImpl->mTemplateSimplifierPointers;
}
std::set<TemplateSimplifier::TokenAndName*>* templateSimplifierPointers() {
return mImpl->mTemplateSimplifierPointers;
}
void templateSimplifierPointer(TemplateSimplifier::TokenAndName* tokenAndName) {
if (!mImpl->mTemplateSimplifierPointers)
mImpl->mTemplateSimplifierPointers = new std::set<TemplateSimplifier::TokenAndName*>;
mImpl->mTemplateSimplifierPointers->insert(tokenAndName);
}
void setBits(const unsigned char b) {
mImpl->mBits = b;
}
bool isUtf8() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "u8")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "u8")));
}
bool isUtf16() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "u")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "u")));
}
bool isUtf32() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "U")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "U")));
}
bool isCChar() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', emptyString)) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', emptyString) && (replaceEscapeSequences(getCharLiteral(mStr)).size() == 1)));
}
bool isCMultiChar() const {
return (mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', emptyString) && (replaceEscapeSequences(getCharLiteral(mStr)).size() > 1);
}
/**
* @brief Is current token a template argument?
*
* Original code:
*
* template<class C> struct S {
* C x;
* };
* S<int> s;
*
* Resulting code:
*
* struct S<int> {
* int x ; // <- "int" is a template argument
* }
* S<int> s;
*/
bool isTemplateArg() const {
return getFlag(fIsTemplateArg);
}
void isTemplateArg(const bool value) {
setFlag(fIsTemplateArg, value);
}
const std::string& getMacroName() const {
return mImpl->mMacroName;
}
void setMacroName(std::string name) {
mImpl->mMacroName = std::move(name);
}
template<size_t count>
static const Token *findsimplematch(const Token * const startTok, const char (&pattern)[count]) {
return findsimplematch(startTok, pattern, count-1);
}
static const Token *findsimplematch(const Token * startTok, const char pattern[], size_t pattern_len);
template<size_t count>
static const Token *findsimplematch(const Token * const startTok, const char (&pattern)[count], const Token * const end) {
return findsimplematch(startTok, pattern, count-1, end);
}
static const Token *findsimplematch(const Token * startTok, const char pattern[], size_t pattern_len, const Token * end);
static const Token *findmatch(const Token * startTok, const char pattern[], nonneg int varId = 0);
static const Token *findmatch(const Token * startTok, const char pattern[], const Token * end, nonneg int varId = 0);
template<size_t count>
static Token *findsimplematch(Token * const startTok, const char (&pattern)[count]) {
return findsimplematch(startTok, pattern, count-1);
}
static Token *findsimplematch(Token * startTok, const char pattern[], size_t pattern_len);
template<size_t count>
static Token *findsimplematch(Token * const startTok, const char (&pattern)[count], const Token * const end) {
return findsimplematch(startTok, pattern, count-1, end);
}
static Token *findsimplematch(Token * startTok, const char pattern[], size_t pattern_len, const Token * end);
static Token *findmatch(Token * startTok, const char pattern[], nonneg int varId = 0);
static Token *findmatch(Token * startTok, const char pattern[], const Token * end, nonneg int varId = 0);
private:
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *tokAtImpl(T *tok, int index)
{
while (index > 0 && tok) {
tok = tok->next();
--index;
}
while (index < 0 && tok) {
tok = tok->previous();
++index;
}
return tok;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *linkAtImpl(T *thisTok, int index)
{
T *tok = thisTok->tokAt(index);
if (!tok) {
throw InternalError(thisTok, "Internal error. Token::linkAt called with index outside the tokens range.");
}
return tok->link();
}
/**
* Needle is build from multiple alternatives. If one of
* them is equal to haystack, return value is 1. If there
* are no matches, but one alternative to needle is empty
* string, return value is 0. If needle was not found, return
* value is -1.
*
* @param tok Current token (needle)
* @param haystack e.g. "one|two" or "|one|two"
* @param varid optional varid of token
* @return 1 if needle is found from the haystack
* 0 if needle was empty string
* -1 if needle was not found
*/
static int multiCompare(const Token *tok, const char *haystack, nonneg int varid);
public:
const std::string& fileName() const;
nonneg int fileIndex() const {
return mImpl->mFileIndex;
}
void fileIndex(nonneg int indexOfFile) {
mImpl->mFileIndex = indexOfFile;
}
nonneg int linenr() const {
return mImpl->mLineNumber;
}
void linenr(nonneg int lineNumber) {
mImpl->mLineNumber = lineNumber;
}
nonneg int column() const {
return mImpl->mColumn;
}
void column(nonneg int c) {
mImpl->mColumn = c;
}
Token* next() {
return mNext;
}
const Token* next() const {
return mNext;
}
/**
* Delete tokens between begin and end. E.g. if begin = 1
* and end = 5, tokens 2,3 and 4 would be erased.
*
* @param begin Tokens after this will be erased.
* @param end Tokens before this will be erased.
*/
static void eraseTokens(Token *begin, const Token *end);
/**
* Insert new token after this token. This function will handle
* relations between next and previous token also.
* @param tokenStr String for the new token.
* @param originalNameStr String used for Token::originalName().
* @param prepend Insert the new token before this token when it's not
* the first one on the tokens list.
*/
RET_NONNULL Token* insertToken(const std::string& tokenStr, const std::string& originalNameStr = emptyString, const std::string& macroNameStr = emptyString, bool prepend = false);
RET_NONNULL Token* insertTokenBefore(const std::string& tokenStr, const std::string& originalNameStr = emptyString, const std::string& macroNameStr = emptyString)
{
return insertToken(tokenStr, originalNameStr, macroNameStr, true);
}
Token* previous() {
return mPrevious;
}
const Token* previous() const {
return mPrevious;
}
nonneg int varId() const {
return mImpl->mVarId;
}
void varId(nonneg int id) {
mImpl->mVarId = id;
if (id != 0) {
tokType(eVariable);
isStandardType(false);
} else {
update_property_info();
}
}
nonneg int exprId() const {
if (mImpl->mExprId)
return mImpl->mExprId;
return mImpl->mVarId;
}
void exprId(nonneg int id) {
mImpl->mExprId = id;
}
void setUniqueExprId()
{
assert(mImpl->mExprId > 0);
mImpl->mExprId |= 1 << efIsUnique;
}
bool isUniqueExprId() const
{
return (mImpl->mExprId & (1 << efIsUnique)) != 0;
}
/**
* For debugging purposes, prints token and all tokens followed by it.
*/
void printOut() const;
/**
* For debugging purposes, prints token and all tokens followed by it.
* @param title Title for the printout or use default parameter or 0
* for no title.
*/
void printOut(std::ostream& out, const char *title = nullptr) const;
/**
* For debugging purposes, prints token and all tokens followed by it.
* @param title Title for the printout or use default parameter or 0
* for no title.
* @param fileNames Prints out file name instead of file index.
* File index should match the index of the string in this vector.
*/
void printOut(std::ostream& out, const char *title, const std::vector<std::string> &fileNames) const;
/**
* print out tokens - used for debugging
*/
void printLines(std::ostream& out, int lines=5) const;
/**
* Replace token replaceThis with tokens between start and end,
* including start and end. The replaceThis token is deleted.
* @param replaceThis This token will be deleted.
* @param start This will be in the place of replaceThis
* @param end This is also in the place of replaceThis
*/
static void replace(Token *replaceThis, Token *start, Token *end);
struct stringifyOptions {
bool varid = false;
bool exprid = false;
bool idtype = false; // distinguish varid / exprid
bool attributes = false;
bool macro = false;
bool linenumbers = false;
bool linebreaks = false;
bool files = false;
static stringifyOptions forDebug() {
stringifyOptions options;
options.attributes = true;
options.macro = true;
options.linenumbers = true;
options.linebreaks = true;
options.files = true;
return options;
}
// cppcheck-suppress unusedFunction
static stringifyOptions forDebugVarId() {
stringifyOptions options = forDebug();
options.varid = true;
return options;
}
static stringifyOptions forDebugExprId() {
stringifyOptions options = forDebug();
options.exprid = true;
return options;
}
static stringifyOptions forPrintOut() {
stringifyOptions options = forDebug();
options.exprid = true;
options.varid = true;
options.idtype = true;
return options;
}
};
std::string stringify(const stringifyOptions& options) const;
/**
* Stringify a token
* @param varid Print varids. (Style: "varname\@id")
* @param attributes Print attributes of tokens like "unsigned" in front of it.
* @param macro Prints $ in front of the token if it was expanded from a macro.
*/
std::string stringify(bool varid, bool attributes, bool macro) const;
std::string stringifyList(const stringifyOptions& options, const std::vector<std::string>* fileNames = nullptr, const Token* end = nullptr) const;
std::string stringifyList(const Token* end, bool attributes = true) const;
std::string stringifyList(bool varid = false) const;
/**
* Stringify a list of token, from current instance on.
* @param varid Print varids. (Style: "varname\@id")
* @param attributes Print attributes of tokens like "unsigned" in front of it.
* @param linenumbers Print line number in front of each line
* @param linebreaks Insert "\\n" into string when line number changes
* @param files print Files as numbers or as names (if fileNames is given)
* @param fileNames Vector of filenames. Used (if given) to print filenames as strings instead of numbers.
* @param end Stringification ends before this token is reached. 0 to stringify until end of list.
* @return Stringified token list as a string
*/
std::string stringifyList(bool varid, bool attributes, bool linenumbers, bool linebreaks, bool files, const std::vector<std::string>* fileNames = nullptr, const Token* end = nullptr) const;
/**
* Remove the contents for this token from the token list.
*
* The contents are replaced with the contents of the next token and
* the next token is unlinked and deleted from the token list.
*
* So this token will still be valid after the 'deleteThis()'.
*/
void deleteThis();
/**
* Create link to given token
* @param linkToToken The token where this token should link
* to.
*/
void link(Token *linkToToken) {
mLink = linkToToken;
if (mStr == "<" || mStr == ">")
update_property_info();
}
/**
* Return token where this token links to.
* Supported links are:
* "{" <-> "}"
* "(" <-> ")"
* "[" <-> "]"
*
* @return The token where this token links to.
*/
const Token* link() const {
return mLink;
}
Token* link() {
return mLink;
}
/**
* Associate this token with given scope
* @param s Scope to be associated
*/
void scope(const Scope *s) {
mImpl->mScope = s;
}
/**
* @return a pointer to the scope containing this token.
*/
const Scope *scope() const {
return mImpl->mScope;
}
/**
* Associate this token with given function
* @param f Function to be associated
*/
void function(const Function *f);
/**
* @return a pointer to the Function associated with this token.
*/
const Function *function() const {
return mTokType == eFunction || mTokType == eLambda ? mImpl->mFunction : nullptr;
}
/**
* Associate this token with given variable
* @param v Variable to be associated
*/
void variable(const Variable *v) {
mImpl->mVariable = v;
if (v || mImpl->mVarId)
tokType(eVariable);
else if (mTokType == eVariable)
tokType(eName);
}
/**
* @return a pointer to the variable associated with this token.
*/
const Variable *variable() const {
return mTokType == eVariable ? mImpl->mVariable : nullptr;
}
/**
* Associate this token with given type
* @param t Type to be associated
*/
void type(const ::Type *t);
/**
* @return a pointer to the type associated with this token.
*/
const ::Type *type() const {
return mTokType == eType ? mImpl->mType : nullptr;
}
static const ::Type* typeOf(const Token* tok, const Token** typeTok = nullptr);
/**
* @return the declaration associated with this token.
* @param pointedToType return the pointed-to type?
*/
static std::pair<const Token*, const Token*> typeDecl(const Token* tok, bool pointedToType = false);
static std::string typeStr(const Token* tok);
/**
* @return a pointer to the Enumerator associated with this token.
*/
const Enumerator *enumerator() const {
return mTokType == eEnumerator ? mImpl->mEnumerator : nullptr;
}
/**
* Associate this token with given enumerator
* @param e Enumerator to be associated
*/
void enumerator(const Enumerator *e) {
mImpl->mEnumerator = e;
if (e)
tokType(eEnumerator);
else if (mTokType == eEnumerator)
tokType(eName);
}
/**
* Links two elements against each other.
**/
static void createMutualLinks(Token *begin, Token *end);
/**
* This can be called only for tokens that are strings, else
* the assert() is called. If Token is e.g. '"hello"', this will return
* 'hello' (removing the double quotes).
* @return String value
*/
std::string strValue() const;
/**
* Move srcStart and srcEnd tokens and all tokens between them
* into new a location. Only links between tokens are changed.
* @param srcStart This is the first token to be moved
* @param srcEnd The last token to be moved
* @param newLocation srcStart will be placed after this token.
*/
static void move(Token *srcStart, Token *srcEnd, Token *newLocation);
/** Get progressValue (0 - 100) */
nonneg int progressValue() const {
return mImpl->mProgressValue;
}
/** Calculate progress values for all tokens */
static void assignProgressValues(Token *tok);
/**
* @return the first token of the next argument. Does only work on argument
* lists. Requires that Tokenizer::createLinks2() has been called before.
* Returns nullptr, if there is no next argument.
*/
const Token* nextArgument() const;
Token *nextArgument();
/**
* @return the first token of the next argument. Does only work on argument
* lists. Should be used only before Tokenizer::createLinks2() was called.
* Returns nullptr, if there is no next argument.
*/
const Token* nextArgumentBeforeCreateLinks2() const;
/**
* @return the first token of the next template argument. Does only work on template argument
* lists. Requires that Tokenizer::createLinks2() has been called before.
* Returns nullptr, if there is no next argument.
*/
const Token* nextTemplateArgument() const;
/**
* Returns the closing bracket of opening '<'. Should only be used if link()
* is unavailable.
* @return closing '>', ')', ']' or '}'. if no closing bracket is found, NULL is returned
*/
const Token* findClosingBracket() const;
Token* findClosingBracket();
const Token* findOpeningBracket() const;
Token* findOpeningBracket();
/**
* @return the original name.
*/
const std::string & originalName() const {
return mImpl->mOriginalName ? *mImpl->mOriginalName : emptyString;
}
const std::list<ValueFlow::Value>& values() const {
return mImpl->mValues ? *mImpl->mValues : TokenImpl::mEmptyValueList;
}
/**
* Sets the original name.
*/
template<typename T>
void originalName(T&& name) {
if (!mImpl->mOriginalName)
mImpl->mOriginalName = new std::string(name);
else
*mImpl->mOriginalName = name;
}
bool hasKnownIntValue() const;
bool hasKnownValue() const;
bool hasKnownValue(ValueFlow::Value::ValueType t) const;
bool hasKnownSymbolicValue(const Token* tok) const;
const ValueFlow::Value* getKnownValue(ValueFlow::Value::ValueType t) const;
MathLib::bigint getKnownIntValue() const {
return mImpl->mValues->front().intvalue;
}
const ValueFlow::Value* getValue(MathLib::bigint val) const;
const ValueFlow::Value* getMaxValue(bool condition, MathLib::bigint path = 0) const;
const ValueFlow::Value* getMinValue(bool condition, MathLib::bigint path = 0) const;
const ValueFlow::Value* getMovedValue() const;
const ValueFlow::Value * getValueLE(MathLib::bigint val, const Settings &settings) const;
const ValueFlow::Value * getValueGE(MathLib::bigint val, const Settings &settings) const;
const ValueFlow::Value * getInvalidValue(const Token *ftok, nonneg int argnr, const Settings &settings) const;
const ValueFlow::Value* getContainerSizeValue(MathLib::bigint val) const;
const Token *getValueTokenMaxStrLength() const;
const Token *getValueTokenMinStrSize(const Settings &settings, MathLib::bigint* path = nullptr) const;
/** Add token value. Return true if value is added. */
bool addValue(const ValueFlow::Value &value);
void removeValues(std::function<bool(const ValueFlow::Value &)> pred) {
if (mImpl->mValues)
mImpl->mValues->remove_if(std::move(pred));
}
nonneg int index() const {
return mImpl->mIndex;
}
void assignIndexes();
private:
void next(Token *nextToken) {
mNext = nextToken;
}
void previous(Token *previousToken) {
mPrevious = previousToken;
}
/** used by deleteThis() to take data from token to delete */
void takeData(Token *fromToken);
/**
* Works almost like strcmp() except returns only true or false and
* if str has empty space ' ' character, that character is handled
* as if it were '\\0'
*/
static bool firstWordEquals(const char *str, const char *word);
/**
* Works almost like strchr() except
* if str has empty space ' ' character, that character is handled
* as if it were '\\0'
*/
static const char *chrInFirstWord(const char *str, char c);
std::string mStr;
Token* mNext{};
Token* mPrevious{};
Token* mLink{};
enum : uint64_t {
fIsUnsigned = (1ULL << 0),
fIsSigned = (1ULL << 1),
fIsPointerCompare = (1ULL << 2),
fIsLong = (1ULL << 3),
fIsStandardType = (1ULL << 4),
//fIsExpandedMacro = (1ULL << 5),
fIsCast = (1ULL << 6),
fIsAttributeConstructor = (1ULL << 7), // __attribute__((constructor)) __attribute__((constructor(priority)))
fIsAttributeDestructor = (1ULL << 8), // __attribute__((destructor)) __attribute__((destructor(priority)))
fIsAttributeUnused = (1ULL << 9), // __attribute__((unused))
fIsAttributePure = (1ULL << 10), // __attribute__((pure))
fIsAttributeConst = (1ULL << 11), // __attribute__((const))
fIsAttributeNoreturn = (1ULL << 12), // __attribute__((noreturn)), __declspec(noreturn)
fIsAttributeNothrow = (1ULL << 13), // __attribute__((nothrow)), __declspec(nothrow)
fIsAttributeUsed = (1ULL << 14), // __attribute__((used))
fIsAttributePacked = (1ULL << 15), // __attribute__((packed))
fIsAttributeExport = (1ULL << 16), // __attribute__((__visibility__("default"))), __declspec(dllexport)
fIsAttributeMaybeUnused = (1ULL << 17), // [[maybe_unused]]
fIsAttributeNodiscard = (1ULL << 18), // __attribute__ ((warn_unused_result)), [[nodiscard]]
fIsControlFlowKeyword = (1ULL << 19), // if/switch/while/...
fIsOperatorKeyword = (1ULL << 20), // operator=, etc
fIsComplex = (1ULL << 21), // complex/_Complex type
fIsEnumType = (1ULL << 22), // enumeration type
fIsName = (1ULL << 23),
fIsLiteral = (1ULL << 24),
fIsTemplateArg = (1ULL << 25),
fAtAddress = (1ULL << 26), // @ 0x4000
fIncompleteVar = (1ULL << 27),
fConstexpr = (1ULL << 28),
fExternC = (1ULL << 29),
fIsSplitVarDeclComma = (1ULL << 30), // set to true when variable declarations are split up ('int a,b;' => 'int a; int b;')
fIsSplitVarDeclEq = (1ULL << 31), // set to true when variable declaration with initialization is split up ('int a=5;' => 'int a; a=5;')
fIsImplicitInt = (1ULL << 32), // Is "int" token implicitly added?
fIsInline = (1ULL << 33), // Is this a inline type
fIsTemplate = (1ULL << 34),
fIsSimplifedScope = (1ULL << 35), // scope added when simplifying e.g. if (int i = ...; ...)
fIsRemovedVoidParameter = (1ULL << 36), // A void function parameter has been removed
fIsIncompleteConstant = (1ULL << 37),
fIsRestrict = (1ULL << 38), // Is this a restrict pointer type
fIsAtomic = (1ULL << 39), // Is this a _Atomic declaration
fIsSimplifiedTypedef = (1ULL << 40),
fIsFinalType = (1ULL << 41), // Is this a type with final specifier
fIsInitComma = (1ULL << 42), // Is this comma located inside some {..}. i.e: {1,2,3,4}
};
enum : std::uint8_t {
efMaxSize = sizeof(nonneg int) * 8,
efIsUnique = efMaxSize - 2,
};
Token::Type mTokType = eNone;
uint64_t mFlags{};
TokenImpl* mImpl{};
/**
* Get specified flag state.
* @param flag_ flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(uint64_t flag_) const {
return ((mFlags & flag_) != 0);
}
/**
* Set specified flag state.
* @param flag_ flag to set state
* @param state_ new state of flag
*/
void setFlag(uint64_t flag_, bool state_) {
mFlags = state_ ? mFlags | flag_ : mFlags & ~flag_;
}
/** Updates internal property cache like _isName or _isBoolean.
Called after any mStr() modification. */
void update_property_info();
/** Update internal property cache about isStandardType() */
void update_property_isStandardType();
/** Internal helper function to avoid excessive string allocations */
void astStringVerboseRecursive(std::string& ret, nonneg int indent1 = 0, nonneg int indent2 = 0) const;
// cppcheck-suppress premium-misra-cpp-2023-12.2.1
bool mIsC : 1;
bool mIsCpp : 1;
public:
void astOperand1(Token *tok);
void astOperand2(Token *tok);
void astParent(Token* tok);
Token * astOperand1() {
return mImpl->mAstOperand1;
}
const Token * astOperand1() const {
return mImpl->mAstOperand1;
}
Token * astOperand2() {
return mImpl->mAstOperand2;
}
const Token * astOperand2() const {
return mImpl->mAstOperand2;
}
Token * astParent() {
return mImpl->mAstParent;
}
const Token * astParent() const {
return mImpl->mAstParent;
}
Token * astSibling() {
if (!astParent())
return nullptr;
if (this == astParent()->astOperand1())
return astParent()->astOperand2();
if (this == astParent()->astOperand2())
return astParent()->astOperand1();
return nullptr;
}
const Token * astSibling() const {
if (!astParent())
return nullptr;
if (this == astParent()->astOperand1())
return astParent()->astOperand2();
if (this == astParent()->astOperand2())
return astParent()->astOperand1();
return nullptr;
}
RET_NONNULL Token *astTop() {
Token *ret = this;
while (ret->mImpl->mAstParent)
ret = ret->mImpl->mAstParent;
return ret;
}
RET_NONNULL const Token *astTop() const {
const Token *ret = this;
while (ret->mImpl->mAstParent)
ret = ret->mImpl->mAstParent;
return ret;
}
std::pair<const Token *, const Token *> findExpressionStartEndTokens() const;
/**
* Is current token a calculation? Only true for operands.
* For '*' and '&' tokens it is looked up if this is a
* dereference or address-of. A dereference or address-of is not
* counted as a calculation.
* @return returns true if current token is a calculation
*/
bool isCalculation() const;
void clearValueFlow() {
delete mImpl->mValues;
mImpl->mValues = nullptr;
}
std::string astString(const char *sep = "") const {
std::string ret;
if (mImpl->mAstOperand1)
ret = mImpl->mAstOperand1->astString(sep);
if (mImpl->mAstOperand2)
ret += mImpl->mAstOperand2->astString(sep);
return ret + sep + mStr;
}
std::string astStringVerbose() const;
std::string astStringZ3() const;
std::string expressionString() const;
void printAst(bool verbose, bool xml, const std::vector<std::string> &fileNames, std::ostream &out) const;
void printValueFlow(bool xml, std::ostream &out) const;
void scopeInfo(std::shared_ptr<ScopeInfo2> newScopeInfo);
std::shared_ptr<ScopeInfo2> scopeInfo() const;
void setCpp11init(bool cpp11init) const {
mImpl->mCpp11init=cpp11init ? TokenImpl::Cpp11init::CPP11INIT : TokenImpl::Cpp11init::NOINIT;
}
TokenImpl::Cpp11init isCpp11init() const {
return mImpl->mCpp11init;
}
TokenDebug getTokenDebug() const {
return mImpl->mDebug;
}
void setTokenDebug(TokenDebug td) {
mImpl->mDebug = td;
}
bool isCpp() const
{
return mIsCpp;
}
bool isC() const
{
return mIsC;
}
};
Token* findTypeEnd(Token* tok);
Token* findLambdaEndScope(Token* tok);
const Token* findLambdaEndScope(const Token* tok);
/// @}
//---------------------------------------------------------------------------
#endif // tokenH
| 51,565
|
C++
|
.h
| 1,379
| 30.91298
| 215
| 0.633349
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,380
|
vfvalue.h
|
danmar_cppcheck/lib/vfvalue.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef vfvalueH
#define vfvalueH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include <cassert>
#include <cmath>
#include <cstdint>
#include <functional>
#include <string>
#include <type_traits>
#include <vector>
class Token;
namespace ValueFlow
{
class CPPCHECKLIB Value {
public:
enum class Bound : std::uint8_t { Upper, Lower, Point };
explicit Value(long long val = 0, Bound b = Bound::Point) :
bound(b),
intvalue(val),
varvalue(val),
wideintvalue(val)
{}
Value(const Token* c, long long val, Bound b = Bound::Point);
static Value unknown() {
Value v;
v.valueType = ValueType::UNINIT;
return v;
}
bool equalValue(const ValueFlow::Value& rhs) const {
if (valueType != rhs.valueType)
return false;
switch (valueType) {
case ValueType::INT:
case ValueType::CONTAINER_SIZE:
case ValueType::BUFFER_SIZE:
case ValueType::ITERATOR_START:
case ValueType::ITERATOR_END:
if (intvalue != rhs.intvalue)
return false;
break;
case ValueType::TOK:
if (tokvalue != rhs.tokvalue)
return false;
break;
case ValueType::FLOAT:
if (floatValue > rhs.floatValue || floatValue < rhs.floatValue || std::signbit(floatValue) != std::signbit(rhs.floatValue))
return false;
break;
case ValueType::MOVED:
if (moveKind != rhs.moveKind)
return false;
break;
case ValueType::UNINIT:
break;
case ValueType::LIFETIME:
if (tokvalue != rhs.tokvalue)
return false;
break;
case ValueType::SYMBOLIC:
if (!sameToken(tokvalue, rhs.tokvalue))
return false;
if (intvalue != rhs.intvalue)
return false;
break;
}
return true;
}
template<class T, class F>
static void visitValue(T& self, F f) {
switch (self.valueType) {
case ValueType::INT:
case ValueType::SYMBOLIC:
case ValueType::BUFFER_SIZE:
case ValueType::CONTAINER_SIZE:
case ValueType::ITERATOR_START:
case ValueType::ITERATOR_END: {
f(self.intvalue);
break;
}
case ValueType::FLOAT: {
f(self.floatValue);
break;
}
case ValueType::UNINIT:
case ValueType::TOK:
case ValueType::LIFETIME:
case ValueType::MOVED:
break;
}
}
struct compareVisitor {
struct innerVisitor {
template<class Compare, class T, class U>
void operator()(bool& result, Compare compare, T x, U y) const {
result = compare(x, y);
}
};
template<class Compare, class T>
void operator()(bool& result, const Value& rhs, Compare compare, T x) const {
visitValue(rhs,
std::bind(innerVisitor{}, std::ref(result), std::move(compare), x, std::placeholders::_1));
}
};
template<class Compare>
bool compareValue(const Value& rhs, Compare compare) const {
assert((!this->isSymbolicValue() && !rhs.isSymbolicValue()) ||
(this->valueType == rhs.valueType && sameToken(this->tokvalue, rhs.tokvalue)));
bool result = false;
visitValue(
*this,
std::bind(compareVisitor{}, std::ref(result), std::ref(rhs), std::move(compare), std::placeholders::_1));
return result;
}
bool operator==(const Value &rhs) const {
if (!equalValue(rhs))
return false;
return varvalue == rhs.varvalue &&
condition == rhs.condition &&
varId == rhs.varId &&
conditional == rhs.conditional &&
defaultArg == rhs.defaultArg &&
indirect == rhs.indirect &&
valueKind == rhs.valueKind;
}
bool operator!=(const Value &rhs) const {
return !(*this == rhs);
}
template<class T, REQUIRES("T must be an arithmetic type", std::is_arithmetic<T> )>
bool equalTo(const T& x) const {
bool result = false;
visitValue(*this, std::bind(equalVisitor{}, std::ref(result), x, std::placeholders::_1));
return result;
}
void decreaseRange() {
if (bound == Bound::Lower)
visitValue(*this, increment{});
else if (bound == Bound::Upper)
visitValue(*this, decrement{});
}
void invertBound() {
if (bound == Bound::Lower)
bound = Bound::Upper;
else if (bound == Bound::Upper)
bound = Bound::Lower;
}
void invertRange() {
invertBound();
decreaseRange();
}
void assumeCondition(const Token* tok);
std::string infoString() const;
std::string toString() const;
enum class ValueType : std::uint8_t {
INT,
TOK,
FLOAT,
MOVED,
UNINIT,
CONTAINER_SIZE,
LIFETIME,
BUFFER_SIZE,
ITERATOR_START,
ITERATOR_END,
SYMBOLIC
} valueType = ValueType::INT;
bool isIntValue() const {
return valueType == ValueType::INT;
}
bool isTokValue() const {
return valueType == ValueType::TOK;
}
bool isFloatValue() const {
return valueType == ValueType::FLOAT;
}
bool isMovedValue() const {
return valueType == ValueType::MOVED;
}
bool isUninitValue() const {
return valueType == ValueType::UNINIT;
}
bool isContainerSizeValue() const {
return valueType == ValueType::CONTAINER_SIZE;
}
bool isLifetimeValue() const {
return valueType == ValueType::LIFETIME;
}
bool isBufferSizeValue() const {
return valueType == ValueType::BUFFER_SIZE;
}
bool isIteratorValue() const {
return valueType == ValueType::ITERATOR_START || valueType == ValueType::ITERATOR_END;
}
bool isIteratorStartValue() const {
return valueType == ValueType::ITERATOR_START;
}
bool isIteratorEndValue() const {
return valueType == ValueType::ITERATOR_END;
}
bool isSymbolicValue() const {
return valueType == ValueType::SYMBOLIC;
}
bool isLocalLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::Local;
}
bool isArgumentLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::Argument;
}
bool isSubFunctionLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::SubFunction;
}
bool isNonValue() const {
return isMovedValue() || isUninitValue() || isLifetimeValue();
}
/** The value bound */
Bound bound = Bound::Point;
/** int value (or sometimes bool value?) */
long long intvalue{};
/** token value - the token that has the value. this is used for pointer aliases, strings, etc. */
const Token* tokvalue{};
/** float value */
double floatValue{};
/** For calculated values - variable value that calculated value depends on */
long long varvalue{};
/** Condition that this value depends on */
const Token* condition{};
ErrorPath errorPath;
ErrorPath debugPath;
/** For calculated values - varId that calculated value depends on */
nonneg int varId{};
/** value relies on safe checking */
bool safe{};
/** Conditional value */
bool conditional{};
/** Value is is from an expanded macro */
bool macro{};
/** Is this value passed as default parameter to the function? */
bool defaultArg{};
int indirect{};
/** kind of moved */
enum class MoveKind : std::uint8_t { NonMovedVariable, MovedVariable, ForwardedVariable } moveKind = MoveKind::NonMovedVariable;
/** Path id */
MathLib::bigint path{};
/** int value before implicit truncation */
long long wideintvalue{};
std::vector<std::string> subexpressions;
// Set to where a lifetime is captured by value
const Token* capturetok{};
enum class LifetimeKind : std::uint8_t {
// Pointer points to a member of lifetime
Object,
// A member of object points to the lifetime
SubObject,
// Lambda has captured lifetime(similar to SubObject)
Lambda,
// Iterator points to the lifetime of a container(similar to Object)
Iterator,
// A pointer that holds the address of the lifetime
Address
} lifetimeKind = LifetimeKind::Object;
enum class LifetimeScope : std::uint8_t { Local, Argument, SubFunction, ThisPointer, ThisValue } lifetimeScope = LifetimeScope::Local;
static const char* toString(MoveKind moveKind);
static const char* toString(LifetimeKind lifetimeKind);
static const char* toString(LifetimeScope lifetimeScope);
static const char* toString(Bound bound);
/** How known is this value */
enum class ValueKind : std::uint8_t {
/** This value is possible, other unlisted values may also be possible */
Possible,
/** Only listed values are possible */
Known,
/** Inconclusive */
Inconclusive,
/** Listed values are impossible */
Impossible
} valueKind = ValueKind::Possible;
void setKnown() {
valueKind = ValueKind::Known;
}
bool isKnown() const {
return valueKind == ValueKind::Known;
}
void setPossible() {
valueKind = ValueKind::Possible;
}
bool isPossible() const {
return valueKind == ValueKind::Possible;
}
bool isImpossible() const {
return valueKind == ValueKind::Impossible;
}
void setImpossible() {
valueKind = ValueKind::Impossible;
}
void setInconclusive(bool inconclusive = true) {
if (inconclusive)
valueKind = ValueKind::Inconclusive;
}
bool isInconclusive() const {
return valueKind == ValueKind::Inconclusive;
}
void changeKnownToPossible() {
if (isKnown())
valueKind = ValueKind::Possible;
}
bool errorSeverity() const {
return !condition && !defaultArg;
}
static bool sameToken(const Token* tok1, const Token* tok2);
private:
struct equalVisitor {
template<class T, class U>
void operator()(bool& result, T x, U y) const {
result = !(x > y || x < y);
}
};
struct increment {
template<class T>
void operator()(T& x) const {
x++;
}
};
struct decrement {
template<class T>
void operator()(T& x) const {
x--;
}
};
};
}
#endif // vfvalueH
| 13,152
|
C++
|
.h
| 351
| 26.353276
| 142
| 0.543413
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,381
|
vf_array.h
|
danmar_cppcheck/lib/vf_array.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfArrayH
#define vfArrayH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeArray(TokenList &tokenlist, const Settings &settings);
}
#endif // vfArrayH
| 947
|
C++
|
.h
| 26
| 34.5
| 72
| 0.756816
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,382
|
vf_iterators.h
|
danmar_cppcheck/lib/vf_iterators.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfIteratorsH
#define vfIteratorsH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeIterators(TokenList &tokenlist, const Settings &settings);
}
#endif // vfIteratorsH
| 963
|
C++
|
.h
| 26
| 35.115385
| 74
| 0.760986
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,383
|
clangimport.h
|
danmar_cppcheck/lib/clangimport.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef clangimportH
#define clangimportH
//---------------------------------------------------------------------------
#include "config.h"
#include <istream>
class Tokenizer;
namespace clangimport {
void CPPCHECKLIB parseClangAstDump(Tokenizer &tokenizer, std::istream &f);
}
#endif
| 1,135
|
C++
|
.h
| 28
| 38.571429
| 78
| 0.651818
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,384
|
templatesimplifier.h
|
danmar_cppcheck/lib/templatesimplifier.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef templatesimplifierH
#define templatesimplifierH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
class Tokenizer;
class TokenList;
struct newInstantiation;
/// @addtogroup Core
/// @{
/** @brief Simplify templates from the preprocessed and partially simplified code. */
class CPPCHECKLIB TemplateSimplifier {
friend class TestSimplifyTemplate;
public:
explicit TemplateSimplifier(Tokenizer &tokenizer);
const std::string& dump() const {
return mDump;
}
/**
*/
void checkComplicatedSyntaxErrorsInTemplates();
/**
* is the token pointing at a template parameters block
* < int , 3 > => yes
* \param tok start token that must point at "<"
* \return number of parameters (invalid parameters => 0)
*/
static unsigned int templateParameters(const Token *tok);
/**
* Token and its full scopename
*/
class TokenAndName {
Token *mToken;
std::string mScope;
std::string mName;
std::string mFullName;
const Token *mNameToken;
const Token *mParamEnd;
unsigned int mFlags;
enum : std::uint16_t {
fIsClass = (1 << 0), // class template
fIsFunction = (1 << 1), // function template
fIsVariable = (1 << 2), // variable template
fIsAlias = (1 << 3), // alias template
fIsSpecialization = (1 << 4), // user specialized template
fIsPartialSpecialization = (1 << 5), // user partial specialized template
fIsForwardDeclaration = (1 << 6), // forward declaration
fIsVariadic = (1 << 7), // variadic template
fIsFriend = (1 << 8), // friend template
fFamilyMask = (fIsClass | fIsFunction | fIsVariable)
};
void isClass(bool state) {
setFlag(fIsClass, state);
}
void isFunction(bool state) {
setFlag(fIsFunction, state);
}
void isVariable(bool state) {
setFlag(fIsVariable, state);
}
void isAlias(bool state) {
setFlag(fIsAlias, state);
}
void isSpecialization(bool state) {
setFlag(fIsSpecialization, state);
}
void isPartialSpecialization(bool state) {
setFlag(fIsPartialSpecialization, state);
}
void isForwardDeclaration(bool state) {
setFlag(fIsForwardDeclaration, state);
}
void isVariadic(bool state) {
setFlag(fIsVariadic, state);
}
void isFriend(bool state) {
setFlag(fIsFriend, state);
}
/**
* Get specified flag state.
* @param flag flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag) const {
return ((mFlags & flag) != 0);
}
/**
* Set specified flag state.
* @param flag flag to set state
* @param state new state of flag
*/
void setFlag(unsigned int flag, bool state) {
mFlags = state ? mFlags | flag : mFlags & ~flag;
}
public:
/**
* Constructor used for instantiations.
* \param token template instantiation name token "name<...>"
* \param scope full qualification of template(scope)
*/
TokenAndName(Token *token, std::string scope);
/**
* Constructor used for declarations.
* \param token template declaration token "template < ... >"
* \param scope full qualification of template(scope)
* \param nameToken template name token "template < ... > class name"
* \param paramEnd template parameter end token ">"
*/
TokenAndName(Token *token, std::string scope, const Token *nameToken, const Token *paramEnd);
TokenAndName(const TokenAndName& other);
~TokenAndName();
bool operator == (const TokenAndName & rhs) const {
return mToken == rhs.mToken && mScope == rhs.mScope && mName == rhs.mName && mFullName == rhs.mFullName &&
mNameToken == rhs.mNameToken && mParamEnd == rhs.mParamEnd && mFlags == rhs.mFlags;
}
std::string dump(const std::vector<std::string>& fileNames) const;
// TODO: do not return non-const pointer from const object
Token * token() const {
return mToken;
}
void token(Token * token) {
mToken = token;
}
const std::string & scope() const {
return mScope;
}
const std::string & name() const {
return mName;
}
const std::string & fullName() const {
return mFullName;
}
const Token * nameToken() const {
return mNameToken;
}
const Token * paramEnd() const {
return mParamEnd;
}
void paramEnd(const Token *end) {
mParamEnd = end;
}
bool isClass() const {
return getFlag(fIsClass);
}
bool isFunction() const {
return getFlag(fIsFunction);
}
bool isVariable() const {
return getFlag(fIsVariable);
}
bool isAlias() const {
return getFlag(fIsAlias);
}
bool isSpecialization() const {
return getFlag(fIsSpecialization);
}
bool isPartialSpecialization() const {
return getFlag(fIsPartialSpecialization);
}
bool isForwardDeclaration() const {
return getFlag(fIsForwardDeclaration);
}
bool isVariadic() const {
return getFlag(fIsVariadic);
}
bool isFriend() const {
return getFlag(fIsFriend);
}
/**
* Get alias start token.
* template < ... > using X = foo < ... >;
* ^
* @return alias start token
*/
const Token * aliasStartToken() const;
/**
* Get alias end token.
* template < ... > using X = foo < ... >;
* ^
* @return alias end token
*/
const Token * aliasEndToken() const;
/**
* Is token an alias token?
* template < ... > using X = foo < ... >;
* ^
* @param tok token to check
* @return true if alias token, false if not
*/
bool isAliasToken(const Token *tok) const;
/**
* Is declaration the same family (class, function or variable).
*
* @param decl declaration to compare to
* @return true if same family, false if different family
*/
bool isSameFamily(const TemplateSimplifier::TokenAndName &decl) const {
// Make sure a family flag is set and matches.
// This works because at most only one flag will be set.
return ((mFlags & fFamilyMask) && (decl.mFlags & fFamilyMask));
}
};
/**
* Find last token of a template declaration.
* @param tok start token of declaration "template" or token after "template < ... >"
* @return last token of declaration or nullptr if syntax error
*/
static Token *findTemplateDeclarationEnd(Token *tok);
static const Token *findTemplateDeclarationEnd(const Token *tok);
/**
* Match template declaration/instantiation
* @param instance template instantiation
* @param numberOfArguments number of template arguments
* @param variadic last template argument is variadic
* @param patternAfter pattern that must match the tokens after the ">"
* @return match => true
*/
static bool instantiateMatch(const Token *instance, std::size_t numberOfArguments, bool variadic, const char patternAfter[]);
/**
* Match template declaration/instantiation
* @param tok The ">" token e.g. before "class"
* @return -1 to bail out or positive integer to identity the position
* of the template name.
*/
int getTemplateNamePosition(const Token *tok);
/**
* Get class template name position
* @param tok The ">" token e.g. before "class"
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateClass(const Token *tok, int &namepos);
/**
* Get function template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateFunction(const Token *tok, int &namepos);
/**
* Get variable template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateVariable(const Token *tok, int &namepos);
/**
* Simplify templates
* @param maxtime time when the simplification should be stopped
*/
void simplifyTemplates(std::time_t maxtime);
/**
* Simplify constant calculations such as "1+2" => "3"
* @param tok start token
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
static bool simplifyNumericCalculations(Token *tok, bool isTemplate = true);
/**
* Simplify constant calculations such as "1+2" => "3".
* This also performs simple cleanup of parentheses etc.
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
bool simplifyCalculations(Token* frontToken = nullptr, const Token *backToken = nullptr, bool isTemplate = true);
/** Simplify template instantiation arguments.
* @param start first token of arguments
* @param end token following last argument token
*/
void simplifyTemplateArgs(Token *start, const Token *end, std::vector<newInstantiation>* newInst = nullptr);
private:
/**
* Get template declarations
* @return true if code has templates.
*/
bool getTemplateDeclarations();
/** Add template instantiation.
* @param token first token of instantiation
* @param scope scope of instantiation
*/
void addInstantiation(Token *token, const std::string &scope);
/**
* Get template instantiations
*/
void getTemplateInstantiations();
/**
* Fix forward declared default argument values by copying them
* when they are not present in the declaration.
*/
void fixForwardDeclaredDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
*/
void useDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
* @param declaration template declaration or forward declaration
*/
void useDefaultArgumentValues(TokenAndName &declaration);
/**
* Try to locate a matching declaration for each user defined
* specialization.
*/
void getSpecializations();
/**
* Try to locate a matching declaration for each user defined
* partial specialization.
*/
void getPartialSpecializations();
/**
* simplify template aliases
*/
void simplifyTemplateAliases();
/**
* Simplify templates : expand all instantiations for a template
* @todo It seems that inner templates should be instantiated recursively
* @param templateDeclaration template declaration
* @param specializations template specializations (list each template name token)
* @param maxtime time when the simplification will stop
* @param expandedtemplates all templates that has been expanded so far. The full names are stored.
* @return true if the template was instantiated
*/
bool simplifyTemplateInstantiations(
const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations,
std::time_t maxtime,
std::set<std::string> &expandedtemplates);
/**
* Simplify templates : add namespace to template name
* @param templateDeclaration template declaration
* @param tok place to insert namespace
*/
void addNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Simplify templates : check if namespace already present
* @param templateDeclaration template declaration
* @param tok place to start looking for namespace
* @return true if namespace already present
*/
static bool alreadyHasNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Expand a template. Create "expanded" class/function at end of tokenlist.
* @param templateDeclaration Template declaration information
* @param templateInstantiation Full name of template
* @param typeParametersInDeclaration The type parameters of the template
* @param newName New name of class/function.
* @param copy copy or expand in place
*/
void expandTemplate(
const TokenAndName &templateDeclaration,
const TokenAndName &templateInstantiation,
const std::vector<const Token *> &typeParametersInDeclaration,
const std::string &newName,
bool copy);
/**
* Replace all matching template usages 'Foo < int >' => 'Foo<int>'
* @param instantiation Template instantiation information.
* @param typeStringsUsedInTemplateInstantiation template parameters. list of token strings.
* @param newName The new type name
*/
void replaceTemplateUsage(const TokenAndName &instantiation,
const std::list<std::string> &typeStringsUsedInTemplateInstantiation,
const std::string &newName);
/**
* @brief TemplateParametersInDeclaration
* @param tok template < typename T, typename S >
* ^ tok
* @param typeParametersInDeclaration template < typename T, typename S >
* ^ [0] ^ [1]
*/
static void getTemplateParametersInDeclaration(
const Token * tok,
std::vector<const Token *> & typeParametersInDeclaration);
/**
* Remove a specific "template < ..." template class/function
*/
static bool removeTemplate(Token *tok, std::map<Token*, Token*>* forwardDecls = nullptr);
/** Syntax error */
NORETURN static void syntaxError(const Token *tok);
static bool matchSpecialization(
const Token *templateDeclarationNameToken,
const Token *templateInstantiationNameToken,
const std::list<const Token *> & specializations);
/*
* Same as Token::eraseTokens() but tries to fix up lists with pointers to the deleted tokens.
* @param begin Tokens after this will be erased.
* @param end Tokens before this will be erased.
*/
static void eraseTokens(Token *begin, const Token *end);
/**
* Delete specified token without invalidating pointer to following token.
* tok will be invalidated.
* @param tok token to delete
*/
static void deleteToken(Token *tok);
/**
* Get the new token name.
* @param tok2 name token
* @param typeStringsUsedInTemplateInstantiation type strings use in template instantiation
* @return new token name
*/
std::string getNewName(
Token *tok2,
std::list<std::string> &typeStringsUsedInTemplateInstantiation);
void printOut(
const TokenAndName &tokenAndName,
const std::string &indent = " ") const;
void printOut(const std::string &text = emptyString) const;
Tokenizer &mTokenizer;
TokenList &mTokenList;
const Settings &mSettings;
ErrorLogger &mErrorLogger;
bool mChanged{};
std::list<TokenAndName> mTemplateDeclarations;
std::list<TokenAndName> mTemplateForwardDeclarations;
std::map<Token *, Token *> mTemplateForwardDeclarationsMap;
std::map<Token *, Token *> mTemplateSpecializationMap;
std::map<Token *, Token *> mTemplatePartialSpecializationMap;
std::list<TokenAndName> mTemplateInstantiations;
std::list<TokenAndName> mInstantiatedTemplates;
std::list<TokenAndName> mMemberFunctionsToDelete;
std::vector<TokenAndName> mExplicitInstantiationsToDelete;
std::vector<TokenAndName> mTypesUsedInTemplateInstantiation;
std::unordered_map<const Token*, int> mTemplateNamePos;
std::string mDump;
};
/// @}
//---------------------------------------------------------------------------
#endif // templatesimplifierH
| 18,114
|
C++
|
.h
| 457
| 32.363239
| 129
| 0.626243
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,385
|
vf_subfunction.h
|
danmar_cppcheck/lib/vf_subfunction.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfSubFunctionH
#define vfSubFunctionH
class TokenList;
class SymbolDatabase;
class ErrorLogger;
class Settings;
namespace ValueFlow
{
void analyzeSubFunction(const TokenList& tokenlist, SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings);
}
#endif // vfSubFunctionH
| 1,076
|
C++
|
.h
| 28
| 36.571429
| 140
| 0.773946
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,386
|
calculate.h
|
danmar_cppcheck/lib/calculate.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef calculateH
#define calculateH
#include "mathlib.h"
#include "errortypes.h"
#include <limits>
#include <string>
template<class T>
bool isEqual(T x, T y)
{
return x == y;
}
inline bool isEqual(double x, double y)
{
const double diff = (x > y) ? x - y : y - x;
return !((diff / 2) < diff);
}
inline bool isEqual(float x, float y)
{
return isEqual(double(x), double(y));
}
template<class T>
bool isZero(T x)
{
return isEqual(x, T(0));
}
template<class R, class T>
R calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
{
auto wrap = [](T z) {
return R{z};
};
constexpr MathLib::bigint maxBitsShift = sizeof(MathLib::bigint) * 8;
// For portability we cannot shift signed integers by 63 bits
constexpr MathLib::bigint maxBitsSignedShift = maxBitsShift - 1;
switch (MathLib::encodeMultiChar(s)) {
case '+':
return wrap(x + y);
case '-':
return wrap(x - y);
case '*':
return wrap(x * y);
case '/':
if (isZero(y) || (std::is_integral<T>{} && std::is_signed<T>{} && isEqual(y, T(-1)) && isEqual(x, std::numeric_limits<T>::min()))) {
if (error)
*error = true;
return R{};
}
return wrap(x / y);
case '%':
if (isZero(MathLib::bigint(y)) || (std::is_integral<T>{} && std::is_signed<T>{} && isEqual(y, T(-1)) && isEqual(x, std::numeric_limits<T>::min()))) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) % MathLib::bigint(y));
case '&':
return wrap(MathLib::bigint(x) & MathLib::bigint(y));
case '|':
return wrap(MathLib::bigint(x) | MathLib::bigint(y));
case '^':
return wrap(MathLib::bigint(x) ^ MathLib::bigint(y));
case '>':
return wrap(x > y);
case '<':
return wrap(x < y);
case '<<':
if (y >= maxBitsSignedShift || y < 0 || x < 0) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) << MathLib::bigint(y));
case '>>':
if (y >= maxBitsSignedShift || y < 0 || x < 0) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) >> MathLib::bigint(y));
case '&&':
return wrap(!isZero(x) && !isZero(y));
case '||':
return wrap(!isZero(x) || !isZero(y));
case '==':
return wrap(isEqual(x, y));
case '!=':
return wrap(!isEqual(x, y));
case '>=':
return wrap(x >= y);
case '<=':
return wrap(x <= y);
case '<=>':
return wrap(x - y);
}
throw InternalError(nullptr, "Unknown operator: " + s);
}
template<class T>
T calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
{
return calculate<T, T>(s, x, y, error);
}
#endif
| 3,705
|
C++
|
.h
| 119
| 25.596639
| 157
| 0.576579
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,387
|
filesettings.h
|
danmar_cppcheck/lib/filesettings.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef fileSettingsH
#define fileSettingsH
#include "config.h"
#include "path.h"
#include "platform.h"
#include <list>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
class FileWithDetails
{
public:
explicit FileWithDetails(std::string path)
: FileWithDetails(std::move(path), 0)
{}
FileWithDetails(std::string path, std::size_t size)
: mPath(std::move(path))
, mPathSimplified(Path::simplifyPath(mPath))
, mSize(size)
{
if (mPath.empty())
throw std::runtime_error("empty path specified");
}
const std::string& path() const
{
return mPath;
}
const std::string& spath() const
{
return mPathSimplified;
}
std::size_t size() const
{
return mSize;
}
private:
std::string mPath;
std::string mPathSimplified;
std::size_t mSize;
};
/** File settings. Multiple configurations for a file is allowed. */
struct CPPCHECKLIB FileSettings {
explicit FileSettings(std::string path)
: file(std::move(path))
{}
FileSettings(std::string path, std::size_t size)
: file(std::move(path), size)
{}
std::string cfg;
FileWithDetails file;
const std::string& filename() const
{
return file.path();
}
// cppcheck-suppress unusedFunction
const std::string& sfilename() const
{
return file.spath();
}
std::string defines;
// TODO: handle differently
std::string cppcheckDefines() const {
return defines + (msc ? ";_MSC_VER=1900" : "") + (useMfc ? ";__AFXWIN_H__=1" : "");
}
std::set<std::string> undefs;
std::list<std::string> includePaths;
// only used by clang mode
std::list<std::string> systemIncludePaths;
std::string standard;
Platform::Type platformType = Platform::Type::Unspecified;
// TODO: get rid of these
bool msc{};
bool useMfc{};
};
#endif // fileSettingsH
| 2,733
|
C++
|
.h
| 93
| 24.989247
| 91
| 0.667808
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,388
|
valueflow.h
|
danmar_cppcheck/lib/valueflow.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef valueflowH
#define valueflowH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include "vfvalue.h"
#include <cstdlib>
#include <functional>
#include <list>
#include <string>
#include <utility>
#include <vector>
class ErrorLogger;
class Settings;
class SymbolDatabase;
class TimerResultsIntf;
class Token;
class TokenList;
class ValueType;
class Variable;
class Scope;
namespace ValueFlow {
/// Constant folding of expression. This can be used before the full ValueFlow has been executed (ValueFlow::setValues).
const Value * valueFlowConstantFoldAST(Token *expr, const Settings &settings);
/// Perform valueflow analysis.
void setValues(TokenList& tokenlist,
SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
TimerResultsIntf* timerResults);
std::string eitherTheConditionIsRedundant(const Token *condition);
size_t getSizeOf(const ValueType &vt, const Settings &settings, int maxRecursion = 0);
const Value* findValue(const std::list<Value>& values,
const Settings& settings,
const std::function<bool(const Value&)> &pred);
std::vector<Value> isOutOfBounds(const Value& size, const Token* indexTok, bool possible = true);
Value asImpossible(Value v);
bool isContainerSizeChanged(const Token* tok, int indirect, const Settings& settings, int depth = 20);
struct LifetimeToken {
const Token* token{};
ErrorPath errorPath;
bool addressOf{};
bool inconclusive{};
LifetimeToken() = default;
LifetimeToken(const Token* token, ErrorPath errorPath)
: token(token), errorPath(std::move(errorPath))
{}
LifetimeToken(const Token* token, bool addressOf, ErrorPath errorPath)
: token(token), errorPath(std::move(errorPath)), addressOf(addressOf)
{}
static std::vector<LifetimeToken> setAddressOf(std::vector<LifetimeToken> v, bool b) {
for (LifetimeToken& x : v)
x.addressOf = b;
return v;
}
static std::vector<LifetimeToken> setInconclusive(std::vector<LifetimeToken> v, bool b) {
for (LifetimeToken& x : v)
x.inconclusive = b;
return v;
}
};
const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value, const std::function<std::vector<MathLib::bigint>(const Token*)>& evaluate);
const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value);
const Token* solveExprValue(const Token* expr,
const std::function<std::vector<MathLib::bigint>(const Token*)>& eval,
Value& value);
std::vector<LifetimeToken> getLifetimeTokens(const Token* tok,
const Settings& settings,
bool escape = false,
ErrorPath errorPath = ErrorPath{});
bool hasLifetimeToken(const Token* tok, const Token* lifetime, const Settings& settings);
const Variable* getLifetimeVariable(const Token* tok, ErrorPath& errorPath, const Settings& settings, bool* addressOf = nullptr);
const Variable* getLifetimeVariable(const Token* tok, const Settings& settings);
bool isLifetimeBorrowed(const Token *tok, const Settings &settings);
std::string lifetimeMessage(const Token *tok, const Value *val, ErrorPath &errorPath);
CPPCHECKLIB Value getLifetimeObjValue(const Token *tok, bool inconclusive = false);
CPPCHECKLIB std::vector<Value> getLifetimeObjValues(const Token* tok,
bool inconclusive = false,
MathLib::bigint path = 0);
const Token* getEndOfExprScope(const Token* tok, const Scope* defaultScope = nullptr, bool smallest = true);
void combineValueProperties(const Value& value1, const Value& value2, Value& result);
}
#endif // valueflowH
| 5,112
|
C++
|
.h
| 102
| 41.196078
| 165
| 0.643503
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,389
|
checkio.h
|
danmar_cppcheck/lib/checkio.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkioH
#define checkioH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <cstdint>
#include <ostream>
#include <string>
class Function;
class Settings;
class Token;
class Variable;
class ErrorLogger;
enum class Severity : std::uint8_t;
/// @addtogroup Checks
/// @{
/** @brief %Check input output operations. */
class CPPCHECKLIB CheckIO : public Check {
friend class TestIO;
public:
/** @brief This constructor is used when registering CheckIO */
CheckIO() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckIO(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckIO checkIO(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkIO.checkWrongPrintfScanfArguments();
checkIO.checkCoutCerrMisusage();
checkIO.checkFileUsage();
checkIO.invalidScanf();
}
/** @brief %Check for missusage of std::cout */
void checkCoutCerrMisusage();
/** @brief %Check usage of files*/
void checkFileUsage();
/** @brief scanf can crash if width specifiers are not used */
void invalidScanf();
/** @brief %Checks type and number of arguments given to functions like printf or scanf*/
void checkWrongPrintfScanfArguments();
class ArgumentInfo {
public:
ArgumentInfo(const Token *arg, const Settings &settings, bool _isCPP);
~ArgumentInfo();
ArgumentInfo(const ArgumentInfo &) = delete;
ArgumentInfo& operator= (const ArgumentInfo &) = delete;
bool isArrayOrPointer() const;
bool isComplexType() const;
bool isKnownType() const;
bool isStdVectorOrString();
bool isStdContainer(const Token *tok);
bool isLibraryType(const Settings &settings) const;
const Variable* variableInfo{};
const Token* typeToken{};
const Function* functionInfo{};
Token* tempToken{};
bool element{};
bool _template{};
bool address{};
bool isCPP{};
};
void checkFormatString(const Token * tok,
const Token * formatStringTok,
const Token * argListTok,
bool scan,
bool scanf_s);
// Reporting errors..
void coutCerrMisusageError(const Token* tok, const std::string& streamName);
void fflushOnInputStreamError(const Token *tok, const std::string &varname);
void ioWithoutPositioningError(const Token *tok);
void readWriteOnlyFileError(const Token *tok);
void writeReadOnlyFileError(const Token *tok);
void useClosedFileError(const Token *tok);
void seekOnAppendedFileError(const Token *tok);
void incompatibleFileOpenError(const Token *tok, const std::string &filename);
void invalidScanfError(const Token *tok);
void wrongPrintfScanfArgumentsError(const Token* tok,
const std::string &functionName,
nonneg int numFormat,
nonneg int numFunction);
void wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName,
nonneg int index, nonneg int numFunction);
void invalidScanfArgTypeError_s(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidScanfArgTypeError_int(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned);
void invalidScanfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_s(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_n(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_p(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_uint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_sint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidLengthModifierError(const Token* tok, nonneg int numFormat, const std::string& modifier);
void invalidScanfFormatWidthError(const Token* tok, nonneg int numFormat, int width, const Variable *var, const std::string& specifier);
static void argumentType(std::ostream & os, const ArgumentInfo * argInfo);
static Severity getSeverity(const ArgumentInfo *argInfo);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckIO c(nullptr, settings, errorLogger);
c.coutCerrMisusageError(nullptr, "cout");
c.fflushOnInputStreamError(nullptr, "stdin");
c.ioWithoutPositioningError(nullptr);
c.readWriteOnlyFileError(nullptr);
c.writeReadOnlyFileError(nullptr);
c.useClosedFileError(nullptr);
c.seekOnAppendedFileError(nullptr);
c.incompatibleFileOpenError(nullptr, "tmp");
c.invalidScanfError(nullptr);
c.wrongPrintfScanfArgumentsError(nullptr, "printf",3,2);
c.invalidScanfArgTypeError_s(nullptr, 1, "s", nullptr);
c.invalidScanfArgTypeError_int(nullptr, 1, "d", nullptr, false);
c.invalidScanfArgTypeError_float(nullptr, 1, "f", nullptr);
c.invalidPrintfArgTypeError_s(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_n(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_p(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_uint(nullptr, 1, "u", nullptr);
c.invalidPrintfArgTypeError_sint(nullptr, 1, "i", nullptr);
c.invalidPrintfArgTypeError_float(nullptr, 1, "f", nullptr);
c.invalidLengthModifierError(nullptr, 1, "I");
c.invalidScanfFormatWidthError(nullptr, 10, 5, nullptr, "s");
c.invalidScanfFormatWidthError(nullptr, 99, -1, nullptr, "s");
c.wrongPrintfScanfPosixParameterPositionError(nullptr, "printf", 2, 1);
}
static std::string myName() {
return "IO using format string";
}
std::string classInfo() const override {
return "Check format string input/output operations.\n"
"- Bad usage of the function 'sprintf' (overlapping data)\n"
"- Missing or wrong width specifiers in 'scanf' format string\n"
"- Use a file that has been closed\n"
"- File input/output without positioning results in undefined behaviour\n"
"- Read to a file that has only been opened for writing (or vice versa)\n"
"- Repositioning operation on a file opened in append mode\n"
"- The same file can't be open for read and write at the same time on different streams\n"
"- Using fflush() on an input stream\n"
"- Invalid usage of output stream. For example: 'std::cout << std::cout;'\n"
"- Wrong number of arguments given to 'printf' or 'scanf;'\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkioH
| 8,641
|
C++
|
.h
| 162
| 45.709877
| 154
| 0.672658
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,391
|
pathanalysis.h
|
danmar_cppcheck/lib/pathanalysis.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GUARD_PATHANALYSIS_H
#define GUARD_PATHANALYSIS_H
#include "errortypes.h"
#include <cstdint>
#include <functional>
#include <list>
#include <utility>
class Library;
class Scope;
class Token;
struct PathAnalysis {
enum class Progress : std::uint8_t {
Continue,
Break
};
PathAnalysis(const Token* start, const Library& library)
: start(start), library(&library)
{}
const Token * start;
const Library * library;
struct Info {
const Token* tok;
ErrorPath errorPath;
bool known;
};
void forward(const std::function<Progress(const Info&)>& f) const;
Info forwardFind(std::function<bool(const Info&)> pred) const {
Info result{};
forward([&](const Info& info) {
if (pred(info)) {
result = info;
return Progress::Break;
}
return Progress::Continue;
});
return result;
}
private:
static Progress forwardRecursive(const Token* tok, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f);
Progress forwardRange(const Token* startToken, const Token* endToken, Info info, const std::function<Progress(const Info&)>& f) const;
static const Scope* findOuterScope(const Scope * scope);
static std::pair<bool, bool> checkCond(const Token * tok, bool& known);
};
/**
* @brief Returns true if there is a path between the two tokens
*
* @param start Starting point of the path
* @param dest The path destination
* @param errorPath Adds the path traversal to the errorPath
*/
bool reaches(const Token * start, const Token * dest, const Library& library, ErrorPath* errorPath);
#endif
| 2,478
|
C++
|
.h
| 69
| 31.376812
| 138
| 0.694363
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,392
|
checktype.h
|
danmar_cppcheck/lib/checktype.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checktypeH
#define checktypeH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <string>
class ErrorLogger;
class Settings;
class Token;
class ValueType;
/// @addtogroup Checks
/// @{
/** @brief Various small checks */
class CPPCHECKLIB CheckType : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckType() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckType(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
// These are not "simplified" because casts can't be ignored
CheckType checkType(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkType.checkTooBigBitwiseShift();
checkType.checkIntegerOverflow();
checkType.checkSignConversion();
checkType.checkLongCast();
checkType.checkFloatToIntegerOverflow();
}
/** @brief %Check for bitwise shift with too big right operand */
void checkTooBigBitwiseShift();
/** @brief %Check for integer overflow */
void checkIntegerOverflow();
/** @brief %Check for dangerous sign conversion */
void checkSignConversion();
/** @brief %Check for implicit long cast of int result */
void checkLongCast();
/** @brief %Check for float to integer overflow */
void checkFloatToIntegerOverflow();
void checkFloatToIntegerOverflow(const Token *tok, const ValueType *vtint, const ValueType *vtfloat, const std::list<ValueFlow::Value> &floatValues);
// Error messages..
void tooBigBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits);
void tooBigSignedBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits);
void integerOverflowError(const Token *tok, const ValueFlow::Value &value);
void signConversionError(const Token *tok, const ValueFlow::Value *negativeValue, bool constvalue);
void longCastAssignError(const Token *tok, const ValueType* src = nullptr, const ValueType* tgt = nullptr);
void longCastReturnError(const Token *tok, const ValueType* src = nullptr, const ValueType* tgt = nullptr);
void floatToIntegerOverflowError(const Token *tok, const ValueFlow::Value &value);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckType c(nullptr, settings, errorLogger);
c.tooBigBitwiseShiftError(nullptr, 32, ValueFlow::Value(64));
c.tooBigSignedBitwiseShiftError(nullptr, 31, ValueFlow::Value(31));
c.integerOverflowError(nullptr, ValueFlow::Value(1LL<<32));
c.signConversionError(nullptr, nullptr, false);
c.longCastAssignError(nullptr);
c.longCastReturnError(nullptr);
ValueFlow::Value f;
f.valueType = ValueFlow::Value::ValueType::FLOAT;
f.floatValue = 1E100;
c.floatToIntegerOverflowError(nullptr, f);
}
static std::string myName() {
return "Type";
}
std::string classInfo() const override {
return "Type checks\n"
"- bitwise shift by too many bits (only enabled when --platform is used)\n"
"- signed integer overflow (only enabled when --platform is used)\n"
"- dangerous sign conversion, when signed value can be negative\n"
"- possible loss of information when assigning int result to long variable\n"
"- possible loss of information when returning int result as long return value\n"
"- float conversion overflow\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checktypeH
| 4,877
|
C++
|
.h
| 100
| 43.55
| 153
| 0.680681
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,393
|
vf_sameexpressions.h
|
danmar_cppcheck/lib/vf_sameexpressions.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfSameExpressionsH
#define vfSameExpressionsH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeSameExpressions(TokenList &tokenlist, const Settings& settings);
}
#endif // vfSameExpressionsH
| 987
|
C++
|
.h
| 26
| 36.038462
| 80
| 0.76698
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,394
|
vf_common.h
|
danmar_cppcheck/lib/vf_common.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfCommonH
#define vfCommonH
#include "config.h"
#include "mathlib.h"
#include "sourcelocation.h"
#include "symboldatabase.h"
#include "vfvalue.h"
#include <cstddef>
#include <list>
#include <string>
class Token;
class Settings;
class Platform;
namespace ValueFlow
{
bool getMinMaxValues(const ValueType* vt, const Platform& platform, MathLib::bigint& minValue, MathLib::bigint& maxValue);
bool getMinMaxValues(const std::string &typestr, const Settings &settings, bool cpp, MathLib::bigint &minvalue, MathLib::bigint &maxvalue);
long long truncateIntValue(long long value, size_t value_size, const ValueType::Sign dst_sign);
Token * valueFlowSetConstantValue(Token *tok, const Settings &settings);
Value castValue(Value value, const ValueType::Sign sign, nonneg int bit);
std::string debugString(const Value& v);
void setSourceLocation(Value& v,
SourceLocation ctx,
const Token* tok,
SourceLocation local = SourceLocation::current());
std::list<Value> getIteratorValues(std::list<Value> values, const Value::ValueKind* kind = nullptr);
MathLib::bigint valueFlowGetStrLength(const Token* tok);
bool isBreakOrContinueScope(const Token* endToken);
const Scope* getLoopScope(const Token* tok);
void setSymbolic(Value& value, const Token* tok);
Value makeSymbolic(const Token* tok, MathLib::bigint delta = 0);
void removeImpossible(std::list<Value>& values, int indirect = -1);
void changeKnownToPossible(std::list<Value> &values, int indirect=-1);
void lowerToPossible(std::list<Value>& values, int indirect = -1);
}
#endif // vfCommonH
| 2,469
|
C++
|
.h
| 53
| 42.150943
| 143
| 0.730689
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,395
|
vf_conditionexpressions.h
|
danmar_cppcheck/lib/vf_conditionexpressions.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfConditionExpressionsH
#define vfConditionExpressionsH
class TokenList;
class SymbolDatabase;
class ErrorLogger;
class Settings;
namespace ValueFlow
{
void analyzeConditionExpressions(const TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings);
}
#endif // vfConditionExpressionsH
| 1,118
|
C++
|
.h
| 28
| 38.071429
| 155
| 0.781768
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,396
|
utils.h
|
danmar_cppcheck/lib/utils.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef utilsH
#define utilsH
//---------------------------------------------------------------------------
#include "config.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <limits>
#include <list>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
struct SelectMapKeys {
template<class Pair>
// NOLINTNEXTLINE(readability-const-return-type) - false positive
typename Pair::first_type operator()(const Pair& p) const {
return p.first;
}
};
struct SelectMapValues {
template<class Pair>
typename Pair::second_type operator()(const Pair& p) const {
return p.second;
}
};
struct OnExit {
std::function<void()> f;
~OnExit() {
f();
}
};
template<class Range, class T>
bool contains(const Range& r, const T& x)
{
return std::find(r.cbegin(), r.cend(), x) != r.cend();
}
template<class T>
bool contains(const std::initializer_list<T>& r, const T& x)
{
return std::find(r.begin(), r.end(), x) != r.end();
}
template<class T, class U>
bool contains(const std::initializer_list<T>& r, const U& x)
{
return std::find(r.begin(), r.end(), x) != r.end();
}
template<class T, class ... Ts>
inline std::array<T, sizeof...(Ts) + 1> makeArray(T x, Ts... xs)
{
return {std::move(x), std::move(xs)...};
}
// Enum hash for C++11. This is not needed in C++14
struct EnumClassHash {
template<typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
inline bool startsWith(const std::string& str, const char start[], std::size_t startlen)
{
return str.compare(0, startlen, start) == 0;
}
template<std::size_t N>
bool startsWith(const std::string& str, const char (&start)[N])
{
return startsWith(str, start, N - 1);
}
inline bool startsWith(const std::string& str, const std::string& start)
{
return startsWith(str, start.c_str(), start.length());
}
inline bool endsWith(const std::string &str, char c)
{
return !str.empty() && str.back() == c;
}
inline bool endsWith(const std::string &str, const char end[], std::size_t endlen)
{
return (str.size() >= endlen) && (str.compare(str.size()-endlen, endlen, end)==0);
}
template<std::size_t N>
bool endsWith(const std::string& str, const char (&end)[N])
{
return endsWith(str, end, N - 1);
}
inline static bool isPrefixStringCharLiteral(const std::string &str, char q, const std::string& p)
{
// str must be at least the prefix plus the start and end quote
if (str.length() < p.length() + 2)
return false;
// check for end quote
if (!endsWith(str, q))
return false;
// check for start quote
if (str[p.size()] != q)
return false;
// check for prefix
if (str.compare(0, p.size(), p) != 0)
return false;
return true;
}
inline static bool isStringCharLiteral(const std::string &str, char q)
{
// early out to avoid the loop
if (!endsWith(str, q))
return false;
static const std::array<std::string, 5> suffixes{"", "u8", "u", "U", "L"};
return std::any_of(suffixes.cbegin(), suffixes.cend(), [&](const std::string& p) {
return isPrefixStringCharLiteral(str, q, p);
});
}
inline static bool isStringLiteral(const std::string &str)
{
return isStringCharLiteral(str, '"');
}
inline static bool isCharLiteral(const std::string &str)
{
return isStringCharLiteral(str, '\'');
}
inline static std::string getStringCharLiteral(const std::string &str, char q)
{
const std::size_t quotePos = str.find(q);
return str.substr(quotePos + 1U, str.size() - quotePos - 2U);
}
inline static std::string getStringLiteral(const std::string &str)
{
if (isStringLiteral(str))
return getStringCharLiteral(str, '"');
return "";
}
inline static std::string getCharLiteral(const std::string &str)
{
if (isCharLiteral(str))
return getStringCharLiteral(str, '\'');
return "";
}
inline static const char *getOrdinalText(int i)
{
if (i == 1)
return "st";
if (i == 2)
return "nd";
if (i == 3)
return "rd";
return "th";
}
CPPCHECKLIB int caseInsensitiveStringCompare(const std::string& lhs, const std::string& rhs);
CPPCHECKLIB bool isValidGlobPattern(const std::string& pattern);
CPPCHECKLIB bool matchglob(const std::string& pattern, const std::string& name);
CPPCHECKLIB bool matchglobs(const std::vector<std::string> &patterns, const std::string &name);
CPPCHECKLIB void strTolower(std::string& str);
template<typename T, typename std::enable_if<std::is_signed<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
long long tmp;
try {
std::size_t idx = 0;
tmp = std::stoll(str, &idx);
if (idx != str.size()) {
if (err)
*err = "not an integer";
return false;
}
} catch (const std::out_of_range&) {
if (err)
*err = "out of range (stoll)";
return false;
} catch (const std::invalid_argument &) {
if (err)
*err = "not an integer";
return false;
}
if (str.front() == '-' && std::numeric_limits<T>::min() == 0) {
if (err)
*err = "needs to be positive";
return false;
}
if (tmp < std::numeric_limits<T>::min() || tmp > std::numeric_limits<T>::max()) {
if (err)
*err = "out of range (limits)";
return false;
}
num = static_cast<T>(tmp);
return true;
}
template<typename T, typename std::enable_if<std::is_unsigned<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
unsigned long long tmp;
try {
std::size_t idx = 0;
tmp = std::stoull(str, &idx);
if (idx != str.size()) {
if (err)
*err = "not an integer";
return false;
}
} catch (const std::out_of_range&) {
if (err)
*err = "out of range (stoull)";
return false;
} catch (const std::invalid_argument &) {
if (err)
*err = "not an integer";
return false;
}
if (str.front() == '-') {
if (err)
*err = "needs to be positive";
return false;
}
if (tmp > std::numeric_limits<T>::max()) {
if (err)
*err = "out of range (limits)";
return false;
}
num = tmp;
return true;
}
template<typename T>
T strToInt(const std::string& str)
{
T tmp = 0;
std::string err;
if (!strToInt(str, tmp, &err))
throw std::runtime_error("converting '" + str + "' to integer failed - " + err);
return tmp;
}
/**
* Simple helper function:
* \return size of array
* */
template<typename T, int size>
// cppcheck-suppress unusedFunction - only used in conditional code
std::size_t getArrayLength(const T (& /*unused*/)[size])
{
return size;
}
/**
* @brief get id string. i.e. for dump files
* it will be a hexadecimal output.
*/
static inline std::string id_string_i(std::uintptr_t l)
{
if (!l)
return "0";
static constexpr int ptr_size = sizeof(void*);
// two characters of each byte / contains terminating \0
static constexpr int buf_size = (ptr_size * 2) + 1;
char buf[buf_size];
// needs to be signed so we don't underflow in padding loop
int idx = buf_size - 1;
buf[idx] = '\0';
while (l != 0)
{
char c;
const std::uintptr_t temp = l % 16; // get the remainder
if (temp < 10) {
// 0-9
c = '0' + temp;
}
else {
// a-f
c = 'a' + (temp - 10);
}
buf[--idx] = c; // store in reverse order
l = l / 16;
}
return &buf[idx];
}
static inline std::string id_string(const void* p)
{
return id_string_i(reinterpret_cast<std::uintptr_t>(p));
}
static inline const char* bool_to_string(bool b)
{
return b ? "true" : "false";
}
/**
* Remove heading and trailing whitespaces from the input parameter.
* If string is all spaces/tabs, return empty string.
* @param s The string to trim.
* @param t The characters to trim.
*/
CPPCHECKLIB std::string trim(const std::string& s, const std::string& t = " \t");
/**
* Replace all occurrences of searchFor with replaceWith in the
* given source.
* @param source The string to modify
* @param searchFor What should be searched for
* @param replaceWith What will replace the found item
*/
CPPCHECKLIB void findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith);
/**
* Replace all escape sequences in the given string.
* @param source The string that contains escape sequences
*/
CPPCHECKLIB std::string replaceEscapeSequences(const std::string &source);
namespace cppcheck
{
NORETURN inline void unreachable()
{
#if defined(__GNUC__)
__builtin_unreachable();
#elif defined(_MSC_VER)
__assume(false);
#else
#error "no unreachable implementation"
#endif
}
}
template<typename T>
static inline T* default_if_null(T* p, T* def)
{
return p ? p : def;
}
template<typename T>
static inline T* empty_if_null(T* p)
{
return default_if_null(p, "");
}
/**
* Split string by given sperator.
* @param str The string to split
* @param sep The seperator
* @return The list of seperate strings (including empty ones). The whole input string if no seperator found.
*/
CPPCHECKLIB std::list<std::string> splitString(const std::string& str, char sep);
namespace utils {
template<class T>
constexpr typename std::add_const<T>::type & as_const(T& t) noexcept
{
return t;
}
}
#endif
| 10,649
|
C++
|
.h
| 358
| 25.564246
| 115
| 0.6309
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,397
|
standards.h
|
danmar_cppcheck/lib/standards.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef standardsH
#define standardsH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <string>
/// @addtogroup Core
/// @{
/**
* @brief This is just a container for standards settings.
* This struct contains all possible standards that cppcheck recognize.
*/
struct CPPCHECKLIB Standards {
enum Language : std::uint8_t { None, C, CPP };
/** C code standard */
enum cstd_t : std::uint8_t { C89, C99, C11, C17, C23, CLatest = C23 } c = CLatest;
/** C++ code standard */
enum cppstd_t : std::uint8_t { CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPP26, CPPLatest = CPP26 } cpp = CPPLatest;
/** --std value given on command line */
std::string stdValueC;
/** --std value given on command line */
std::string stdValueCPP;
bool setC(std::string str);
std::string getC() const;
static std::string getC(cstd_t c_std);
static cstd_t getC(const std::string &std);
bool setCPP(std::string str);
std::string getCPP() const;
static std::string getCPP(cppstd_t std);
static cppstd_t getCPP(const std::string &std);
bool setStd(const std::string& str);
};
/// @}
//---------------------------------------------------------------------------
#endif // standardsH
| 2,150
|
C++
|
.h
| 53
| 37.622642
| 120
| 0.621583
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,398
|
vf_unknownfunctionreturn.h
|
danmar_cppcheck/lib/vf_unknownfunctionreturn.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfUnknownFunctionReturnH
#define vfUnknownFunctionReturnH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeUnknownFunctionReturn(TokenList &tokenlist, const Settings &settings);
}
#endif // vfUnknownFunctionReturnH
| 1,011
|
C++
|
.h
| 26
| 36.961538
| 86
| 0.772681
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,399
|
valueptr.h
|
danmar_cppcheck/lib/valueptr.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef valueptrH
#define valueptrH
//---------------------------------------------------------------------------
#include "config.h"
#include <memory>
template<class T>
class CPPCHECKLIB ValuePtr {
template<class U>
struct cloner {
static T* apply(const T* x) {
return new U(*static_cast<const U*>(x));
}
};
public:
using pointer = T*;
using element_type = T;
using cloner_type = decltype(&cloner<T>::apply);
ValuePtr() : mPtr(nullptr), mClone() {}
template<class U>
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
ValuePtr(const U& value) : mPtr(cloner<U>::apply(&value)), mClone(&cloner<U>::apply)
{}
ValuePtr(const ValuePtr& rhs) : mPtr(nullptr), mClone(rhs.mClone) {
if (rhs) {
mPtr.reset(mClone(rhs.get()));
}
}
ValuePtr(ValuePtr&& rhs) NOEXCEPT : mPtr(std::move(rhs.mPtr)), mClone(std::move(rhs.mClone)) {}
T* get() NOEXCEPT {
return mPtr.get();
}
const T* get() const NOEXCEPT {
return mPtr.get();
}
T& operator*() {
return *get();
}
const T& operator*() const {
return *get();
}
T* operator->() NOEXCEPT {
return get();
}
const T* operator->() const NOEXCEPT {
return get();
}
void swap(ValuePtr& rhs) NOEXCEPT {
using std::swap;
swap(mPtr, rhs.mPtr);
swap(mClone, rhs.mClone);
}
ValuePtr<T>& operator=(ValuePtr rhs) & {
swap(rhs);
return *this;
}
// NOLINTNEXTLINE(google-explicit-constructor)
operator bool() const NOEXCEPT {
return !!mPtr;
}
private:
std::shared_ptr<T> mPtr;
cloner_type mClone;
};
#endif
| 2,612
|
C++
|
.h
| 83
| 26.518072
| 99
| 0.601671
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,400
|
vf_infercondition.h
|
danmar_cppcheck/lib/vf_infercondition.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfInferConditionH
#define vfInferConditionH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeInferCondition(TokenList& tokenlist, const Settings& settings);
}
#endif // vfInferConditionH
| 983
|
C++
|
.h
| 26
| 35.884615
| 79
| 0.766002
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,401
|
checkpostfixoperator.h
|
danmar_cppcheck/lib/checkpostfixoperator.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkpostfixoperatorH
#define checkpostfixoperatorH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Using postfix operators ++ or -- rather than postfix operator.
*/
class CPPCHECKLIB CheckPostfixOperator : public Check {
friend class TestPostfixOperator;
public:
/** This constructor is used when registering the CheckPostfixOperator */
CheckPostfixOperator() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckPostfixOperator(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckPostfixOperator checkPostfixOperator(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkPostfixOperator.postfixOperator();
}
/** Check postfix operators */
void postfixOperator();
/** Report Error */
void postfixOperatorError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckPostfixOperator c(nullptr, settings, errorLogger);
c.postfixOperatorError(nullptr);
}
static std::string myName() {
return "Using postfix operators";
}
std::string classInfo() const override {
return "Warn if using postfix operators ++ or -- rather than prefix operator\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkpostfixoperatorH
| 2,668
|
C++
|
.h
| 66
| 36.712121
| 104
| 0.66499
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,402
|
checkstl.h
|
danmar_cppcheck/lib/checkstl.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkstlH
#define checkstlH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <cstdint>
#include <string>
class Scope;
class Settings;
class Token;
class Variable;
class ErrorLogger;
/// @addtogroup Checks
/// @{
/** @brief %Check STL usage (invalidation of iterators, mismatching containers, etc) */
class CPPCHECKLIB CheckStl : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckStl() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckStl(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** run checks, the token list is not simplified */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.isCPP()) {
return;
}
CheckStl checkStl(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkStl.erase();
checkStl.if_find();
checkStl.checkFindInsert();
checkStl.iterators();
checkStl.missingComparison();
checkStl.outOfBounds();
checkStl.outOfBoundsIndexExpression();
checkStl.redundantCondition();
checkStl.string_c_str();
checkStl.uselessCalls();
checkStl.useStlAlgorithm();
checkStl.stlOutOfBounds();
checkStl.negativeIndex();
checkStl.invalidContainer();
checkStl.mismatchingContainers();
checkStl.mismatchingContainerIterator();
checkStl.knownEmptyContainer();
checkStl.eraseIteratorOutOfBounds();
checkStl.stlBoundaries();
checkStl.checkDereferenceInvalidIterator();
checkStl.checkDereferenceInvalidIterator2();
checkStl.checkMutexes();
// Style check
checkStl.size();
}
/** Accessing container out of bounds using ValueFlow */
void outOfBounds();
/** Accessing container out of bounds, following index expression */
void outOfBoundsIndexExpression();
/**
* Finds errors like this:
* for (unsigned ii = 0; ii <= foo.size(); ++ii)
*/
void stlOutOfBounds();
/**
* negative index for array like containers
*/
void negativeIndex();
/**
* Finds errors like this:
* for (it = foo.begin(); it != bar.end(); ++it)
*/
void iterators();
void invalidContainer();
bool checkIteratorPair(const Token* tok1, const Token* tok2);
/**
* Mismatching containers:
* std::find(foo.begin(), bar.end(), x)
*/
void mismatchingContainers();
void mismatchingContainerIterator();
/**
* Dangerous usage of erase. The iterator is invalidated by erase so
* it is bad to dereference it after the erase.
*/
void erase();
void eraseCheckLoopVar(const Scope& scope, const Variable* var);
/**
* bad condition.. "it < alist.end()"
*/
void stlBoundaries();
/** if (a.find(x)) - possibly incorrect condition */
void if_find();
void checkFindInsert();
/**
* Suggest using empty() instead of checking size() against zero for containers.
* Item 4 from Scott Meyers book "Effective STL".
*/
void size();
/**
* Check for redundant condition 'if (ints.find(1) != ints.end()) ints.remove(123);'
* */
void redundantCondition();
/**
* @brief Missing inner comparison, when incrementing iterator inside loop
* Dangers:
* - may increment iterator beyond end
* - may unintentionally skip elements in list/set etc
*/
void missingComparison();
/** Check for common mistakes when using the function string::c_str() */
void string_c_str();
/** @brief %Check calls that using them is useless */
void uselessCalls();
/** @brief %Check for dereferencing an iterator that is invalid */
void checkDereferenceInvalidIterator();
void checkDereferenceInvalidIterator2();
/**
* Dereferencing an erased iterator
* @param erased token where the erase occurs
* @param deref token where the dereference occurs
* @param itername iterator name
* @param inconclusive inconclusive flag
*/
void dereferenceErasedError(const Token* erased, const Token* deref, const std::string& itername, bool inconclusive);
/** @brief Look for loops that can replaced with std algorithms */
void useStlAlgorithm();
void knownEmptyContainer();
void eraseIteratorOutOfBounds();
void checkMutexes();
bool isContainerSize(const Token *containerToken, const Token *expr) const;
bool isContainerSizeGE(const Token * containerToken, const Token *expr) const;
void missingComparisonError(const Token* incrementToken1, const Token* incrementToken2);
void string_c_strThrowError(const Token* tok);
void string_c_strError(const Token* tok);
void string_c_strReturn(const Token* tok);
void string_c_strParam(const Token* tok, nonneg int number, const std::string& argtype = "std::string");
void string_c_strConstructor(const Token* tok, const std::string& argtype = "std::string");
void string_c_strAssignment(const Token* tok, const std::string& argtype = "std::string");
void string_c_strConcat(const Token* tok);
void string_c_strStream(const Token* tok);
void outOfBoundsError(const Token *tok, const std::string &containerName, const ValueFlow::Value *containerSize, const std::string &index, const ValueFlow::Value *indexValue);
void outOfBoundsIndexExpressionError(const Token *tok, const Token *index);
void stlOutOfBoundsError(const Token* tok, const std::string& num, const std::string& var, bool at);
void negativeIndexError(const Token* tok, const ValueFlow::Value& index);
void invalidIteratorError(const Token* tok, const std::string& iteratorName);
void iteratorsError(const Token* tok, const std::string& containerName1, const std::string& containerName2);
void iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName1, const std::string& containerName2);
void iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName);
void mismatchingContainerIteratorError(const Token* containerTok, const Token* iterTok, const Token* containerTok2);
void mismatchingContainersError(const Token* tok1, const Token* tok2);
void mismatchingContainerExpressionError(const Token *tok1, const Token *tok2);
void sameIteratorExpressionError(const Token *tok);
void stlBoundariesError(const Token* tok);
void if_findError(const Token* tok, bool str);
void checkFindInsertError(const Token *tok);
void sizeError(const Token* tok);
void redundantIfRemoveError(const Token* tok);
void invalidContainerLoopError(const Token* tok, const Token* loopTok, ErrorPath errorPath);
void invalidContainerError(const Token *tok, const Token * contTok, const ValueFlow::Value *val, ErrorPath errorPath);
void invalidContainerReferenceError(const Token* tok, const Token* contTok, ErrorPath errorPath);
void uselessCallsReturnValueError(const Token* tok, const std::string& varname, const std::string& function);
void uselessCallsSwapError(const Token* tok, const std::string& varname);
enum class SubstrErrorType : std::uint8_t { EMPTY, COPY, PREFIX, PREFIX_CONCAT };
void uselessCallsSubstrError(const Token* tok, SubstrErrorType type);
void uselessCallsEmptyError(const Token* tok);
void uselessCallsRemoveError(const Token* tok, const std::string& function);
void uselessCallsConstructorError(const Token* tok);
void dereferenceInvalidIteratorError(const Token* deref, const std::string& iterName);
void dereferenceInvalidIteratorError(const Token* tok, const ValueFlow::Value *value, bool inconclusive);
void useStlAlgorithmError(const Token *tok, const std::string &algoName);
void knownEmptyContainerError(const Token *tok, const std::string& algo);
void eraseIteratorOutOfBoundsError(const Token* ftok, const Token* itertok, const ValueFlow::Value* val = nullptr);
void globalLockGuardError(const Token *tok);
void localMutexError(const Token *tok);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const override {
CheckStl c(nullptr, settings, errorLogger);
c.outOfBoundsError(nullptr, "container", nullptr, "x", nullptr);
c.invalidIteratorError(nullptr, "iterator");
c.iteratorsError(nullptr, "container1", "container2");
c.iteratorsError(nullptr, nullptr, "container0", "container1");
c.iteratorsError(nullptr, nullptr, "container");
c.invalidContainerLoopError(nullptr, nullptr, ErrorPath{});
c.invalidContainerError(nullptr, nullptr, nullptr, ErrorPath{});
c.mismatchingContainerIteratorError(nullptr, nullptr, nullptr);
c.mismatchingContainersError(nullptr, nullptr);
c.mismatchingContainerExpressionError(nullptr, nullptr);
c.sameIteratorExpressionError(nullptr);
c.dereferenceErasedError(nullptr, nullptr, "iter", false);
c.stlOutOfBoundsError(nullptr, "i", "foo", false);
c.negativeIndexError(nullptr, ValueFlow::Value(-1));
c.stlBoundariesError(nullptr);
c.if_findError(nullptr, false);
c.if_findError(nullptr, true);
c.checkFindInsertError(nullptr);
c.string_c_strError(nullptr);
c.string_c_strReturn(nullptr);
c.string_c_strParam(nullptr, 0);
c.string_c_strThrowError(nullptr);
c.sizeError(nullptr);
c.missingComparisonError(nullptr, nullptr);
c.redundantIfRemoveError(nullptr);
c.uselessCallsReturnValueError(nullptr, "str", "find");
c.uselessCallsSwapError(nullptr, "str");
c.uselessCallsSubstrError(nullptr, SubstrErrorType::COPY);
c.uselessCallsEmptyError(nullptr);
c.uselessCallsRemoveError(nullptr, "remove");
c.dereferenceInvalidIteratorError(nullptr, "i");
c.eraseIteratorOutOfBoundsError(nullptr, nullptr);
c.useStlAlgorithmError(nullptr, emptyString);
c.knownEmptyContainerError(nullptr, emptyString);
c.globalLockGuardError(nullptr);
c.localMutexError(nullptr);
}
static std::string myName() {
return "STL usage";
}
std::string classInfo() const override {
return "Check for invalid usage of STL:\n"
"- out of bounds errors\n"
"- misuse of iterators when iterating through a container\n"
"- mismatching containers in calls\n"
"- same iterators in calls\n"
"- dereferencing an erased iterator\n"
"- for vectors: using iterator/pointer after push_back has been used\n"
"- optimisation: use empty() instead of size() to guarantee fast code\n"
"- suspicious condition when using find\n"
"- unnecessary searching in associative containers\n"
"- redundant condition\n"
"- common mistakes when using string::c_str()\n"
"- useless calls of string and STL functions\n"
"- dereferencing an invalid iterator\n"
"- erasing an iterator that is out of bounds\n"
"- reading from empty STL container\n"
"- iterating over an empty STL container\n"
"- consider using an STL algorithm instead of raw loop\n"
"- incorrect locking with mutex\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkstlH
| 12,683
|
C++
|
.h
| 262
| 41.874046
| 179
| 0.687606
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,403
|
vf_impossiblevalues.h
|
danmar_cppcheck/lib/vf_impossiblevalues.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfImpossibleValuesH
#define vfImpossibleValuesH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeImpossibleValues(TokenList& tokenList, const Settings& settings);
}
#endif // vfImpossibleValuesH
| 991
|
C++
|
.h
| 26
| 36.192308
| 81
| 0.76795
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,404
|
xml.h
|
danmar_cppcheck/lib/xml.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef xmlH
#define xmlH
#include "config.h"
#include "path.h"
SUPPRESS_WARNING_CLANG_PUSH("-Wzero-as-null-pointer-constant")
SUPPRESS_WARNING_CLANG_PUSH("-Wsuggest-destructor-override")
SUPPRESS_WARNING_CLANG_PUSH("-Winconsistent-missing-destructor-override")
#include <tinyxml2.h> // IWYU pragma: export
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
inline static tinyxml2::XMLError xml_LoadFile(tinyxml2::XMLDocument& doc, const char* filename)
{
// tinyxml2 will fail with a misleading XML_ERROR_FILE_READ_ERROR when you try to load a directory as a XML file
if (Path::isDirectory(filename))
return tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND;
return doc.LoadFile(filename);
}
#endif // xmlH
| 1,522
|
C++
|
.h
| 36
| 40.083333
| 116
| 0.763354
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,405
|
checkinternal.h
|
danmar_cppcheck/lib/checkinternal.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkinternalH
#define checkinternalH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "settings.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Token;
/// @addtogroup Checks
/// @{
/** @brief %Check Internal cppcheck API usage */
class CPPCHECKLIB CheckInternal : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckInternal() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckInternal(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.getSettings().checks.isEnabled(Checks::internalCheck))
return;
CheckInternal checkInternal(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkInternal.checkTokenMatchPatterns();
checkInternal.checkTokenSimpleMatchPatterns();
checkInternal.checkMissingPercentCharacter();
checkInternal.checkUnknownPattern();
checkInternal.checkRedundantNextPrevious();
checkInternal.checkExtraWhitespace();
checkInternal.checkRedundantTokCheck();
}
/** @brief %Check if a simple pattern is used inside Token::Match or Token::findmatch */
void checkTokenMatchPatterns();
/** @brief %Check if a complex pattern is used inside Token::simpleMatch or Token::findsimplematch */
void checkTokenSimpleMatchPatterns();
/** @brief %Check for missing % end character in Token::Match pattern */
void checkMissingPercentCharacter();
/** @brief %Check for unknown (invalid) complex patterns like "%typ%" */
void checkUnknownPattern();
/** @brief %Check for inefficient usage of Token::next(), Token::previous() and Token::tokAt() */
void checkRedundantNextPrevious();
/** @brief %Check if there is whitespace at the beginning or at the end of a pattern */
void checkExtraWhitespace();
/** @brief %Check if there is a redundant check for none-nullness of parameter before Match functions, such as (tok && Token::Match(tok, "foo")) */
void checkRedundantTokCheck();
void multiComparePatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void simplePatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void complexPatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void missingPercentCharacterError(const Token *tok, const std::string &pattern, const std::string &funcname);
void unknownPatternError(const Token* tok, const std::string& pattern);
void redundantNextPreviousError(const Token* tok, const std::string& func1, const std::string& func2);
void orInComplexPattern(const Token *tok, const std::string &pattern, const std::string &funcname);
void extraWhitespaceError(const Token *tok, const std::string &pattern, const std::string &funcname);
void checkRedundantTokCheckError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckInternal c(nullptr, settings, errorLogger);
c.multiComparePatternError(nullptr, ";|%type%", "Match");
c.simplePatternError(nullptr, "class {", "Match");
c.complexPatternError(nullptr, "%type% ( )", "Match");
c.missingPercentCharacterError(nullptr, "%num", "Match");
c.unknownPatternError(nullptr, "%typ");
c.redundantNextPreviousError(nullptr, "previous", "next");
c.orInComplexPattern(nullptr, "||", "Match");
c.extraWhitespaceError(nullptr, "%str% ", "Match");
c.checkRedundantTokCheckError(nullptr);
}
static std::string myName() {
return "cppcheck internal API usage";
}
std::string classInfo() const override {
// Don't include these checks on the WIKI where people can read what
// checks there are. These checks are not intended for users.
return "";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkinternalH
| 5,185
|
C++
|
.h
| 99
| 47.505051
| 151
| 0.689315
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,406
|
vf_analyzers.h
|
danmar_cppcheck/lib/vf_analyzers.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfAnalyzers
#define vfAnalyzers
#include "analyzer.h"
#include "valueptr.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
class Token;
class Variable;
class Settings;
namespace ValueFlow {
class Value;
}
ValuePtr<Analyzer> makeMultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& settings);
ValuePtr<Analyzer> makeSameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s);
ValuePtr<Analyzer> makeOppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s);
using PartialReadContainer = std::vector<std::pair<Token *, ValueFlow::Value>>;
ValuePtr<Analyzer> makeMemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s);
ValuePtr<Analyzer> makeAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings);
ValuePtr<Analyzer> makeReverseAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings);
#endif // vfAnalyzers
| 1,900
|
C++
|
.h
| 40
| 45.725
| 174
| 0.780963
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,407
|
importproject.h
|
danmar_cppcheck/lib/importproject.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef importprojectH
#define importprojectH
//---------------------------------------------------------------------------
#include "config.h"
#include "filesettings.h"
#include "platform.h"
#include "utils.h"
#include <cstdint>
#include <iosfwd>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
/// @addtogroup Core
/// @{
namespace cppcheck {
struct stricmp {
bool operator()(const std::string &lhs, const std::string &rhs) const {
return caseInsensitiveStringCompare(lhs,rhs) < 0;
}
};
}
class Settings;
/**
* @brief Importing project settings.
*/
class CPPCHECKLIB WARN_UNUSED ImportProject {
public:
enum class Type : std::uint8_t {
NONE,
UNKNOWN,
MISSING,
FAILURE,
COMPILE_DB,
VS_SLN,
VS_VCXPROJ,
BORLAND,
CPPCHECK_GUI
};
static void fsParseCommand(FileSettings& fs, const std::string& command);
static void fsSetDefines(FileSettings& fs, std::string defs);
static void fsSetIncludePaths(FileSettings& fs, const std::string &basepath, const std::list<std::string> &in, std::map<std::string, std::string, cppcheck::stricmp> &variables);
std::list<FileSettings> fileSettings;
Type projectType{Type::NONE};
ImportProject() = default;
virtual ~ImportProject() = default;
ImportProject(const ImportProject&) = default;
ImportProject& operator=(const ImportProject&) & = default;
void selectOneVsConfig(Platform::Type platform);
void selectVsConfigurations(Platform::Type platform, const std::vector<std::string> &configurations);
std::list<std::string> getVSConfigs();
// Cppcheck GUI output
struct {
std::string analyzeAllVsConfigs;
std::vector<std::string> pathNames;
std::list<std::string> libraries;
std::list<std::string> excludedPaths;
std::list<std::string> checkVsConfigs;
std::string projectFile;
std::string platform;
} guiProject;
void ignorePaths(const std::vector<std::string> &ipaths);
void ignoreOtherConfigs(const std::string &cfg);
Type import(const std::string &filename, Settings *settings=nullptr);
protected:
bool importCompileCommands(std::istream &istr);
bool importCppcheckGuiProject(std::istream &istr, Settings *settings);
virtual bool sourceFileExists(const std::string &file);
private:
struct SharedItemsProject {
bool successful = false;
std::string pathToProjectFile;
std::vector<std::string> includePaths;
std::vector<std::string> sourceFiles;
};
bool importSln(std::istream &istr, const std::string &path, const std::vector<std::string> &fileFilters);
static SharedItemsProject importVcxitems(const std::string &filename, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache);
bool importVcxproj(const std::string &filename, std::map<std::string, std::string, cppcheck::stricmp> &variables, const std::string &additionalIncludeDirectories, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache);
bool importBcb6Prj(const std::string &projectFilename);
static void printError(const std::string &message);
void setRelativePaths(const std::string &filename);
std::string mPath;
std::set<std::string> mAllVSConfigs;
};
namespace CppcheckXml {
static constexpr char ProjectElementName[] = "project";
static constexpr char ProjectVersionAttrib[] = "version";
static constexpr char ProjectFileVersion[] = "1";
static constexpr char BuildDirElementName[] = "builddir";
static constexpr char ImportProjectElementName[] = "importproject";
static constexpr char AnalyzeAllVsConfigsElementName[] = "analyze-all-vs-configs";
static constexpr char Parser[] = "parser";
static constexpr char IncludeDirElementName[] = "includedir";
static constexpr char DirElementName[] = "dir";
static constexpr char DirNameAttrib[] = "name";
static constexpr char DefinesElementName[] = "defines";
static constexpr char DefineName[] = "define";
static constexpr char DefineNameAttrib[] = "name";
static constexpr char UndefinesElementName[] = "undefines";
static constexpr char UndefineName[] = "undefine";
static constexpr char PathsElementName[] = "paths";
static constexpr char PathName[] = "dir";
static constexpr char PathNameAttrib[] = "name";
static constexpr char RootPathName[] = "root";
static constexpr char RootPathNameAttrib[] = "name";
static constexpr char IgnoreElementName[] = "ignore";
static constexpr char IgnorePathName[] = "path";
static constexpr char IgnorePathNameAttrib[] = "name";
static constexpr char ExcludeElementName[] = "exclude";
static constexpr char ExcludePathName[] = "path";
static constexpr char ExcludePathNameAttrib[] = "name";
static constexpr char FunctionContracts[] = "function-contracts";
static constexpr char VariableContractsElementName[] = "variable-contracts";
static constexpr char LibrariesElementName[] = "libraries";
static constexpr char LibraryElementName[] = "library";
static constexpr char PlatformElementName[] = "platform";
static constexpr char SuppressionsElementName[] = "suppressions";
static constexpr char SuppressionElementName[] = "suppression";
static constexpr char AddonElementName[] = "addon";
static constexpr char AddonsElementName[] = "addons";
static constexpr char ToolElementName[] = "tool";
static constexpr char ToolsElementName[] = "tools";
static constexpr char TagsElementName[] = "tags";
static constexpr char TagElementName[] = "tag";
static constexpr char TagWarningsElementName[] = "tag-warnings";
static constexpr char TagAttributeName[] = "tag";
static constexpr char WarningElementName[] = "warning";
static constexpr char HashAttributeName[] = "hash";
static constexpr char CheckLevelExhaustiveElementName[] = "check-level-exhaustive";
static constexpr char CheckHeadersElementName[] = "check-headers";
static constexpr char CheckUnusedTemplatesElementName[] = "check-unused-templates";
static constexpr char MaxCtuDepthElementName[] = "max-ctu-depth";
static constexpr char MaxTemplateRecursionElementName[] = "max-template-recursion";
static constexpr char CheckUnknownFunctionReturn[] = "check-unknown-function-return-values";
static constexpr char InlineSuppression[] = "inline-suppression";
static constexpr char ClangTidy[] = "clang-tidy";
static constexpr char Name[] = "name";
static constexpr char VSConfigurationElementName[] = "vs-configurations";
static constexpr char VSConfigurationName[] = "config";
// Cppcheck Premium
static constexpr char BughuntingElementName[] = "bug-hunting";
static constexpr char CodingStandardsElementName[] = "coding-standards";
static constexpr char CodingStandardElementName[] = "coding-standard";
static constexpr char CertIntPrecisionElementName[] = "cert-c-int-precision";
static constexpr char LicenseFileElementName[] = "license-file";
static constexpr char ProjectNameElementName[] = "project-name";
}
/// @}
//---------------------------------------------------------------------------
#endif // importprojectH
| 8,192
|
C++
|
.h
| 169
| 43.846154
| 252
| 0.71175
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,408
|
vf_symbolicoperators.h
|
danmar_cppcheck/lib/vf_symbolicoperators.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfSymbolicOperatorsH
#define vfSymbolicOperatorsH
class SymbolDatabase;
class Settings;
namespace ValueFlow
{
void analyzeSymbolicOperators(const SymbolDatabase& symboldatabase, const Settings& settings);
}
#endif // vfSymbolicOperatorsH
| 1,016
|
C++
|
.h
| 26
| 37.153846
| 98
| 0.772819
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,409
|
vf_arrayelement.h
|
danmar_cppcheck/lib/vf_arrayelement.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfArrayElementH
#define vfArrayElementH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeArrayElement(TokenList& tokenlist, const Settings& settings);
}
#endif // vfArrayElementH
| 975
|
C++
|
.h
| 26
| 35.576923
| 77
| 0.764021
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,410
|
vf_functionreturn.h
|
danmar_cppcheck/lib/vf_functionreturn.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfFunctionReturnH
#define vfFunctionReturnH
class TokenList;
class ErrorLogger;
class Settings;
namespace ValueFlow
{
void analyzeFunctionReturn(TokenList &tokenlist, ErrorLogger &errorLogger, const Settings& settings);
}
#endif // vfFunctionReturnH
| 1,028
|
C++
|
.h
| 27
| 36.185185
| 105
| 0.770311
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,411
|
vf_analyze.h
|
danmar_cppcheck/lib/vf_analyze.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfAnalyzeH
#define vfAnalyzeH
#include "vf_array.h" // IWYU pragma: export
#include "vf_arraybool.h" // IWYU pragma: export
#include "vf_arrayelement.h" // IWYU pragma: export
#include "vf_bitand.h" // IWYU pragma: export
#include "vf_conditionexpressions.h" // IWYU pragma: export
#include "vf_debug.h" // IWYU pragma: export
#include "vf_enumvalue.h" // IWYU pragma: export
#include "vf_functionreturn.h" // IWYU pragma: export
#include "vf_globalconstvar.h" // IWYU pragma: export
#include "vf_globalstaticvar.h" // IWYU pragma: export
#include "vf_impossiblevalues.h" // IWYU pragma: export
#include "vf_infercondition.h" // IWYU pragma: export
#include "vf_iteratorinfer.h" // IWYU pragma: export
#include "vf_iterators.h" // IWYU pragma: export
#include "vf_number.h" // IWYU pragma: export
#include "vf_pointeralias.h" // IWYU pragma: export
#include "vf_rightshift.h" // IWYU pragma: export
#include "vf_sameexpressions.h" // IWYU pragma: export
#include "vf_string.h" // IWYU pragma: export
#include "vf_subfunction.h" // IWYU pragma: export
#include "vf_switchvariable.h" // IWYU pragma: export
#include "vf_symbolicinfer.h" // IWYU pragma: export
#include "vf_symbolicoperators.h" // IWYU pragma: export
#include "vf_unknownfunctionreturn.h" // IWYU pragma: export
#endif // vfAnalyzeH
| 2,070
|
C++
|
.h
| 44
| 45.613636
| 72
| 0.746416
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,412
|
checkuninitvar.h
|
danmar_cppcheck/lib/checkuninitvar.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkuninitvarH
#define checkuninitvarH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "mathlib.h"
#include "errortypes.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <string>
class Scope;
class Token;
class Variable;
class ErrorLogger;
class Settings;
class Library;
namespace CTU {
class FileInfo;
}
namespace tinyxml2 {
class XMLElement;
}
struct VariableValue {
explicit VariableValue(MathLib::bigint val = 0) : value(val) {}
MathLib::bigint value;
bool notEqual{};
};
/// @addtogroup Checks
/// @{
/** @brief Checking for uninitialized variables */
class CPPCHECKLIB CheckUninitVar : public Check {
friend class TestUninitVar;
public:
/** @brief This constructor is used when registering the CheckUninitVar */
CheckUninitVar() : Check(myName()) {}
enum Alloc : std::uint8_t { NO_ALLOC, NO_CTOR_CALL, CTOR_CALL, ARRAY };
static const Token *isVariableUsage(const Token *vartok, const Library &library, bool pointer, Alloc alloc, int indirect = 0);
const Token *isVariableUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect = 0) const;
private:
/** @brief This constructor is used when running checks. */
CheckUninitVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckUninitVar checkUninitVar(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkUninitVar.valueFlowUninit();
checkUninitVar.check();
}
bool diag(const Token* tok);
/** Check for uninitialized variables */
void check();
void checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs);
void checkStruct(const Token *tok, const Variable &structvar);
bool checkScopeForVariable(const Token *tok, const Variable& var, bool* possibleInit, bool* noreturn, Alloc* alloc, const std::string &membervar, std::map<nonneg int, VariableValue>& variableValue);
const Token* checkExpr(const Token* tok, const Variable& var, Alloc alloc, bool known, bool* bailout = nullptr) const;
bool checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar);
bool checkLoopBody(const Token *tok, const Variable& var, Alloc alloc, const std::string &membervar, bool suppressErrors);
const Token* checkLoopBodyRecursive(const Token *start, const Variable& var, Alloc alloc, const std::string &membervar, bool &bailout, bool &alwaysReturns) const;
void checkRhs(const Token *tok, const Variable &var, Alloc alloc, nonneg int number_of_if, const std::string &membervar);
static int isFunctionParUsage(const Token *vartok, const Library &library, bool pointer, Alloc alloc, int indirect = 0);
int isFunctionParUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect = 0) const;
bool isMemberVariableAssignment(const Token *tok, const std::string &membervar) const;
bool isMemberVariableUsage(const Token *tok, bool isPointer, Alloc alloc, const std::string &membervar) const;
/** ValueFlow-based checking for uninitialized variables */
void valueFlowUninit();
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
void uninitvarError(const Token* tok, const ValueFlow::Value& v);
void uninitdataError(const Token *tok, const std::string &varname);
void uninitvarError(const Token *tok, const std::string &varname, ErrorPath errorPath);
void uninitvarError(const Token *tok, const std::string &varname) {
uninitvarError(tok, varname, ErrorPath{});
}
void uninitvarError(const Token *tok, const std::string &varname, Alloc alloc) {
if (alloc == NO_CTOR_CALL || alloc == CTOR_CALL)
uninitdataError(tok, varname);
else
uninitvarError(tok, varname);
}
void uninitStructMemberError(const Token *tok, const std::string &membername);
std::set<const Token*> mUninitDiags;
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const override
{
CheckUninitVar c(nullptr, settings, errorLogger);
ValueFlow::Value v{};
c.uninitvarError(nullptr, v);
c.uninitdataError(nullptr, "varname");
c.uninitStructMemberError(nullptr, "a.b");
}
static std::string myName() {
return "Uninitialized variables";
}
std::string classInfo() const override {
return "Uninitialized variables\n"
"- using uninitialized local variables\n"
"- using allocated data before it has been initialized\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkuninitvarH
| 6,309
|
C++
|
.h
| 126
| 45.674603
| 202
| 0.703722
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,413
|
keywords.h
|
danmar_cppcheck/lib/keywords.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef keywordsH
#define keywordsH
#include "standards.h"
#include <string>
#include <unordered_set>
class Keywords
{
public:
static const std::unordered_set<std::string>& getAll(Standards::cstd_t cStd);
static const std::unordered_set<std::string>& getAll(Standards::cppstd_t cppStd);
static const std::unordered_set<std::string>& getOnly(Standards::cstd_t cStd);
static const std::unordered_set<std::string>& getOnly(Standards::cppstd_t cppStd);
};
#endif
| 1,243
|
C++
|
.h
| 31
| 37.870968
| 86
| 0.747927
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,414
|
checkexceptionsafety.h
|
danmar_cppcheck/lib/checkexceptionsafety.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkexceptionsafetyH
#define checkexceptionsafetyH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class Settings;
class ErrorLogger;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief %Check exception safety (exceptions shouldn't cause leaks nor corrupt data)
*
* The problem with these checks is that Cppcheck can't determine what the valid
* values are for variables. But in some cases (dead pointers) it can be determined
* that certain variable values are corrupt.
*/
class CPPCHECKLIB CheckExceptionSafety : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckExceptionSafety() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckExceptionSafety(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckExceptionSafety checkExceptionSafety(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkExceptionSafety.destructors();
checkExceptionSafety.deallocThrow();
checkExceptionSafety.checkRethrowCopy();
checkExceptionSafety.checkCatchExceptionByValue();
checkExceptionSafety.nothrowThrows();
checkExceptionSafety.unhandledExceptionSpecification();
checkExceptionSafety.rethrowNoCurrentException();
}
/** Don't throw exceptions in destructors */
void destructors();
/** deallocating memory and then throw (dead pointer) */
void deallocThrow();
/** Don't rethrow a copy of the caught exception; use a bare throw instead */
void checkRethrowCopy();
/** @brief %Check for exceptions that are caught by value instead of by reference */
void checkCatchExceptionByValue();
/** @brief %Check for functions that throw that shouldn't */
void nothrowThrows();
/** @brief %Check for unhandled exception specification */
void unhandledExceptionSpecification();
/** @brief %Check for rethrow not from catch scope */
void rethrowNoCurrentException();
/** Don't throw exceptions in destructors */
void destructorsError(const Token * tok, const std::string &className);
void deallocThrowError(const Token * tok, const std::string &varname);
void rethrowCopyError(const Token * tok, const std::string &varname);
void catchExceptionByValueError(const Token *tok);
void noexceptThrowError(const Token * tok);
/** Missing exception specification */
void unhandledExceptionSpecificationError(const Token * tok1, const Token * tok2, const std::string & funcname);
/** Rethrow without currently handled exception */
void rethrowNoCurrentExceptionError(const Token *tok);
/** Generate all possible errors (for --errorlist) */
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckExceptionSafety c(nullptr, settings, errorLogger);
c.destructorsError(nullptr, "Class");
c.deallocThrowError(nullptr, "p");
c.rethrowCopyError(nullptr, "varname");
c.catchExceptionByValueError(nullptr);
c.noexceptThrowError(nullptr);
c.unhandledExceptionSpecificationError(nullptr, nullptr, "funcname");
c.rethrowNoCurrentExceptionError(nullptr);
}
/** Short description of class (for --doc) */
static std::string myName() {
return "Exception Safety";
}
/** wiki formatted description of the class (for --doc) */
std::string classInfo() const override {
return "Checking exception safety\n"
"- Throwing exceptions in destructors\n"
"- Throwing exception during invalid state\n"
"- Throwing a copy of a caught exception instead of rethrowing the original exception\n"
"- Exception caught by value instead of by reference\n"
"- Throwing exception in noexcept, nothrow(), __attribute__((nothrow)) or __declspec(nothrow) function\n"
"- Unhandled exception specification when calling function foo()\n"
"- Rethrow without currently handled exception\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkexceptionsafetyH
| 5,369
|
C++
|
.h
| 111
| 43.063063
| 120
| 0.688061
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,416
|
addoninfo.h
|
danmar_cppcheck/lib/addoninfo.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef addonInfoH
#define addonInfoH
#include "config.h"
#include <string>
struct CPPCHECKLIB AddonInfo {
std::string name;
std::string scriptFile; // addon script
std::string executable; // addon executable
std::string args; // special extra arguments
std::string python; // script interpreter
bool ctu = false;
std::string runScript;
std::string getAddonInfo(const std::string &fileName, const std::string &exename, bool debug = false);
};
#endif // addonInfoH
| 1,274
|
C++
|
.h
| 32
| 37.125
| 106
| 0.731392
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,417
|
vf_rightshift.h
|
danmar_cppcheck/lib/vf_rightshift.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfRightShiftH
#define vfRightShiftH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeRightShift(TokenList &tokenList, const Settings& settings);
}
#endif // vfRightShiftH
| 967
|
C++
|
.h
| 26
| 35.269231
| 75
| 0.762006
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,418
|
vf_globalstaticvar.h
|
danmar_cppcheck/lib/vf_globalstaticvar.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfGlobalStaticVarH
#define vfGlobalStaticVarH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeGlobalStaticVar(TokenList &tokenList, const Settings &settings);
}
#endif // vfGlobalStaticVarH
| 987
|
C++
|
.h
| 26
| 36.038462
| 80
| 0.76698
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,419
|
vf_iteratorinfer.h
|
danmar_cppcheck/lib/vf_iteratorinfer.h
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfIteratorInferH
#define vfIteratorInferH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeIteratorInfer(TokenList &tokenlist, const Settings &settings);
}
#endif // vfIteratorInferH
| 967
|
C++
|
.h
| 26
| 35.269231
| 78
| 0.773746
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,420
|
checkbufferoverrun.h
|
danmar_cppcheck/lib/checkbufferoverrun.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkbufferoverrunH
#define checkbufferoverrunH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "ctu.h"
#include "errortypes.h"
#include "mathlib.h"
#include "symboldatabase.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <map>
#include <string>
#include <vector>
namespace tinyxml2 {
class XMLElement;
}
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief buffer overruns and array index out of bounds
*
* Buffer overrun and array index out of bounds are pretty much the same.
* But I generally use 'array index' if the code contains []. And the given
* index is out of bounds.
* I generally use 'buffer overrun' if you for example call a strcpy or
* other function and pass a buffer and reads or writes too much data.
*/
class CPPCHECKLIB CheckBufferOverrun : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckBufferOverrun() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckBufferOverrun checkBufferOverrun(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkBufferOverrun.arrayIndex();
checkBufferOverrun.pointerArithmetic();
checkBufferOverrun.bufferOverflow();
checkBufferOverrun.arrayIndexThenCheck();
checkBufferOverrun.stringNotZeroTerminated();
checkBufferOverrun.objectIndex();
checkBufferOverrun.argumentSize();
checkBufferOverrun.negativeArraySize();
}
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckBufferOverrun c(nullptr, settings, errorLogger);
c.arrayIndexError(nullptr, std::vector<Dimension>(), std::vector<ValueFlow::Value>());
c.pointerArithmeticError(nullptr, nullptr, nullptr);
c.negativeIndexError(nullptr, std::vector<Dimension>(), std::vector<ValueFlow::Value>());
c.arrayIndexThenCheckError(nullptr, "i");
c.bufferOverflowError(nullptr, nullptr, Certainty::normal);
c.objectIndexError(nullptr, nullptr, true);
c.argumentSizeError(nullptr, "function", 1, "buffer", nullptr, nullptr);
c.negativeMemoryAllocationSizeError(nullptr, nullptr);
c.negativeArraySizeError(nullptr);
}
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
void arrayIndex();
void arrayIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes);
void negativeIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes);
void pointerArithmetic();
void pointerArithmeticError(const Token *tok, const Token *indexToken, const ValueFlow::Value *indexValue);
void bufferOverflow();
void bufferOverflowError(const Token *tok, const ValueFlow::Value *value, Certainty certainty);
void arrayIndexThenCheck();
void arrayIndexThenCheckError(const Token *tok, const std::string &indexName);
void stringNotZeroTerminated();
void terminateStrncpyError(const Token *tok, const std::string &varname);
void argumentSize();
void argumentSizeError(const Token *tok, const std::string &functionName, nonneg int paramIndex, const std::string ¶mExpression, const Variable *paramVar, const Variable *functionArg);
void negativeArraySize();
void negativeArraySizeError(const Token* tok);
void negativeMemoryAllocationSizeError(const Token* tok, const ValueFlow::Value* value); // provide a negative value to memory allocation function
void objectIndex();
void objectIndexError(const Token *tok, const ValueFlow::Value *v, bool known);
ValueFlow::Value getBufferSize(const Token *bufTok) const;
// CTU
static bool isCtuUnsafeBufferUsage(const Settings &settings, const Token *argtok, MathLib::bigint *offset, int type);
static bool isCtuUnsafeArrayIndex(const Settings &settings, const Token *argtok, MathLib::bigint *offset);
static bool isCtuUnsafePointerArith(const Settings &settings, const Token *argtok, MathLib::bigint *offset);
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
static bool analyseWholeProgram1(const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap, const CTU::FileInfo::UnsafeUsage &unsafeUsage, int type, ErrorLogger &errorLogger, int maxCtuDepth);
static std::string myName() {
return "Bounds checking";
}
std::string classInfo() const override {
return "Out of bounds checking:\n"
"- Array index out of bounds\n"
"- Pointer arithmetic overflow\n"
"- Buffer overflow\n"
"- Dangerous usage of strncat()\n"
"- Using array index before checking it\n"
"- Partial string write that leads to buffer that is not zero terminated.\n"
"- Check for large enough arrays being passed to functions\n"
"- Allocating memory with a negative size\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkbufferoverrunH
| 6,813
|
C++
|
.h
| 132
| 45.909091
| 220
| 0.697625
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,421
|
checkcondition.h
|
danmar_cppcheck/lib/checkcondition.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkconditionH
#define checkconditionH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "mathlib.h"
#include "errortypes.h"
#include "tokenize.h"
#include <set>
#include <string>
class Settings;
class Token;
class ErrorLogger;
class ValueType;
namespace ValueFlow {
class Value;
}
/// @addtogroup Checks
/// @{
/**
* @brief Check for condition mismatches
*/
class CPPCHECKLIB CheckCondition : public Check {
public:
/** This constructor is used when registering the CheckAssignIf */
CheckCondition() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckCondition(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckCondition checkCondition(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkCondition.multiCondition();
checkCondition.clarifyCondition(); // not simplified because ifAssign
checkCondition.multiCondition2();
checkCondition.checkIncorrectLogicOperator();
checkCondition.checkInvalidTestForOverflow();
checkCondition.duplicateCondition();
checkCondition.checkPointerAdditionResultNotNull();
checkCondition.checkDuplicateConditionalAssign();
checkCondition.assignIf();
checkCondition.checkBadBitmaskCheck();
checkCondition.comparison();
checkCondition.checkModuloAlwaysTrueFalse();
checkCondition.checkAssignmentInCondition();
checkCondition.checkCompareValueOutOfTypeRange();
checkCondition.alwaysTrueFalse();
}
/** mismatching assignment / comparison */
void assignIf();
/** parse scopes recursively */
bool assignIfParseScope(const Token * assignTok,
const Token * startTok,
nonneg int varid,
bool islocal,
char bitop,
MathLib::bigint num);
/** check bitmask using | instead of & */
void checkBadBitmaskCheck();
/** mismatching lhs and rhs in comparison */
void comparison();
void duplicateCondition();
/** match 'if' and 'else if' conditions */
void multiCondition();
/**
* multiconditions #2
* - Opposite inner conditions => always false
* - (TODO) Same/Overlapping inner condition => always true
* - same condition after early exit => always false
**/
void multiCondition2();
/** @brief %Check for testing for mutual exclusion over ||*/
void checkIncorrectLogicOperator();
/** @brief %Check for suspicious usage of modulo (e.g. "if(var % 4 == 4)") */
void checkModuloAlwaysTrueFalse();
/** @brief Suspicious condition (assignment+comparison) */
void clarifyCondition();
/** @brief Condition is always true/false */
void alwaysTrueFalse();
/** @brief %Check for invalid test for overflow 'x+100 < x' */
void checkInvalidTestForOverflow();
/** @brief Check if pointer addition result is NULL '(ptr + 1) == NULL' */
void checkPointerAdditionResultNotNull();
void checkDuplicateConditionalAssign();
/** @brief Assignment in condition */
void checkAssignmentInCondition();
// The conditions that have been diagnosed
std::set<const Token*> mCondDiags;
bool diag(const Token* tok, bool insert=true);
bool isAliased(const std::set<int> &vars) const;
bool isOverlappingCond(const Token * cond1, const Token * cond2, bool pure) const;
void assignIfError(const Token *tok1, const Token *tok2, const std::string &condition, bool result);
void mismatchingBitAndError(const Token *tok1, MathLib::bigint num1, const Token *tok2, MathLib::bigint num2);
void badBitmaskCheckError(const Token *tok, bool isNoOp = false);
void comparisonError(const Token *tok,
const std::string &bitop,
MathLib::bigint value1,
const std::string &op,
MathLib::bigint value2,
bool result);
void duplicateConditionError(const Token *tok1, const Token *tok2, ErrorPath errorPath);
void overlappingElseIfConditionError(const Token *tok, nonneg int line1);
void oppositeElseIfConditionError(const Token *ifCond, const Token *elseIfCond, ErrorPath errorPath);
void oppositeInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath);
void identicalInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath);
void identicalConditionAfterEarlyExitError(const Token *cond1, const Token *cond2, ErrorPath errorPath);
void incorrectLogicOperatorError(const Token *tok, const std::string &condition, bool always, bool inconclusive, ErrorPath errors);
void redundantConditionError(const Token *tok, const std::string &text, bool inconclusive);
void moduloAlwaysTrueFalseError(const Token* tok, const std::string& maxVal);
void clarifyConditionError(const Token *tok, bool assign, bool boolop);
void alwaysTrueFalseError(const Token* tok, const Token* condition, const ValueFlow::Value* value);
void invalidTestForOverflow(const Token* tok, const ValueType *valueType, const std::string &replace);
void pointerAdditionResultNotNullError(const Token *tok, const Token *calc);
void duplicateConditionalAssignError(const Token *condTok, const Token* assignTok, bool isRedundant = false);
void assignmentInCondition(const Token *eq);
void checkCompareValueOutOfTypeRange();
void compareValueOutOfTypeRangeError(const Token *comparison, const std::string &type, long long value, bool result);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckCondition c(nullptr, settings, errorLogger);
c.assignIfError(nullptr, nullptr, emptyString, false);
c.badBitmaskCheckError(nullptr);
c.comparisonError(nullptr, "&", 6, "==", 1, false);
c.duplicateConditionError(nullptr, nullptr, ErrorPath{});
c.overlappingElseIfConditionError(nullptr, 1);
c.mismatchingBitAndError(nullptr, 0xf0, nullptr, 1);
c.oppositeInnerConditionError(nullptr, nullptr, ErrorPath{});
c.identicalInnerConditionError(nullptr, nullptr, ErrorPath{});
c.identicalConditionAfterEarlyExitError(nullptr, nullptr, ErrorPath{});
c.incorrectLogicOperatorError(nullptr, "foo > 3 && foo < 4", true, false, ErrorPath{});
c.redundantConditionError(nullptr, "If x > 11 the condition x > 10 is always true.", false);
c.moduloAlwaysTrueFalseError(nullptr, "1");
c.clarifyConditionError(nullptr, true, false);
c.alwaysTrueFalseError(nullptr, nullptr, nullptr);
c.invalidTestForOverflow(nullptr, nullptr, "false");
c.pointerAdditionResultNotNullError(nullptr, nullptr);
c.duplicateConditionalAssignError(nullptr, nullptr);
c.assignmentInCondition(nullptr);
c.compareValueOutOfTypeRangeError(nullptr, "unsigned char", 256, true);
}
static std::string myName() {
return "Condition";
}
std::string classInfo() const override {
return "Match conditions with assignments and other conditions:\n"
"- Mismatching assignment and comparison => comparison is always true/false\n"
"- Mismatching lhs and rhs in comparison => comparison is always true/false\n"
"- Detect usage of | where & should be used\n"
"- Duplicate condition and assignment\n"
"- Detect matching 'if' and 'else if' conditions\n"
"- Mismatching bitand (a &= 0xf0; a &= 1; => a = 0)\n"
"- Opposite inner condition is always false\n"
"- Identical condition after early exit is always false\n"
"- Condition that is always true/false\n"
"- Mutual exclusion over || always evaluating to true\n"
"- Comparisons of modulo results that are always true/false.\n"
"- Known variable values => condition is always true/false\n"
"- Invalid test for overflow. Some mainstream compilers remove such overflow tests when optimising code.\n"
"- Suspicious assignment of container/iterator in condition => condition is always true.\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkconditionH
| 9,545
|
C++
|
.h
| 181
| 45.436464
| 135
| 0.681613
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,423
|
checkassert.h
|
danmar_cppcheck/lib/checkassert.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkassertH
#define checkassertH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Scope;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Checking for side effects in assert statements
*/
class CPPCHECKLIB CheckAssert : public Check {
public:
CheckAssert() : Check(myName()) {}
private:
CheckAssert(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** run checks, the token list is not simplified */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckAssert checkAssert(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkAssert.assertWithSideEffects();
}
void assertWithSideEffects();
void checkVariableAssignment(const Token* assignTok, const Scope *assertionScope);
static bool inSameScope(const Token* returnTok, const Token* assignTok);
void sideEffectInAssertError(const Token *tok, const std::string& functionName);
void assignmentInAssertError(const Token *tok, const std::string &varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckAssert c(nullptr, settings, errorLogger);
c.sideEffectInAssertError(nullptr, "function");
c.assignmentInAssertError(nullptr, "var");
}
static std::string myName() {
return "Assert";
}
std::string classInfo() const override {
return "Warn if there are side effects in assert statements (since this cause different behaviour in debug/release builds).\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkassertH
| 2,737
|
C++
|
.h
| 65
| 38.615385
| 135
| 0.674322
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,424
|
checkclass.h
|
danmar_cppcheck/lib/checkclass.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkclassH
#define checkclassH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include "symboldatabase.h"
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
namespace CTU {
class FileInfo;
}
namespace tinyxml2 {
class XMLElement;
}
/// @addtogroup Checks
/// @{
/** @brief %Check classes. Uninitialized member variables, non-conforming operators, missing virtual destructor, etc */
class CPPCHECKLIB CheckClass : public Check {
friend class TestClass;
friend class TestConstructors;
friend class TestUnusedPrivateFunction;
public:
/** @brief This constructor is used when registering the CheckClass */
CheckClass() : Check(myName()) {}
/** @brief Set of the STL types whose operator[] is not const */
static const std::set<std::string> stl_containers_not_const;
private:
/** @brief This constructor is used when running checks. */
CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger);
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckClass checkClass(&tokenizer, &tokenizer.getSettings(), errorLogger);
// can't be a simplified check .. the 'sizeof' is used.
checkClass.checkMemset();
checkClass.constructors();
checkClass.privateFunctions();
checkClass.operatorEqRetRefThis();
checkClass.thisSubtraction();
checkClass.operatorEqToSelf();
checkClass.initializerListOrder();
checkClass.initializationListUsage();
checkClass.checkSelfInitialization();
checkClass.virtualDestructor();
checkClass.checkConst();
checkClass.copyconstructors();
checkClass.checkVirtualFunctionCallInConstructor();
checkClass.checkDuplInheritedMembers();
checkClass.checkExplicitConstructors();
checkClass.checkCopyCtorAndEqOperator();
checkClass.checkOverride();
checkClass.checkUselessOverride();
checkClass.checkReturnByReference();
checkClass.checkThisUseAfterFree();
checkClass.checkUnsafeClassRefMember();
}
/** @brief %Check that all class constructors are ok */
void constructors();
/** @brief %Check that constructors with single parameter are explicit,
* if they has to be.*/
void checkExplicitConstructors();
/** @brief %Check that all private functions are called */
void privateFunctions();
/**
* @brief %Check that the memsets are valid.
* The 'memset' function can do dangerous things if used wrong. If it
* is used on STL containers for instance it will clear all its data
* and then the STL container may leak memory or worse have an invalid state.
* It can also overwrite the virtual table.
* Important: The checking doesn't work on simplified tokens list.
*/
void checkMemset();
void checkMemsetType(const Scope *start, const Token *tok, const Scope *type, bool allocation, std::set<const Scope *> parsedTypes);
/** @brief 'operator=' should return reference to *this */
void operatorEqRetRefThis(); // Warning upon no "return *this;"
/** @brief 'operator=' should check for assignment to self */
void operatorEqToSelf(); // Warning upon no check for assignment to self
/** @brief The destructor in a base class should be virtual */
void virtualDestructor();
/** @brief warn for "this-x". The indented code may be "this->x" */
void thisSubtraction();
/** @brief can member function be const? */
void checkConst();
/** @brief Check initializer list order */
void initializerListOrder();
/** @brief Suggest using initialization list */
void initializationListUsage();
/** @brief Check for initialization of a member with itself */
void checkSelfInitialization();
void copyconstructors();
/** @brief call of virtual function in constructor/destructor */
void checkVirtualFunctionCallInConstructor();
/** @brief Check duplicated inherited members */
void checkDuplInheritedMembers();
/** @brief Check that copy constructor and operator defined together */
void checkCopyCtorAndEqOperator();
/** @brief Check that the override keyword is used when overriding virtual functions */
void checkOverride();
/** @brief Check that the overriden function is not identical to the base function */
void checkUselessOverride();
/** @brief Check that large members are returned by reference from getter function */
void checkReturnByReference();
/** @brief When "self pointer" is destroyed, 'this' might become invalid. */
void checkThisUseAfterFree();
/** @brief Unsafe class check - const reference member */
void checkUnsafeClassRefMember();
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
const SymbolDatabase* mSymbolDatabase{};
// Reporting errors..
void noConstructorError(const Token *tok, const std::string &classname, bool isStruct);
void noExplicitConstructorError(const Token *tok, const std::string &classname, bool isStruct);
//void copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& var_name);
void copyConstructorShallowCopyError(const Token *tok, const std::string& varname);
void noCopyConstructorError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive);
void noOperatorEqError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive);
void noDestructorError(const Scope *scope, bool isdefault, const Token *alloc);
void uninitVarError(const Token *tok, bool isprivate, Function::Type functionType, const std::string &classname, const std::string &varname, bool derived, bool inconclusive);
void uninitVarError(const Token *tok, const std::string &classname, const std::string &varname);
void missingMemberCopyError(const Token *tok, Function::Type functionType, const std::string& classname, const std::string& varname);
void operatorEqVarError(const Token *tok, const std::string &classname, const std::string &varname, bool inconclusive);
void unusedPrivateFunctionError(const Token *tok, const std::string &classname, const std::string &funcname);
void memsetError(const Token *tok, const std::string &memfunc, const std::string &classname, const std::string &type, bool isContainer = false);
void memsetErrorReference(const Token *tok, const std::string &memfunc, const std::string &type);
void memsetErrorFloat(const Token *tok, const std::string &type);
void mallocOnClassError(const Token* tok, const std::string &memfunc, const Token* classTok, const std::string &classname);
void mallocOnClassWarning(const Token* tok, const std::string &memfunc, const Token* classTok);
void virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived, bool inconclusive);
void thisSubtractionError(const Token *tok);
void operatorEqRetRefThisError(const Token *tok);
void operatorEqShouldBeLeftUnimplementedError(const Token *tok);
void operatorEqMissingReturnStatementError(const Token *tok, bool error);
void operatorEqToSelfError(const Token *tok);
void checkConstError(const Token *tok, const std::string &classname, const std::string &funcname, bool suggestStatic);
void checkConstError2(const Token *tok1, const Token *tok2, const std::string &classname, const std::string &funcname, bool suggestStatic);
void initializerListError(const Token *tok1,const Token *tok2, const std::string & classname, const std::string &varname, const std::string& argname = {});
void suggestInitializationList(const Token *tok, const std::string& varname);
void selfInitializationError(const Token* tok, const std::string& varname);
void pureVirtualFunctionCallInConstructorError(const Function * scopeFunction, const std::list<const Token *> & tokStack, const std::string &purefuncname);
void virtualFunctionCallInConstructorError(const Function * scopeFunction, const std::list<const Token *> & tokStack, const std::string &funcname);
void duplInheritedMembersError(const Token* tok1, const Token* tok2, const std::string &derivedName, const std::string &baseName, const std::string &memberName, bool derivedIsStruct, bool baseIsStruct, bool isFunction = false);
void copyCtorAndEqOperatorError(const Token *tok, const std::string &classname, bool isStruct, bool hasCopyCtor);
void overrideError(const Function *funcInBase, const Function *funcInDerived);
void uselessOverrideError(const Function *funcInBase, const Function *funcInDerived, bool isSameCode = false);
void returnByReferenceError(const Function *func, const Variable* var);
void thisUseAfterFree(const Token *self, const Token *free, const Token *use);
void unsafeClassRefMemberError(const Token *tok, const std::string &varname);
void checkDuplInheritedMembersRecursive(const Type* typeCurrent, const Type* typeBase);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckClass c(nullptr, settings, errorLogger);
c.noConstructorError(nullptr, "classname", false);
c.noExplicitConstructorError(nullptr, "classname", false);
//c.copyConstructorMallocError(nullptr, 0, "var");
c.copyConstructorShallowCopyError(nullptr, "var");
c.noCopyConstructorError(nullptr, false, nullptr, false);
c.noOperatorEqError(nullptr, false, nullptr, false);
c.noDestructorError(nullptr, false, nullptr);
c.uninitVarError(nullptr, false, Function::eConstructor, "classname", "varname", false, false);
c.uninitVarError(nullptr, true, Function::eConstructor, "classname", "varnamepriv", false, false);
c.uninitVarError(nullptr, false, Function::eConstructor, "classname", "varname", true, false);
c.uninitVarError(nullptr, true, Function::eConstructor, "classname", "varnamepriv", true, false);
c.missingMemberCopyError(nullptr, Function::eConstructor, "classname", "varnamepriv");
c.operatorEqVarError(nullptr, "classname", emptyString, false);
c.unusedPrivateFunctionError(nullptr, "classname", "funcname");
c.memsetError(nullptr, "memfunc", "classname", "class");
c.memsetErrorReference(nullptr, "memfunc", "class");
c.memsetErrorFloat(nullptr, "class");
c.mallocOnClassWarning(nullptr, "malloc", nullptr);
c.mallocOnClassError(nullptr, "malloc", nullptr, "std::string");
c.virtualDestructorError(nullptr, "Base", "Derived", false);
c.thisSubtractionError(nullptr);
c.operatorEqRetRefThisError(nullptr);
c.operatorEqMissingReturnStatementError(nullptr, true);
c.operatorEqShouldBeLeftUnimplementedError(nullptr);
c.operatorEqToSelfError(nullptr);
c.checkConstError(nullptr, "class", "function", false);
c.checkConstError(nullptr, "class", "function", true);
c.initializerListError(nullptr, nullptr, "class", "variable");
c.suggestInitializationList(nullptr, "variable");
c.selfInitializationError(nullptr, "var");
c.duplInheritedMembersError(nullptr, nullptr, "class", "class", "variable", false, false);
c.copyCtorAndEqOperatorError(nullptr, "class", false, false);
c.overrideError(nullptr, nullptr);
c.uselessOverrideError(nullptr, nullptr);
c.returnByReferenceError(nullptr, nullptr);
c.pureVirtualFunctionCallInConstructorError(nullptr, std::list<const Token *>(), "f");
c.virtualFunctionCallInConstructorError(nullptr, std::list<const Token *>(), "f");
c.thisUseAfterFree(nullptr, nullptr, nullptr);
c.unsafeClassRefMemberError(nullptr, "UnsafeClass::var");
}
static std::string myName() {
return "Class";
}
std::string classInfo() const override {
return "Check the code for each class.\n"
"- Missing constructors and copy constructors\n"
//"- Missing allocation of memory in copy constructor\n"
"- Constructors which should be explicit\n"
"- Are all variables initialized by the constructors?\n"
"- Are all variables assigned by 'operator='?\n"
"- Warn if memset, memcpy etc are used on a class\n"
"- Warn if memory for classes is allocated with malloc()\n"
"- If it's a base class, check that the destructor is virtual\n"
"- Are there unused private functions?\n"
"- 'operator=' should check for assignment to self\n"
"- Constness for member functions\n"
"- Order of initializations\n"
"- Suggest usage of initialization list\n"
"- Initialization of a member with itself\n"
"- Suspicious subtraction from 'this'\n"
"- Call of pure virtual function in constructor/destructor\n"
"- Duplicated inherited data members\n"
// disabled for now "- If 'copy constructor' defined, 'operator=' also should be defined and vice versa\n"
"- Check that arbitrary usage of public interface does not result in division by zero\n"
"- Delete \"self pointer\" and then access 'this'\n"
"- Check that the 'override' keyword is used when overriding virtual functions\n"
"- Check that the 'one definition rule' is not violated\n";
}
// operatorEqRetRefThis helper functions
void checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last);
void checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last, std::set<const Function*>& analyzedFunctions);
// operatorEqToSelf helper functions
bool hasAllocation(const Function *func, const Scope* scope) const;
bool hasAllocation(const Function *func, const Scope* scope, const Token *start, const Token *end) const;
bool hasAllocationInIfScope(const Function *func, const Scope* scope, const Token *ifStatementScopeStart) const;
static bool hasAssignSelf(const Function *func, const Token *rhs, const Token *&out_ifStatementScopeStart);
enum class Bool : std::uint8_t { TRUE, FALSE, BAILOUT };
static Bool isInverted(const Token *tok, const Token *rhs);
static const Token * getIfStmtBodyStart(const Token *tok, const Token *rhs);
// checkConst helper functions
bool isMemberVar(const Scope *scope, const Token *tok) const;
static bool isMemberFunc(const Scope *scope, const Token *tok);
static bool isConstMemberFunc(const Scope *scope, const Token *tok);
enum class MemberAccess : std::uint8_t { NONE, SELF, MEMBER };
bool checkConstFunc(const Scope *scope, const Function *func, MemberAccess& memberAccessed) const;
// constructors helper function
/** @brief Information about a member variable. Used when checking for uninitialized variables */
struct Usage {
explicit Usage(const Variable *var) : var(var) {}
/** Variable that this usage is for */
const Variable *var;
/** @brief has this variable been assigned? */
bool assign{};
/** @brief has this variable been initialized? */
bool init{};
};
static bool isBaseClassMutableMemberFunc(const Token *tok, const Scope *scope);
/**
* @brief Create usage list that contains all scope members and also members
* of base classes without constructors.
* @param scope current class scope
*/
static std::vector<Usage> createUsageList(const Scope *scope);
/**
* @brief assign a variable in the varlist
* @param usageList reference to usage vector
* @param varid id of variable to mark assigned
*/
static void assignVar(std::vector<Usage> &usageList, nonneg int varid);
/**
* @brief assign a variable in the varlist
* @param usageList reference to usage vector
* @param vartok variable token
*/
static void assignVar(std::vector<Usage> &usageList, const Token *vartok);
/**
* @brief initialize a variable in the varlist
* @param usageList reference to usage vector
* @param varid id of variable to mark initialized
*/
static void initVar(std::vector<Usage> &usageList, nonneg int varid);
/**
* @brief set all variables in list assigned
* @param usageList reference to usage vector
*/
static void assignAllVar(std::vector<Usage> &usageList);
/**
* @brief set all variable in list assigned, if visible from given scope
* @param usageList reference to usage vector
* @param scope scope from which usages must be visible
*/
static void assignAllVarsVisibleFromScope(std::vector<Usage> &usageList, const Scope *scope);
/**
* @brief set all variables in list not assigned and not initialized
* @param usageList reference to usage vector
*/
static void clearAllVar(std::vector<Usage> &usageList);
/**
* @brief parse a scope for a constructor or member function and set the "init" flags in the provided varlist
* @param func reference to the function that should be checked
* @param callstack the function doesn't look into recursive function calls.
* @param scope pointer to variable Scope
* @param usage reference to usage vector
*/
void initializeVarList(const Function &func, std::list<const Function *> &callstack, const Scope *scope, std::vector<Usage> &usage) const;
/**
* @brief gives a list of tokens where virtual functions are called directly or indirectly
* @param function function to be checked
* @param virtualFunctionCallsMap map of results for already checked functions
* @return list of tokens where pure virtual functions are called
*/
const std::list<const Token *> & getVirtualFunctionCalls(
const Function & function,
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap);
/**
* @brief looks for the first virtual function call stack
* @param virtualFunctionCallsMap map of results obtained from getVirtualFunctionCalls
* @param callToken token where pure virtual function is called directly or indirectly
* @param[in,out] pureFuncStack list to append the stack
*/
static void getFirstVirtualFunctionCallStack(
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap,
const Token *callToken,
std::list<const Token *> & pureFuncStack);
static bool canNotCopy(const Scope *scope);
static bool canNotMove(const Scope *scope);
/**
* @brief Helper for checkThisUseAfterFree
*/
bool checkThisUseAfterFreeRecursive(const Scope *classScope, const Function *func, const Variable *selfPointer, std::set<const Function *> callstack, const Token *&freeToken);
};
/// @}
//---------------------------------------------------------------------------
#endif // checkclassH
| 20,658
|
C++
|
.h
| 354
| 51.935028
| 231
| 0.709571
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,425
|
vf_symbolicinfer.h
|
danmar_cppcheck/lib/vf_symbolicinfer.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfSymbolicInferH
#define vfSymbolicInferH
class SymbolDatabase;
class Settings;
namespace ValueFlow
{
void valueFlowSymbolicInfer(const SymbolDatabase& symboldatabase, const Settings& settings);
}
#endif // vfSymbolicInferH
| 1,002
|
C++
|
.h
| 26
| 36.615385
| 96
| 0.769547
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,426
|
vf_pointeralias.h
|
danmar_cppcheck/lib/vf_pointeralias.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfPointerAliasH
#define vfPointerAliasH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzePointerAlias(TokenList &tokenlist, const Settings& settings);
}
#endif // vfPointerAliasH
| 975
|
C++
|
.h
| 26
| 35.576923
| 77
| 0.764021
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,427
|
checkfunctions.h
|
danmar_cppcheck/lib/checkfunctions.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkfunctionsH
#define checkfunctionsH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "tokenize.h"
#include <map>
#include <string>
class Token;
class ErrorLogger;
namespace ValueFlow {
class Value;
} // namespace ValueFlow
/// @addtogroup Checks
/// @{
/**
* @brief Check for bad function usage
*/
class CPPCHECKLIB CheckFunctions : public Check {
public:
/** This constructor is used when registering the CheckFunctions */
CheckFunctions() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckFunctions checkFunctions(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkFunctions.checkIgnoredReturnValue();
checkFunctions.checkMissingReturn(); // Missing "return" in exit path
// --check-library : functions with nonmatching configuration
checkFunctions.checkLibraryMatchFunctions();
checkFunctions.checkProhibitedFunctions();
checkFunctions.invalidFunctionUsage();
checkFunctions.checkMathFunctions();
checkFunctions.memsetZeroBytes();
checkFunctions.memsetInvalid2ndParam();
checkFunctions.returnLocalStdMove();
checkFunctions.useStandardLibrary();
}
/** Check for functions that should not be used */
void checkProhibitedFunctions();
/**
* @brief Invalid function usage (invalid input value / overlapping data)
*
* %Check that given function parameters are valid according to the standard
* - wrong radix given for strtol/strtoul
* - overlapping data when using sprintf/snprintf
* - wrong input value according to library
*/
void invalidFunctionUsage();
/** @brief %Check for ignored return values. */
void checkIgnoredReturnValue();
/** @brief %Check for parameters given to math function that do not make sense*/
void checkMathFunctions();
/** @brief %Check for filling zero bytes with memset() */
void memsetZeroBytes();
/** @brief %Check for invalid 2nd parameter of memset() */
void memsetInvalid2ndParam();
/** @brief %Check for copy elision by RVO|NRVO */
void returnLocalStdMove();
void useStandardLibrary();
/** @brief --check-library: warn for unconfigured function calls */
void checkLibraryMatchFunctions();
/** @brief %Check for missing "return" */
void checkMissingReturn();
void invalidFunctionArgError(const Token *tok, const std::string &functionName, int argnr, const ValueFlow::Value *invalidValue, const std::string &validstr);
void invalidFunctionArgBoolError(const Token *tok, const std::string &functionName, int argnr);
void invalidFunctionArgStrError(const Token *tok, const std::string &functionName, nonneg int argnr);
void ignoredReturnValueError(const Token* tok, const std::string& function);
void ignoredReturnErrorCode(const Token* tok, const std::string& function);
void mathfunctionCallWarning(const Token *tok, nonneg int numParam = 1);
void mathfunctionCallWarning(const Token *tok, const std::string& oldexp, const std::string& newexp);
void memsetZeroBytesError(const Token *tok);
void memsetFloatError(const Token *tok, const std::string &var_value);
void memsetValueOutOfRangeError(const Token *tok, const std::string &value);
void missingReturnError(const Token *tok);
void copyElisionError(const Token *tok);
void useStandardLibraryError(const Token *tok, const std::string& expected);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckFunctions c(nullptr, settings, errorLogger);
for (std::map<std::string, Library::WarnInfo>::const_iterator i = settings->library.functionwarn().cbegin(); i != settings->library.functionwarn().cend(); ++i) {
c.reportError(nullptr, Severity::style, i->first+"Called", i->second.message);
}
c.invalidFunctionArgError(nullptr, "func_name", 1, nullptr,"1:4");
c.invalidFunctionArgBoolError(nullptr, "func_name", 1);
c.invalidFunctionArgStrError(nullptr, "func_name", 1);
c.ignoredReturnValueError(nullptr, "malloc");
c.mathfunctionCallWarning(nullptr);
c.mathfunctionCallWarning(nullptr, "1 - erf(x)", "erfc(x)");
c.memsetZeroBytesError(nullptr);
c.memsetFloatError(nullptr, "varname");
c.memsetValueOutOfRangeError(nullptr, "varname");
c.missingReturnError(nullptr);
c.copyElisionError(nullptr);
c.useStandardLibraryError(nullptr, "memcpy");
}
static std::string myName() {
return "Check function usage";
}
std::string classInfo() const override {
return "Check function usage:\n"
"- missing 'return' in non-void function\n"
"- return value of certain functions not used\n"
"- invalid input values for functions\n"
"- Warn if a function is called whose usage is discouraged\n"
"- memset() third argument is zero\n"
"- memset() with a value out of range as the 2nd parameter\n"
"- memset() with a float as the 2nd parameter\n"
"- copy elision optimization for returning value affected by std::move\n"
"- use memcpy()/memset() instead of for loop\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkfunctionsH
| 6,753
|
C++
|
.h
| 138
| 43.188406
| 169
| 0.682564
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,428
|
vf_number.h
|
danmar_cppcheck/lib/vf_number.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfNumberH
#define vfNumberH
class TokenList;
class Settings;
namespace ValueFlow
{
void analyzeNumber(TokenList &tokenlist, const Settings& settings);
}
#endif // vfNumberH
| 951
|
C++
|
.h
| 26
| 34.653846
| 72
| 0.757872
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,429
|
checkleakautovar.h
|
danmar_cppcheck/lib/checkleakautovar.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkleakautovarH
#define checkleakautovarH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "library.h"
#include "tokenize.h"
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <utility>
class ErrorLogger;
class Settings;
class Token;
class CPPCHECKLIB VarInfo {
public:
enum AllocStatus : std::int8_t { REALLOC = -3, OWNED = -2, DEALLOC = -1, NOALLOC = 0, ALLOC = 1 };
struct AllocInfo {
AllocStatus status;
/** Allocation type. If it is a positive value then it corresponds to
* a Library allocation id. A negative value is a builtin
* checkleakautovar allocation type.
*/
int type;
int reallocedFromType = -1;
const Token * allocTok;
explicit AllocInfo(int type_ = 0, AllocStatus status_ = NOALLOC, const Token* allocTok_ = nullptr) : status(status_), type(type_), allocTok(allocTok_) {}
bool managed() const {
return status < 0;
}
};
enum Usage : std::uint8_t { USED, NORET };
std::map<int, AllocInfo> alloctype;
std::map<int, std::pair<const Token*, Usage>> possibleUsage;
std::set<int> conditionalAlloc;
std::set<int> referenced;
void clear() {
alloctype.clear();
possibleUsage.clear();
conditionalAlloc.clear();
referenced.clear();
}
void erase(nonneg int varid) {
alloctype.erase(varid);
possibleUsage.erase(varid);
conditionalAlloc.erase(varid);
referenced.erase(varid);
}
void swap(VarInfo &other) NOEXCEPT {
alloctype.swap(other.alloctype);
possibleUsage.swap(other.possibleUsage);
conditionalAlloc.swap(other.conditionalAlloc);
referenced.swap(other.referenced);
}
void reallocToAlloc(nonneg int varid) {
const AllocInfo& alloc = alloctype[varid];
if (alloc.reallocedFromType >= 0) {
const std::map<int, VarInfo::AllocInfo>::iterator it = alloctype.find(alloc.reallocedFromType);
if (it != alloctype.end() && it->second.status == REALLOC) {
it->second.status = ALLOC;
}
}
}
/** set possible usage for all variables */
void possibleUsageAll(const std::pair<const Token*, Usage>& functionUsage);
};
/// @addtogroup Checks
/// @{
/**
* @brief Check for leaks
*/
class CPPCHECKLIB CheckLeakAutoVar : public Check {
public:
/** This constructor is used when registering the CheckLeakAutoVar */
CheckLeakAutoVar() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckLeakAutoVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckLeakAutoVar checkLeakAutoVar(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkLeakAutoVar.check();
}
/** check for leaks in all scopes */
void check();
/** check for leaks in a function scope */
bool checkScope(const Token * startToken,
VarInfo &varInfo,
std::set<int> notzero,
nonneg int recursiveCount);
/** Check token inside expression.
* @param tok token inside expression.
* @param varInfo Variable info
* @return next token to process (if no other checks needed for this token). NULL if other checks could be performed.
*/
const Token * checkTokenInsideExpression(const Token * tok, VarInfo &varInfo, bool inFuncCall = false);
/** parse function call */
void functionCall(const Token *tokName, const Token *tokOpeningPar, VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Library::AllocFunc* af);
/** parse changes in allocation status */
void changeAllocStatus(VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Token* tok, const Token* arg);
/** update allocation status if reallocation function */
void changeAllocStatusIfRealloc(std::map<int, VarInfo::AllocInfo> &alloctype, const Token *fTok, const Token *retTok) const;
/** return. either "return" or end of variable scope is seen */
void ret(const Token *tok, VarInfo &varInfo, bool isEndOfScope = false);
/** if variable is allocated then there is a leak */
void leakIfAllocated(const Token *vartok, const VarInfo &varInfo);
void leakError(const Token* tok, const std::string &varname, int type) const;
void mismatchError(const Token* deallocTok, const Token* allocTok, const std::string &varname) const;
void deallocUseError(const Token *tok, const std::string &varname) const;
void deallocReturnError(const Token *tok, const Token *deallocTok, const std::string &varname);
void doubleFreeError(const Token *tok, const Token *prevFreeTok, const std::string &varname, int type);
/** message: user configuration is needed to complete analysis */
void configurationInfo(const Token* tok, const std::pair<const Token*, VarInfo::Usage>& functionUsage);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckLeakAutoVar c(nullptr, settings, errorLogger);
c.deallocReturnError(nullptr, nullptr, "p");
c.configurationInfo(nullptr, { nullptr, VarInfo::USED }); // user configuration is needed to complete analysis
c.doubleFreeError(nullptr, nullptr, "varname", 0);
}
static std::string myName() {
return "Leaks (auto variables)";
}
std::string classInfo() const override {
return "Detect when a auto variable is allocated but not deallocated or deallocated twice.\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkleakautovarH
| 6,781
|
C++
|
.h
| 148
| 40.162162
| 161
| 0.668687
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,430
|
suppressions.h
|
danmar_cppcheck/lib/suppressions.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef suppressionsH
#define suppressionsH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstddef>
#include <cstdint>
#include <istream>
#include <list>
#include <set>
#include <string>
#include <utility>
#include <vector>
/// @addtogroup Core
/// @{
class Tokenizer;
class ErrorMessage;
class ErrorLogger;
enum class Certainty : std::uint8_t;
class FileWithDetails;
/** @brief class for handling suppressions */
class CPPCHECKLIB SuppressionList {
public:
enum class Type : std::uint8_t {
unique, file, block, blockBegin, blockEnd, macro
};
struct CPPCHECKLIB ErrorMessage {
std::size_t hash;
std::string errorId;
void setFileName(std::string s);
const std::string &getFileName() const {
return mFileName;
}
int lineNumber;
Certainty certainty;
std::string symbolNames;
std::set<std::string> macroNames;
static SuppressionList::ErrorMessage fromErrorMessage(const ::ErrorMessage &msg, const std::set<std::string> ¯oNames);
private:
std::string mFileName;
};
struct CPPCHECKLIB Suppression {
Suppression() = default;
Suppression(std::string id, std::string file, int line=NO_LINE) : errorId(std::move(id)), fileName(std::move(file)), lineNumber(line) {}
bool operator<(const Suppression &other) const {
if (errorId != other.errorId)
return errorId < other.errorId;
if (lineNumber < other.lineNumber)
return true;
if (fileName != other.fileName)
return fileName < other.fileName;
if (symbolName != other.symbolName)
return symbolName < other.symbolName;
if (macroName != other.macroName)
return macroName < other.macroName;
if (hash != other.hash)
return hash < other.hash;
if (thisAndNextLine != other.thisAndNextLine)
return thisAndNextLine;
return false;
}
bool operator==(const Suppression &other) const {
if (errorId != other.errorId)
return false;
if (lineNumber < other.lineNumber)
return false;
if (fileName != other.fileName)
return false;
if (symbolName != other.symbolName)
return false;
if (macroName != other.macroName)
return false;
if (hash != other.hash)
return false;
if (type != other.type)
return false;
if (lineBegin != other.lineBegin)
return false;
if (lineEnd != other.lineEnd)
return false;
return true;
}
/**
* Parse inline suppression in comment
* @param comment the full comment text
* @param errorMessage output parameter for error message (wrong suppression attribute)
* @return true if it is a inline comment.
*/
bool parseComment(std::string comment, std::string *errorMessage);
bool isSuppressed(const ErrorMessage &errmsg) const;
bool isMatch(const ErrorMessage &errmsg);
std::string getText() const;
bool isLocal() const {
return !fileName.empty() && fileName.find_first_of("?*") == std::string::npos;
}
bool isSameParameters(const Suppression &other) const {
return errorId == other.errorId &&
fileName == other.fileName &&
lineNumber == other.lineNumber &&
symbolName == other.symbolName &&
hash == other.hash &&
thisAndNextLine == other.thisAndNextLine;
}
std::string errorId;
std::string fileName;
int lineNumber = NO_LINE;
int lineBegin = NO_LINE;
int lineEnd = NO_LINE;
Type type = Type::unique;
std::string symbolName;
std::string macroName;
std::size_t hash{};
bool thisAndNextLine{}; // Special case for backwards compatibility: { // cppcheck-suppress something
bool matched{};
bool checked{}; // for inline suppressions, checked or not
enum : std::int8_t { NO_LINE = -1 };
};
/**
* @brief Don't show errors listed in the file.
* @param istr Open file stream where errors can be read.
* @return error message. empty upon success
*/
std::string parseFile(std::istream &istr);
/**
* @brief Don't show errors listed in the file.
* @param filename file name
* @return error message. empty upon success
*/
std::string parseXmlFile(const char *filename);
/**
* Parse multi inline suppression in comment
* @param comment the full comment text
* @param errorMessage output parameter for error message (wrong suppression attribute)
* @return empty vector if something wrong.
*/
static std::vector<Suppression> parseMultiSuppressComment(const std::string &comment, std::string *errorMessage);
/**
* @brief Don't show the given error.
* @param line Description of error to suppress (in id:file:line format).
* @return error message. empty upon success
*/
std::string addSuppressionLine(const std::string &line);
/**
* @brief Don't show this error. File and/or line are optional. In which case
* the errorId alone is used for filtering.
* @param suppression suppression details
* @return error message. empty upon success
*/
std::string addSuppression(Suppression suppression);
/**
* @brief Combine list of suppressions into the current suppressions.
* @param suppressions list of suppression details
* @return error message. empty upon success
*/
std::string addSuppressions(std::list<Suppression> suppressions);
/**
* @brief Returns true if this message should not be shown to the user.
* @param errmsg error message
* @param global use global suppressions
* @return true if this error is suppressed.
*/
bool isSuppressed(const ErrorMessage &errmsg, bool global = true);
/**
* @brief Returns true if this message is "explicitly" suppressed. The suppression "id" must match textually exactly.
* @param errmsg error message
* @param global use global suppressions
* @return true if this error is explicitly suppressed.
*/
bool isSuppressedExplicitly(const ErrorMessage &errmsg, bool global = true);
/**
* @brief Returns true if this message should not be shown to the user.
* @param errmsg error message
* @return true if this error is suppressed.
*/
bool isSuppressed(const ::ErrorMessage &errmsg, const std::set<std::string>& macroNames);
/**
* @brief Create an xml dump of suppressions
* @param out stream to write XML to
*/
void dump(std::ostream &out) const;
/**
* @brief Returns list of unmatched local (per-file) suppressions.
* @return list of unmatched suppressions
*/
std::list<Suppression> getUnmatchedLocalSuppressions(const FileWithDetails &file, bool unusedFunctionChecking) const;
/**
* @brief Returns list of unmatched global (glob pattern) suppressions.
* @return list of unmatched suppressions
*/
std::list<Suppression> getUnmatchedGlobalSuppressions(bool unusedFunctionChecking) const;
/**
* @brief Returns list of all suppressions.
* @return list of suppressions
*/
const std::list<Suppression> &getSuppressions() const;
/**
* @brief Marks Inline Suppressions as checked if source line is in the token stream
*/
void markUnmatchedInlineSuppressionsAsChecked(const Tokenizer &tokenizer);
/**
* Report unmatched suppressions
* @param unmatched list of unmatched suppressions (from Settings::Suppressions::getUnmatched(Local|Global)Suppressions)
* @return true is returned if errors are reported
*/
static bool reportUnmatchedSuppressions(const std::list<SuppressionList::Suppression> &unmatched, ErrorLogger &errorLogger);
private:
/** @brief List of error which the user doesn't want to see. */
std::list<Suppression> mSuppressions;
};
struct Suppressions
{
/** @brief suppress message (--suppressions) */
SuppressionList nomsg;
/** @brief suppress exitcode */
SuppressionList nofail;
};
/// @}
//---------------------------------------------------------------------------
#endif // suppressionsH
| 9,519
|
C++
|
.h
| 236
| 33.050847
| 144
| 0.637357
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
26,431
|
findtoken.h
|
danmar_cppcheck/lib/findtoken.h
|
/* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef findtokenH
#define findtokenH
//---------------------------------------------------------------------------
#include <functional>
#include <stack>
#include <string>
#include <type_traits>
#include <vector>
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "smallvector.h"
#include "symboldatabase.h"
#include "token.h"
inline std::vector<MathLib::bigint> evaluateKnownValues(const Token* tok)
{
if (!tok->hasKnownIntValue())
return {};
return {tok->getKnownIntValue()};
}
template<class T, class Predicate, class Found, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
void findTokensImpl(T* start, const Token* end, const Predicate& pred, Found found)
{
for (T* tok = start; precedes(tok, end); tok = tok->next()) {
if (pred(tok)) {
if (found(tok))
break;
}
}
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokens(T* start, const Token* end, const Predicate& pred)
{
std::vector<T*> result;
findTokensImpl(start, end, pred, [&](T* tok) {
result.push_back(tok);
return false;
});
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findToken(T* start, const Token* end, const Predicate& pred)
{
T* result = nullptr;
findTokensImpl(start, end, pred, [&](T* tok) {
result = tok;
return true;
});
return result;
}
template<class T,
class Predicate,
class Found,
class Evaluate,
REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
bool findTokensSkipDeadCodeImpl(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
Found found,
const Evaluate& evaluate,
bool skipUnevaluated)
{
for (T* tok = start; precedes(tok, end); tok = tok->next()) {
if (pred(tok)) {
if (found(tok))
return true;
}
if (Token::Match(tok, "if|for|while (") && Token::simpleMatch(tok->linkAt(1), ") {")) {
const Token* condTok = getCondTok(tok);
if (!condTok)
continue;
auto result = evaluate(condTok);
if (result.empty())
continue;
if (findTokensSkipDeadCodeImpl(library, tok->next(), tok->linkAt(1), pred, found, evaluate, skipUnevaluated))
return true;
T* thenStart = tok->linkAt(1)->next();
T* elseStart = nullptr;
if (Token::simpleMatch(thenStart->link(), "} else {"))
elseStart = thenStart->link()->tokAt(2);
int r = result.front();
if (r == 0) {
if (elseStart) {
if (findTokensSkipDeadCodeImpl(library, elseStart, elseStart->link(), pred, found, evaluate, skipUnevaluated))
return true;
if (isReturnScope(elseStart->link(), library))
return true;
tok = elseStart->link();
} else {
tok = thenStart->link();
}
} else {
if (findTokensSkipDeadCodeImpl(library, thenStart, thenStart->link(), pred, found, evaluate, skipUnevaluated))
return true;
if (isReturnScope(thenStart->link(), library))
return true;
tok = thenStart->link();
}
} else if (Token::Match(tok->astParent(), "&&|?|%oror%") && astIsLHS(tok)) {
auto result = evaluate(tok);
if (result.empty())
continue;
const bool cond = result.front() != 0;
T* next = nullptr;
if ((cond && Token::simpleMatch(tok->astParent(), "||")) ||
(!cond && Token::simpleMatch(tok->astParent(), "&&"))) {
next = nextAfterAstRightmostLeaf(tok->astParent());
} else if (Token::simpleMatch(tok->astParent(), "?")) {
T* colon = tok->astParent()->astOperand2();
if (!cond) {
next = colon;
} else {
if (findTokensSkipDeadCodeImpl(library, tok->astParent()->next(), colon, pred, found, evaluate, skipUnevaluated))
return true;
next = nextAfterAstRightmostLeaf(colon);
}
}
if (next)
tok = next;
} else if (Token::simpleMatch(tok, "} else {")) {
const Token* condTok = getCondTokFromEnd(tok);
if (!condTok)
continue;
auto result = evaluate(condTok);
if (result.empty())
continue;
if (isReturnScope(tok->link(), library))
return true;
int r = result.front();
if (r != 0) {
tok = tok->linkAt(2);
}
} else if (Token::simpleMatch(tok, "[") && Token::Match(tok->link(), "] (|{")) {
T* afterCapture = tok->link()->next();
if (Token::simpleMatch(afterCapture, "(") && afterCapture->link())
tok = afterCapture->link()->next();
else
tok = afterCapture;
}
if (skipUnevaluated && isUnevaluated(tok)) {
T *next = tok->linkAt(1);
if (!next)
continue;
tok = next;
}
}
return false;
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadCode(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
const Evaluate& evaluate)
{
std::vector<T*> result;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result.push_back(tok);
return false;
},
evaluate,
false);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokensSkipDeadCode(library, start, end, pred, &evaluateKnownValues);
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadAndUnevaluatedCode(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
const Evaluate& evaluate)
{
std::vector<T*> result;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result.push_back(tok);
return false;
},
evaluate,
true);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadAndUnevaluatedCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokensSkipDeadAndUnevaluatedCode(library, start, end, pred, &evaluateKnownValues);
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findTokenSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred, const Evaluate& evaluate)
{
T* result = nullptr;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result = tok;
return true;
},
evaluate,
false);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findTokenSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokenSkipDeadCode(library, start, end, pred, &evaluateKnownValues);
}
#endif // findtokenH
| 9,558
|
C++
|
.h
| 242
| 29.367769
| 133
| 0.551457
|
danmar/cppcheck
| 5,720
| 1,444
| 118
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.