Check for JSON error when parsing addon .json files + fixes (#2374)

* cppcheck.cpp: Check for JSON error when parsing addon .json files

This fixes that errors in JSON files given via `--addon=*.json` are
silently ignored and maybe only a part of the JSON file is used.
Now the error message which picojson can return is checked and a
corresponding error message is returned again by getAddonInfo().

* naming.json: Fix missing comma

* CLI: Fix naming violations detected by addon naming.py via naming.json

* Addon naming: Add argument for validating names of constants

* LIB: Rename functions/variables so they are valid, loosen naming rules

* GUI: Fix naming violations
This commit is contained in:
Sebastian 2019-11-20 15:37:09 +01:00 committed by GitHub
parent feeb27f3c9
commit c990d10ffa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 168 additions and 147 deletions

View File

@ -21,12 +21,16 @@ def validate_regex(expr):
RE_VARNAME = None
RE_CONSTNAME = None
RE_PRIVATE_MEMBER_VARIABLE = None
RE_FUNCTIONNAME = None
for arg in sys.argv[1:]:
if arg[:6] == '--var=':
RE_VARNAME = arg[6:]
validate_regex(RE_VARNAME)
elif arg.startswith('--const='):
RE_CONSTNAME = arg[arg.find('=')+1:]
validate_regex(RE_CONSTNAME)
elif arg.startswith('--private-member-variable='):
RE_PRIVATE_MEMBER_VARIABLE = arg[arg.find('=')+1:]
validate_regex(RE_PRIVATE_MEMBER_VARIABLE)
@ -49,11 +53,22 @@ for arg in sys.argv[1:]:
print('Checking ' + arg + ', config "' + cfg.name + '"...')
if RE_VARNAME:
for var in cfg.variables:
if var.nameToken:
if var.access == 'Private':
continue
if var.nameToken and not var.isConst:
res = re.match(RE_VARNAME, var.nameToken.str)
if not res:
reportError(var.typeStartToken, 'style', 'Variable ' +
var.nameToken.str + ' violates naming convention', 'varname')
if RE_CONSTNAME:
for var in cfg.variables:
if var.access == 'Private':
continue
if var.nameToken and var.isConst:
res = re.match(RE_CONSTNAME, var.nameToken.str)
if not res:
reportError(var.typeStartToken, 'style', 'Constant ' +
var.nameToken.str + ' violates naming convention', 'constname')
if RE_PRIVATE_MEMBER_VARIABLE:
for var in cfg.variables:
if (var.access is None) or var.access != 'Private':

View File

@ -44,42 +44,42 @@
#include <tinyxml2.h>
#endif
static void addFilesToList(const std::string& FileList, std::vector<std::string>& PathNames)
static void addFilesToList(const std::string& fileList, std::vector<std::string>& pathNames)
{
// To keep things initially simple, if the file can't be opened, just be silent and move on.
std::istream *Files;
std::ifstream Infile;
if (FileList == "-") { // read from stdin
Files = &std::cin;
std::istream *files;
std::ifstream infile;
if (fileList == "-") { // read from stdin
files = &std::cin;
} else {
Infile.open(FileList);
Files = &Infile;
infile.open(fileList);
files = &infile;
}
if (Files && *Files) {
std::string FileName;
while (std::getline(*Files, FileName)) { // next line
if (!FileName.empty()) {
PathNames.push_back(FileName);
if (files && *files) {
std::string fileName;
while (std::getline(*files, fileName)) { // next line
if (!fileName.empty()) {
pathNames.push_back(fileName);
}
}
}
}
static bool addIncludePathsToList(const std::string& FileList, std::list<std::string>* PathNames)
static bool addIncludePathsToList(const std::string& fileList, std::list<std::string>* pathNames)
{
std::ifstream Files(FileList);
if (Files) {
std::string PathName;
while (std::getline(Files, PathName)) { // next line
if (!PathName.empty()) {
PathName = Path::removeQuotationMarks(PathName);
PathName = Path::fromNativeSeparators(PathName);
std::ifstream files(fileList);
if (files) {
std::string pathName;
while (std::getline(files, pathName)) { // next line
if (!pathName.empty()) {
pathName = Path::removeQuotationMarks(pathName);
pathName = Path::fromNativeSeparators(pathName);
// If path doesn't end with / or \, add it
if (!endsWith(PathName, '/'))
PathName += '/';
if (!endsWith(pathName, '/'))
pathName += '/';
PathNames->push_back(PathName);
pathNames->push_back(pathName);
}
}
return true;
@ -87,10 +87,10 @@ static bool addIncludePathsToList(const std::string& FileList, std::list<std::st
return false;
}
static bool addPathsToSet(const std::string& FileName, std::set<std::string>* set)
static bool addPathsToSet(const std::string& fileName, std::set<std::string>* set)
{
std::list<std::string> templist;
if (!addIncludePathsToList(FileName, &templist))
if (!addIncludePathsToList(fileName, &templist))
return false;
set->insert(templist.begin(), templist.end());
return true;

View File

@ -208,7 +208,7 @@ void CppCheckExecutor::setSettings(const Settings &settings)
* \return size of array
* */
template<typename T, int size>
std::size_t GetArrayLength(const T(&)[size])
std::size_t getArrayLength(const T(&)[size])
{
return size;
}
@ -228,7 +228,7 @@ static void print_stacktrace(FILE* output, bool demangling, int maxdepth, bool l
#define ADDRESSDISPLAYLENGTH ((sizeof(long)==8)?12:8)
const int fd = fileno(output);
void *callstackArray[32]= {nullptr}; // the less resources the better...
const int currentdepth = backtrace(callstackArray, (int)GetArrayLength(callstackArray));
const int currentdepth = backtrace(callstackArray, (int)getArrayLength(callstackArray));
const int offset=2; // some entries on top are within our own exception handling code or libc
if (maxdepth<0)
maxdepth=currentdepth-offset;
@ -256,7 +256,7 @@ static void print_stacktrace(FILE* output, bool demangling, int maxdepth, bool l
char input_buffer[1024]= {0};
strncpy(input_buffer, firstBracketName+1, plus-firstBracketName-1);
char output_buffer[2048]= {0};
size_t length = GetArrayLength(output_buffer);
size_t length = getArrayLength(output_buffer);
int status=0;
// We're violating the specification - passing stack address instead of malloc'ed heap.
// Benefit is that no further heap is required, while there is sufficient stack...
@ -539,7 +539,7 @@ static void CppcheckSignalHandler(int signo, siginfo_t * info, void * context)
namespace {
const ULONG maxnamelength = 512;
struct IMAGEHLP_SYMBOL64_EXT : public IMAGEHLP_SYMBOL64 {
TCHAR NameExt[maxnamelength]; // actually no need to worry about character encoding here
TCHAR nameExt[maxnamelength]; // actually no need to worry about character encoding here
};
typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
fpStackWalk64 pStackWalk64;
@ -574,7 +574,7 @@ namespace {
}
void PrintCallstack(FILE* outputFile, PEXCEPTION_POINTERS ex)
void printCallstack(FILE* outputFile, PEXCEPTION_POINTERS ex)
{
if (!loadDbgHelp())
return;
@ -628,7 +628,7 @@ namespace {
break;
pSymGetSymFromAddr64(hProcess, (ULONG64)stack.AddrPC.Offset, &displacement, &symbol);
TCHAR undname[maxnamelength]= {0};
pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)GetArrayLength(undname), UNDNAME_COMPLETE);
pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)getArrayLength(undname), UNDNAME_COMPLETE);
if (beyond_main>=0)
++beyond_main;
if (_tcscmp(undname, _T("main"))==0)
@ -751,7 +751,7 @@ namespace {
break;
}
fputc('\n', outputFile);
PrintCallstack(outputFile, ex);
printCallstack(outputFile, ex);
fflush(outputFile);
return EXCEPTION_EXECUTE_HANDLER;
}

View File

@ -40,7 +40,7 @@
// When compiling Unicode targets WinAPI automatically uses *W Unicode versions
// of called functions. Thus, we explicitly call *A versions of the functions.
static BOOL MyIsDirectory(const std::string& path)
static BOOL myIsDirectory(const std::string& path)
{
#ifdef __BORLANDC__
return (GetFileAttributes(path.c_str()) & FILE_ATTRIBUTE_DIRECTORY);
@ -50,13 +50,13 @@ static BOOL MyIsDirectory(const std::string& path)
#endif
}
static HANDLE MyFindFirstFile(const std::string& path, LPWIN32_FIND_DATAA findData)
static HANDLE myFindFirstFile(const std::string& path, LPWIN32_FIND_DATAA findData)
{
HANDLE hFind = FindFirstFileA(path.c_str(), findData);
return hFind;
}
static BOOL MyFileExists(const std::string& path)
static BOOL myFileExists(const std::string& path)
{
#ifdef __BORLANDC__
DWORD fa = GetFileAttributes(path.c_str());
@ -86,7 +86,7 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
std::string searchPattern = cleanedPath;
// The user wants to check all files in a dir
const bool checkAllFilesInDir = (MyIsDirectory(cleanedPath) != FALSE);
const bool checkAllFilesInDir = (myIsDirectory(cleanedPath) != FALSE);
if (checkAllFilesInDir) {
const char c = cleanedPath.back();
@ -111,7 +111,7 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
}
WIN32_FIND_DATAA ffd;
HANDLE hFind = MyFindFirstFile(searchPattern, &ffd);
HANDLE hFind = myFindFirstFile(searchPattern, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
return;
@ -152,12 +152,12 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
bool FileLister::isDirectory(const std::string &path)
{
return (MyIsDirectory(path) != FALSE);
return (myIsDirectory(path) != FALSE);
}
bool FileLister::fileExists(const std::string &path)
{
return (MyFileExists(path) != FALSE);
return (myFileExists(path) != FALSE);
}

View File

@ -122,12 +122,12 @@ void CheckThread::runAddonsAndTools(const ImportProject::FileSettings *fileSetti
continue;
QStringList args;
for (std::list<std::string>::const_iterator I = fileSettings->includePaths.begin(); I != fileSettings->includePaths.end(); ++I)
args << ("-I" + QString::fromStdString(*I));
for (std::list<std::string>::const_iterator incIt = fileSettings->includePaths.begin(); incIt != fileSettings->includePaths.end(); ++incIt)
args << ("-I" + QString::fromStdString(*incIt));
for (std::list<std::string>::const_iterator i = fileSettings->systemIncludePaths.begin(); i != fileSettings->systemIncludePaths.end(); ++i)
args << "-isystem" << QString::fromStdString(*i);
foreach (QString D, QString::fromStdString(fileSettings->defines).split(";")) {
args << ("-D" + D);
foreach (QString def, QString::fromStdString(fileSettings->defines).split(";")) {
args << ("-D" + def);
}
foreach (const std::string& U, fileSettings->undefs) {
args << QString::fromStdString("-U" + U);

View File

@ -415,16 +415,16 @@ void CheckFunctions::checkLibraryMatchFunctions()
if (!mSettings->checkLibrary || !mSettings->isEnabled(Settings::INFORMATION))
return;
bool New = false;
bool insideNew = false;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->scope() || !tok->scope()->isExecutable())
continue;
if (tok->str() == "new")
New = true;
insideNew = true;
else if (tok->str() == ";")
New = false;
else if (New)
insideNew = false;
else if (insideNew)
continue;
if (!Token::Match(tok, "%name% (") || Token::Match(tok, "asm|sizeof|catch"))

View File

@ -637,7 +637,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
if (allocation.status == VarInfo::NOALLOC && Token::simpleMatch(tok, ") ; }")) {
const std::string &functionName(tok->link()->previous()->str());
bool unknown = false;
if (mTokenizer->IsScopeNoReturn(tok->tokAt(2), &unknown)) {
if (mTokenizer->isScopeNoReturn(tok->tokAt(2), &unknown)) {
if (!unknown)
varInfo->clear();
else if (!mSettings->library.isLeakIgnore(functionName) && !mSettings->library.isUse(functionName))

View File

@ -559,7 +559,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage()
if (Token::simpleMatch(tokEndRealloc->next(), "; if (") &&
notvar(tokEndRealloc->tokAt(3)->astOperand2(), tok->varId())) {
const Token* tokEndBrace = tokEndRealloc->linkAt(3)->linkAt(1);
if (tokEndBrace && mTokenizer->IsScopeNoReturn(tokEndBrace))
if (tokEndBrace && mTokenizer->isScopeNoReturn(tokEndBrace))
continue;
}
@ -606,8 +606,8 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
const std::string& classname = scope->className;
// Check if member variable has been allocated and deallocated..
CheckMemoryLeak::AllocType Alloc = CheckMemoryLeak::No;
CheckMemoryLeak::AllocType Dealloc = CheckMemoryLeak::No;
CheckMemoryLeak::AllocType memberAlloc = CheckMemoryLeak::No;
CheckMemoryLeak::AllocType memberDealloc = CheckMemoryLeak::No;
bool allocInConstructor = false;
bool deallocInDestructor = false;
@ -619,7 +619,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
if (!func.hasBody()) {
if (destructor) { // implementation for destructor is not seen => assume it deallocates all variables properly
deallocInDestructor = true;
Dealloc = CheckMemoryLeak::Many;
memberDealloc = CheckMemoryLeak::Many;
}
continue;
}
@ -652,16 +652,16 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
if (constructor)
allocInConstructor = true;
if (Alloc != No && Alloc != alloc)
if (memberAlloc != No && memberAlloc != alloc)
alloc = CheckMemoryLeak::Many;
if (alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) {
if (alloc != CheckMemoryLeak::Many && memberDealloc != CheckMemoryLeak::No && memberDealloc != CheckMemoryLeak::Many && memberDealloc != alloc) {
std::list<const Token *> callstack;
callstack.push_back(tok);
mismatchAllocDealloc(callstack, classname + "::" + varname);
}
Alloc = alloc;
memberAlloc = alloc;
}
}
@ -679,16 +679,16 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
deallocInDestructor = true;
// several types of allocation/deallocation?
if (Dealloc != CheckMemoryLeak::No && Dealloc != dealloc)
if (memberDealloc != CheckMemoryLeak::No && memberDealloc != dealloc)
dealloc = CheckMemoryLeak::Many;
if (dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) {
if (dealloc != CheckMemoryLeak::Many && memberAlloc != CheckMemoryLeak::No && memberAlloc != Many && memberAlloc != dealloc) {
std::list<const Token *> callstack;
callstack.push_back(tok);
mismatchAllocDealloc(callstack, classname + "::" + varname);
}
Dealloc = dealloc;
memberDealloc = dealloc;
}
// Function call .. possible deallocation
@ -702,9 +702,9 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
}
if (allocInConstructor && !deallocInDestructor) {
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, Alloc*/);
} else if (Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) {
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, Alloc*/);
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
} else if (memberAlloc != CheckMemoryLeak::No && memberDealloc == CheckMemoryLeak::No) {
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
}
}

View File

@ -247,13 +247,13 @@ void CheckOther::checkSuspiciousSemicolon()
if (Token::simpleMatch(scope.bodyStart, "{ ; } {") &&
scope.bodyStart->previous()->linenr() == scope.bodyStart->tokAt(2)->linenr()
&& scope.bodyStart->linenr()+1 >= scope.bodyStart->tokAt(3)->linenr()) {
SuspiciousSemicolonError(scope.classDef);
suspiciousSemicolonError(scope.classDef);
}
}
}
}
void CheckOther::SuspiciousSemicolonError(const Token* tok)
void CheckOther::suspiciousSemicolonError(const Token* tok)
{
reportError(tok, Severity::warning, "suspiciousSemicolon",
"Suspicious use of ; at the end of '" + (tok ? tok->str() : std::string()) + "' statement.", CWE398, true);

View File

@ -250,7 +250,7 @@ private:
void pointerLessThanZeroError(const Token *tok, const ValueFlow::Value *v);
void unsignedPositiveError(const Token *tok, const ValueFlow::Value *v, const std::string &varname);
void pointerPositiveError(const Token *tok, const ValueFlow::Value *v);
void SuspiciousSemicolonError(const Token *tok);
void suspiciousSemicolonError(const Token *tok);
void negativeBitwiseShiftError(const Token *tok, int op);
void redundantCopyError(const Token *tok, const std::string &varname);
void incompleteArrayFillError(const Token* tok, const std::string& buffer, const std::string& function, bool boolean);
@ -316,7 +316,7 @@ private:
c.unsignedPositiveError(nullptr, nullptr, "varname");
c.pointerLessThanZeroError(nullptr, nullptr);
c.pointerPositiveError(nullptr, nullptr);
c.SuspiciousSemicolonError(nullptr);
c.suspiciousSemicolonError(nullptr);
c.incompleteArrayFillError(nullptr, "buffer", "memset", false);
c.varFuncNullUBError(nullptr);
c.nanInArithmeticExpressionError(nullptr);

View File

@ -372,7 +372,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var
*possibleInit = true;
// might be a noreturn function..
if (mTokenizer->IsScopeNoReturn(tok)) {
if (mTokenizer->isScopeNoReturn(tok)) {
if (noreturn)
*noreturn = true;
return false;

View File

@ -55,7 +55,7 @@
static const char Version[] = CPPCHECK_VERSION_STRING;
static const char ExtraVersion[] = "";
static TimerResults S_timerResults;
static TimerResults s_timerResults;
// CWE ids used
static const CWE CWE398(398U); // Indicator of Poor Code Quality
@ -115,6 +115,10 @@ namespace {
return "Failed to open " + fileName;
picojson::value json;
fin >> json;
std::string json_error = picojson::get_last_error();
if (!json_error.empty()) {
return "Loading " + fileName + " failed. " + json_error;
}
if (!json.is<picojson::object>())
return "Loading " + fileName + " failed. Bad json.";
picojson::object obj = json.get<picojson::object>();
@ -173,7 +177,7 @@ CppCheck::~CppCheck()
delete mFileInfo.back();
mFileInfo.pop_back();
}
S_timerResults.ShowResults(mSettings.showtime);
s_timerResults.showResults(mSettings.showtime);
}
const char * CppCheck::version()
@ -387,7 +391,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// Get configurations..
if ((mSettings.checkAllConfigurations && mSettings.userDefines.empty()) || mSettings.force) {
Timer t("Preprocessor::getConfigs", mSettings.showtime, &S_timerResults);
Timer t("Preprocessor::getConfigs", mSettings.showtime, &s_timerResults);
configurations = preprocessor.getConfigs(tokens1);
} else {
configurations.insert(mSettings.userDefines);
@ -453,9 +457,9 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
}
if (mSettings.preprocessOnly) {
Timer t("Preprocessor::getcode", mSettings.showtime, &S_timerResults);
Timer t("Preprocessor::getcode", mSettings.showtime, &s_timerResults);
std::string codeWithoutCfg = preprocessor.getcode(tokens1, mCurrentConfig, files, true);
t.Stop();
t.stop();
if (codeWithoutCfg.compare(0,5,"#file") == 0)
codeWithoutCfg.insert(0U, "//");
@ -474,16 +478,16 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
Tokenizer mTokenizer(&mSettings, this);
if (mSettings.showtime != SHOWTIME_MODES::SHOWTIME_NONE)
mTokenizer.setTimerResults(&S_timerResults);
mTokenizer.setTimerResults(&s_timerResults);
try {
bool result;
// Create tokens, skip rest of iteration if failed
Timer timer("Tokenizer::createTokens", mSettings.showtime, &S_timerResults);
Timer timer("Tokenizer::createTokens", mSettings.showtime, &s_timerResults);
const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, mCurrentConfig, files, true);
mTokenizer.createTokens(&tokensP);
timer.Stop();
timer.stop();
hasValidConfig = true;
// If only errors are printed, print filename after the check
@ -504,9 +508,9 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
checkRawTokens(mTokenizer);
// Simplify tokens into normal form, skip rest of iteration if failed
Timer timer2("Tokenizer::simplifyTokens1", mSettings.showtime, &S_timerResults);
Timer timer2("Tokenizer::simplifyTokens1", mSettings.showtime, &s_timerResults);
result = mTokenizer.simplifyTokens1(mCurrentConfig);
timer2.Stop();
timer2.stop();
if (!result)
continue;
@ -543,9 +547,9 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// simplify more if required, skip rest of iteration if failed
if (mSimplify && hasRule("simple")) {
// if further simplification fails then skip rest of iteration
Timer timer3("Tokenizer::simplifyTokenList2", mSettings.showtime, &S_timerResults);
Timer timer3("Tokenizer::simplifyTokenList2", mSettings.showtime, &s_timerResults);
result = mTokenizer.simplifyTokenList2();
timer3.Stop();
timer3.stop();
if (!result)
continue;
@ -614,6 +618,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
const std::string &failedToGetAddonInfo = addonInfo.getAddonInfo(addon, mSettings.exename);
if (!failedToGetAddonInfo.empty()) {
reportOut(failedToGetAddonInfo);
mExitCode = 1;
continue;
}
const std::string results = executeAddon(addonInfo, dumpFile);
@ -723,7 +728,7 @@ void CppCheck::checkNormalTokens(const Tokenizer &tokenizer)
if (Tokenizer::isMaxTime())
return;
Timer timerRunChecks(check->name() + "::runChecks", mSettings.showtime, &S_timerResults);
Timer timerRunChecks(check->name() + "::runChecks", mSettings.showtime, &s_timerResults);
check->runChecks(&tokenizer, &mSettings, this);
}

View File

@ -36,7 +36,7 @@
* See https://cwe.mitre.org/ for further reference.
* */
struct CWE {
explicit CWE(unsigned short ID) : id(ID) {}
explicit CWE(unsigned short cweId) : id(cweId) {}
unsigned short id;
};

View File

@ -142,7 +142,7 @@ static bool simplifyPathWithVariables(std::string &s, std::map<std::string, std:
void ImportProject::FileSettings::setIncludePaths(const std::string &basepath, const std::list<std::string> &in, std::map<std::string, std::string, cppcheck::stricmp> &variables)
{
std::list<std::string> I;
std::list<std::string> listInc;
// only parse each includePath once - so remove duplicates
std::list<std::string> uniqueIncludePaths = in;
uniqueIncludePaths.sort();
@ -157,7 +157,7 @@ void ImportProject::FileSettings::setIncludePaths(const std::string &basepath, c
if (s[0] == '/' || (s.size() > 1U && s.compare(1,2,":/") == 0)) {
if (!endsWith(s,'/'))
s += '/';
I.push_back(s);
listInc.push_back(s);
continue;
}
@ -172,9 +172,9 @@ void ImportProject::FileSettings::setIncludePaths(const std::string &basepath, c
}
if (s.empty())
continue;
I.push_back(s + '/');
listInc.push_back(s + '/');
}
includePaths.swap(I);
includePaths.swap(listInc);
}
ImportProject::Type ImportProject::import(const std::string &filename, Settings *settings)

View File

@ -576,17 +576,17 @@ Library::Error Library::load(const tinyxml2::XMLDocument &doc)
return Error(MISSING_ATTRIBUTE, "type");
platform.insert(type_attribute);
} else if (typenodename == "signed")
type._signed = true;
type.mSigned = true;
else if (typenodename == "unsigned")
type._unsigned = true;
type.mUnsigned = true;
else if (typenodename == "long")
type._long = true;
type.mLong = true;
else if (typenodename == "pointer")
type._pointer= true;
type.mPointer= true;
else if (typenodename == "ptr_ptr")
type._ptr_ptr = true;
type.mPtrPtr = true;
else if (typenodename == "const_ptr")
type._const_ptr = true;
type.mConstPtr = true;
else
unknown_elements.insert(typenodename);
}

View File

@ -423,32 +423,32 @@ public:
struct PlatformType {
PlatformType()
: _signed(false)
, _unsigned(false)
, _long(false)
, _pointer(false)
, _ptr_ptr(false)
, _const_ptr(false) {
: mSigned(false)
, mUnsigned(false)
, mLong(false)
, mPointer(false)
, mPtrPtr(false)
, mConstPtr(false) {
}
bool operator == (const PlatformType & type) const {
return (_signed == type._signed &&
_unsigned == type._unsigned &&
_long == type._long &&
_pointer == type._pointer &&
_ptr_ptr == type._ptr_ptr &&
_const_ptr == type._const_ptr &&
return (mSigned == type.mSigned &&
mUnsigned == type.mUnsigned &&
mLong == type.mLong &&
mPointer == type.mPointer &&
mPtrPtr == type.mPtrPtr &&
mConstPtr == type.mConstPtr &&
mType == type.mType);
}
bool operator != (const PlatformType & type) const {
return !(*this == type);
}
std::string mType;
bool _signed;
bool _unsigned;
bool _long;
bool _pointer;
bool _ptr_ptr;
bool _const_ptr;
bool mSigned;
bool mUnsigned;
bool mLong;
bool mPointer;
bool mPtrPtr;
bool mConstPtr;
};
struct Platform {

View File

@ -588,7 +588,7 @@ static double myStod(const std::string& str, std::string::const_iterator from, s
// Assuming a limited support of built-in hexadecimal floats (see C99, C++17) that is a fall-back implementation.
// Performance has been optimized WRT to heap activity, however the calculation part is not optimized.
static double FloatHexToDoubleNumber(const std::string& str)
static double floatHexToDoubleNumber(const std::string& str)
{
const std::size_t p = str.find_first_of("pP",3);
const double factor1 = myStod(str, str.begin() + 2, str.begin()+p, 16);
@ -613,7 +613,7 @@ double MathLib::toDoubleNumber(const std::string &str)
return std::strtod(str.c_str(), nullptr);
#endif
if (isFloatHex(str))
return FloatHexToDoubleNumber(str);
return floatHexToDoubleNumber(str);
// otherwise, convert to double
std::istringstream istr(str);
istr.imbue(std::locale::classic());
@ -740,7 +740,7 @@ bool MathLib::isPositive(const std::string &str)
return !MathLib::isNegative(str);
}
static bool _isValidIntegerSuffix(std::string::const_iterator it, std::string::const_iterator end, bool supportMicrosoftExtensions=true)
static bool isValidIntegerSuffixIt(std::string::const_iterator it, std::string::const_iterator end, bool supportMicrosoftExtensions=true)
{
enum { START, SUFFIX_U, SUFFIX_UL, SUFFIX_ULL, SUFFIX_L, SUFFIX_LU, SUFFIX_LL, SUFFIX_LLU, SUFFIX_I, SUFFIX_I6, SUFFIX_I64, SUFFIX_UI, SUFFIX_UI6, SUFFIX_UI64 } state = START;
for (; it != end; ++it) {
@ -826,7 +826,7 @@ static bool _isValidIntegerSuffix(std::string::const_iterator it, std::string::c
bool MathLib::isValidIntegerSuffix(const std::string& str, bool supportMicrosoftExtensions)
{
return _isValidIntegerSuffix(str.begin(), str.end(), supportMicrosoftExtensions);
return isValidIntegerSuffixIt(str.begin(), str.end(), supportMicrosoftExtensions);
}
@ -868,7 +868,7 @@ bool MathLib::isOct(const std::string& str)
if (isOctalDigit(static_cast<unsigned char>(*it)))
state = Status::DIGITS;
else
return _isValidIntegerSuffix(it,str.end());
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
@ -909,7 +909,7 @@ bool MathLib::isIntHex(const std::string& str)
if (isxdigit(static_cast<unsigned char>(*it)))
; // state = DIGIT;
else
return _isValidIntegerSuffix(it,str.end());
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
@ -1040,7 +1040,7 @@ bool MathLib::isBin(const std::string& str)
if (*it == '0' || *it == '1')
; // state = DIGIT;
else
return _isValidIntegerSuffix(it,str.end());
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
@ -1069,7 +1069,7 @@ bool MathLib::isDec(const std::string & str)
if (isdigit(static_cast<unsigned char>(*it)))
state = DIGIT;
else
return _isValidIntegerSuffix(it,str.end());
return isValidIntegerSuffixIt(it,str.end());
break;
}
}

View File

@ -5904,18 +5904,18 @@ bool ValueType::fromLibraryType(const std::string &typestr, const Settings *sett
else if (platformType->mType == "wchar_t")
type = ValueType::Type::WCHAR_T;
else if (platformType->mType == "int")
type = platformType->_long ? ValueType::Type::LONG : ValueType::Type::INT;
type = platformType->mLong ? ValueType::Type::LONG : ValueType::Type::INT;
else if (platformType->mType == "long")
type = platformType->_long ? ValueType::Type::LONGLONG : ValueType::Type::LONG;
if (platformType->_signed)
type = platformType->mLong ? ValueType::Type::LONGLONG : ValueType::Type::LONG;
if (platformType->mSigned)
sign = ValueType::SIGNED;
else if (platformType->_unsigned)
else if (platformType->mUnsigned)
sign = ValueType::UNSIGNED;
if (platformType->_pointer)
if (platformType->mPointer)
pointer = 1;
if (platformType->_ptr_ptr)
if (platformType->mPtrPtr)
pointer = 2;
if (platformType->_const_ptr)
if (platformType->mConstPtr)
constness = 1;
return true;
} else if (!podtype && (typestr == "size_t" || typestr == "std::size_t")) {

View File

@ -39,7 +39,7 @@ namespace {
}
}
void TimerResults::ShowResults(SHOWTIME_MODES mode) const
void TimerResults::showResults(SHOWTIME_MODES mode) const
{
if (mode == SHOWTIME_MODES::SHOWTIME_NONE)
return;
@ -65,7 +65,7 @@ void TimerResults::ShowResults(SHOWTIME_MODES mode) const
std::cout << "Overall time: " << secOverall << "s" << std::endl;
}
void TimerResults::AddResults(const std::string& str, std::clock_t clocks)
void TimerResults::addResults(const std::string& str, std::clock_t clocks)
{
mResults[str].mClocks += clocks;
mResults[str].mNumberOfResults++;
@ -84,10 +84,10 @@ Timer::Timer(const std::string& str, SHOWTIME_MODES showtimeMode, TimerResultsIn
Timer::~Timer()
{
Stop();
stop();
}
void Timer::Stop()
void Timer::stop()
{
if ((mShowTimeMode != SHOWTIME_MODES::SHOWTIME_NONE) && !mStopped) {
const std::clock_t end = std::clock();
@ -98,7 +98,7 @@ void Timer::Stop()
std::cout << mStr << ": " << sec << "s" << std::endl;
} else {
if (mTimerResults)
mTimerResults->AddResults(mStr, diff);
mTimerResults->addResults(mStr, diff);
}
}

View File

@ -37,7 +37,7 @@ class CPPCHECKLIB TimerResultsIntf {
public:
virtual ~TimerResultsIntf() { }
virtual void AddResults(const std::string& str, std::clock_t clocks) = 0;
virtual void addResults(const std::string& str, std::clock_t clocks) = 0;
};
struct TimerResultsData {
@ -60,8 +60,8 @@ public:
TimerResults() {
}
void ShowResults(SHOWTIME_MODES mode) const;
void AddResults(const std::string& str, std::clock_t clocks) OVERRIDE;
void showResults(SHOWTIME_MODES mode) const;
void addResults(const std::string& str, std::clock_t clocks) OVERRIDE;
private:
std::map<std::string, struct TimerResultsData> mResults;
@ -71,7 +71,7 @@ class CPPCHECKLIB Timer {
public:
Timer(const std::string& str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults = nullptr);
~Timer();
void Stop();
void stop();
private:
Timer(const Timer& other); // disallow copying

View File

@ -5701,10 +5701,10 @@ Token *Tokenizer::simplifyAddBracesPair(Token *tok, bool commandWithCondition)
Token * tokOpenBrace=tokAfterCondition->previous();
tokEnd->insertToken("}");
Token * TokCloseBrace=tokEnd->next();
Token * tokCloseBrace=tokEnd->next();
Token::createMutualLinks(tokOpenBrace,TokCloseBrace);
tokBracesEnd=TokCloseBrace;
Token::createMutualLinks(tokOpenBrace,tokCloseBrace);
tokBracesEnd=tokCloseBrace;
}
return tokBracesEnd;
@ -8442,7 +8442,7 @@ void Tokenizer::simplifyStd()
//---------------------------------------------------------------------------
bool Tokenizer::IsScopeNoReturn(const Token *endScopeToken, bool *unknown) const
bool Tokenizer::isScopeNoReturn(const Token *endScopeToken, bool *unknown) const
{
std::string unknownFunc;
const bool ret = mSettings->library.isScopeNoReturn(endScopeToken,&unknownFunc);

View File

@ -107,7 +107,7 @@ public:
* \param unknown set to true if it's unknown if the scope is noreturn
* \return true if scope ends with a function call that might be 'noreturn'
*/
bool IsScopeNoReturn(const Token *endScopeToken, bool *unknown = nullptr) const;
bool isScopeNoReturn(const Token *endScopeToken, bool *unknown = nullptr) const;
bool createTokens(std::istream &code, const std::string& FileName);
void createTokens(const simplecpp::TokenList *tokenList);

View File

@ -1565,16 +1565,16 @@ void TokenList::simplifyPlatformTypes()
tok->deleteThis();
}
Token *typeToken;
if (platformtype->_const_ptr) {
if (platformtype->mConstPtr) {
tok->str("const");
tok->insertToken("*");
tok->insertToken(platformtype->mType);
typeToken = tok;
} else if (platformtype->_pointer) {
} else if (platformtype->mPointer) {
tok->str(platformtype->mType);
typeToken = tok;
tok->insertToken("*");
} else if (platformtype->_ptr_ptr) {
} else if (platformtype->mPtrPtr) {
tok->str(platformtype->mType);
typeToken = tok;
tok->insertToken("*");
@ -1584,11 +1584,11 @@ void TokenList::simplifyPlatformTypes()
tok->str(platformtype->mType);
typeToken = tok;
}
if (platformtype->_signed)
if (platformtype->mSigned)
typeToken->isSigned(true);
if (platformtype->_unsigned)
if (platformtype->mUnsigned)
typeToken->isUnsigned(true);
if (platformtype->_long)
if (platformtype->mLong)
typeToken->isLong(true);
}
}

View File

@ -1,8 +1,9 @@
{
"script": "addons/naming.py",
"args": [
"--private-member-variable=m[A-Z].*"
"--var=[a-z].*",
"--function=[a-z].*"
"--private-member-variable=m[A-Z].*",
"--var=[_a-z].*",
"--const=[_a-zA-Z].*",
"--function=[a-zA-Z].*"
]
}