Format with uncrustify (#3388)

This commit is contained in:
Paul Fultz II 2021-08-07 13:51:18 -05:00 committed by GitHub
parent f361106770
commit 7f358b2bed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
287 changed files with 27831 additions and 24185 deletions

3128
.uncrustify.cfg Normal file

File diff suppressed because it is too large Load Diff

View File

@ -102,8 +102,7 @@ CmdLineParser::CmdLineParser(Settings *settings)
, mShowVersion(false) , mShowVersion(false)
, mShowErrorMessages(false) , mShowErrorMessages(false)
, mExitAfterPrint(false) , mExitAfterPrint(false)
{ {}
}
void CmdLineParser::printMessage(const std::string &message) void CmdLineParser::printMessage(const std::string &message)
{ {
@ -968,306 +967,306 @@ bool CmdLineParser::parseFromArgs(int argc, const char* const argv[])
void CmdLineParser::printHelp() void CmdLineParser::printHelp()
{ {
std::cout << "Cppcheck - A tool for static C/C++ code analysis\n" std::cout << "Cppcheck - A tool for static C/C++ code analysis\n"
"\n" "\n"
"Syntax:\n" "Syntax:\n"
" cppcheck [OPTIONS] [files or paths]\n" " cppcheck [OPTIONS] [files or paths]\n"
"\n" "\n"
"If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n" "If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n"
"*.tpp, and *.txx files are checked recursively from the given directory.\n\n" "*.tpp, and *.txx files are checked recursively from the given directory.\n\n"
"Options:\n" "Options:\n"
" --addon=<addon>\n" " --addon=<addon>\n"
" Execute addon. i.e. --addon=cert. If options must be\n" " Execute addon. i.e. --addon=cert. If options must be\n"
" provided a json configuration is needed.\n" " provided a json configuration is needed.\n"
" --addon-python=<python interpreter>\n" " --addon-python=<python interpreter>\n"
" You can specify the python interpreter either in the\n" " You can specify the python interpreter either in the\n"
" addon json files or through this command line option.\n" " addon json files or through this command line option.\n"
" If not present, Cppcheck will try \"python3\" first and\n" " If not present, Cppcheck will try \"python3\" first and\n"
" then \"python\".\n" " then \"python\".\n"
" --bug-hunting\n" " --bug-hunting\n"
" Enable noisy and soundy analysis. The normal Cppcheck\n" " Enable noisy and soundy analysis. The normal Cppcheck\n"
" analysis is turned off.\n" " analysis is turned off.\n"
" --cppcheck-build-dir=<dir>\n" " --cppcheck-build-dir=<dir>\n"
" Cppcheck work folder. Advantages:\n" " Cppcheck work folder. Advantages:\n"
" * whole program analysis\n" " * whole program analysis\n"
" * faster analysis; Cppcheck will reuse the results if\n" " * faster analysis; Cppcheck will reuse the results if\n"
" the hash for a file is unchanged.\n" " the hash for a file is unchanged.\n"
" * some useful debug information, i.e. commands used to\n" " * some useful debug information, i.e. commands used to\n"
" execute clang/clang-tidy/addons.\n" " execute clang/clang-tidy/addons.\n"
" --check-config Check cppcheck configuration. The normal code\n" " --check-config Check cppcheck configuration. The normal code\n"
" analysis is disabled by this flag.\n" " analysis is disabled by this flag.\n"
" --check-library Show information messages when library files have\n" " --check-library Show information messages when library files have\n"
" incomplete info.\n" " incomplete info.\n"
" --clang=<path> Experimental: Use Clang parser instead of the builtin Cppcheck\n" " --clang=<path> Experimental: Use Clang parser instead of the builtin Cppcheck\n"
" parser. Takes the executable as optional parameter and\n" " parser. Takes the executable as optional parameter and\n"
" defaults to `clang`. Cppcheck will run the given Clang\n" " defaults to `clang`. Cppcheck will run the given Clang\n"
" executable, import the Clang AST and convert it into\n" " executable, import the Clang AST and convert it into\n"
" Cppcheck data. After that the normal Cppcheck analysis is\n" " Cppcheck data. After that the normal Cppcheck analysis is\n"
" used. You must have the executable in PATH if no path is\n" " used. You must have the executable in PATH if no path is\n"
" given.\n" " given.\n"
" --config-exclude=<dir>\n" " --config-exclude=<dir>\n"
" Path (prefix) to be excluded from configuration\n" " Path (prefix) to be excluded from configuration\n"
" checking. Preprocessor configurations defined in\n" " checking. Preprocessor configurations defined in\n"
" headers (but not sources) matching the prefix will not\n" " headers (but not sources) matching the prefix will not\n"
" be considered for evaluation.\n" " be considered for evaluation.\n"
" --config-excludes-file=<file>\n" " --config-excludes-file=<file>\n"
" A file that contains a list of config-excludes\n" " A file that contains a list of config-excludes\n"
" --dump Dump xml data for each translation unit. The dump\n" " --dump Dump xml data for each translation unit. The dump\n"
" files have the extension .dump and contain ast,\n" " files have the extension .dump and contain ast,\n"
" tokenlist, symboldatabase, valueflow.\n" " tokenlist, symboldatabase, valueflow.\n"
" -D<ID> Define preprocessor symbol. Unless --max-configs or\n" " -D<ID> Define preprocessor symbol. Unless --max-configs or\n"
" --force is used, Cppcheck will only check the given\n" " --force is used, Cppcheck will only check the given\n"
" configuration when -D is used.\n" " configuration when -D is used.\n"
" Example: '-DDEBUG=1 -D__cplusplus'.\n" " Example: '-DDEBUG=1 -D__cplusplus'.\n"
" -E Print preprocessor output on stdout and don't do any\n" " -E Print preprocessor output on stdout and don't do any\n"
" further processing.\n" " further processing.\n"
" --enable=<id> Enable additional checks. The available ids are:\n" " --enable=<id> Enable additional checks. The available ids are:\n"
" * all\n" " * all\n"
" Enable all checks. It is recommended to only\n" " Enable all checks. It is recommended to only\n"
" use --enable=all when the whole program is\n" " use --enable=all when the whole program is\n"
" scanned, because this enables unusedFunction.\n" " scanned, because this enables unusedFunction.\n"
" * warning\n" " * warning\n"
" Enable warning messages\n" " Enable warning messages\n"
" * style\n" " * style\n"
" Enable all coding style checks. All messages\n" " Enable all coding style checks. All messages\n"
" with the severities 'style', 'performance' and\n" " with the severities 'style', 'performance' and\n"
" 'portability' are enabled.\n" " 'portability' are enabled.\n"
" * performance\n" " * performance\n"
" Enable performance messages\n" " Enable performance messages\n"
" * portability\n" " * portability\n"
" Enable portability messages\n" " Enable portability messages\n"
" * information\n" " * information\n"
" Enable information messages\n" " Enable information messages\n"
" * unusedFunction\n" " * unusedFunction\n"
" Check for unused functions. It is recommend\n" " Check for unused functions. It is recommend\n"
" to only enable this when the whole program is\n" " to only enable this when the whole program is\n"
" scanned.\n" " scanned.\n"
" * missingInclude\n" " * missingInclude\n"
" Warn if there are missing includes. For\n" " Warn if there are missing includes. For\n"
" detailed information, use '--check-config'.\n" " detailed information, use '--check-config'.\n"
" Several ids can be given if you separate them with\n" " Several ids can be given if you separate them with\n"
" commas. See also --std\n" " commas. See also --std\n"
" --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n" " --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n"
" the default '0'. '" << EXIT_FAILURE << "' is returned\n" " the default '0'. '" << EXIT_FAILURE << "' is returned\n"
" if arguments are not valid or if no input files are\n" " if arguments are not valid or if no input files are\n"
" provided. Note that your operating system can modify\n" " provided. Note that your operating system can modify\n"
" this value, e.g. '256' can become '0'.\n" " this value, e.g. '256' can become '0'.\n"
" --errorlist Print a list of all the error messages in XML format.\n" " --errorlist Print a list of all the error messages in XML format.\n"
" --exitcode-suppressions=<file>\n" " --exitcode-suppressions=<file>\n"
" Used when certain messages should be displayed but\n" " Used when certain messages should be displayed but\n"
" should not cause a non-zero exitcode.\n" " should not cause a non-zero exitcode.\n"
" --file-filter=<str> Analyze only those files matching the given filter str\n" " --file-filter=<str> Analyze only those files matching the given filter str\n"
" Example: --file-filter=*bar.cpp analyzes only files\n" " Example: --file-filter=*bar.cpp analyzes only files\n"
" that end with bar.cpp.\n" " that end with bar.cpp.\n"
" --file-list=<file> Specify the files to check in a text file. Add one\n" " --file-list=<file> Specify the files to check in a text file. Add one\n"
" filename per line. When file is '-,' the file list will\n" " filename per line. When file is '-,' the file list will\n"
" be read from standard input.\n" " be read from standard input.\n"
" -f, --force Force checking of all configurations in files. If used\n" " -f, --force Force checking of all configurations in files. If used\n"
" together with '--max-configs=', the last option is the\n" " together with '--max-configs=', the last option is the\n"
" one that is effective.\n" " one that is effective.\n"
" -h, --help Print this help.\n" " -h, --help Print this help.\n"
" -I <dir> Give path to search for include files. Give several -I\n" " -I <dir> Give path to search for include files. Give several -I\n"
" parameters to give several paths. First given path is\n" " parameters to give several paths. First given path is\n"
" searched for contained header files first. If paths are\n" " searched for contained header files first. If paths are\n"
" relative to source files, this is not needed.\n" " relative to source files, this is not needed.\n"
" --includes-file=<file>\n" " --includes-file=<file>\n"
" Specify directory paths to search for included header\n" " Specify directory paths to search for included header\n"
" files in a text file. Add one include path per line.\n" " files in a text file. Add one include path per line.\n"
" First given path is searched for contained header\n" " First given path is searched for contained header\n"
" files first. If paths are relative to source files,\n" " files first. If paths are relative to source files,\n"
" this is not needed.\n" " this is not needed.\n"
" --include=<file>\n" " --include=<file>\n"
" Force inclusion of a file before the checked file.\n" " Force inclusion of a file before the checked file.\n"
" -i <dir or file> Give a source file or source file directory to exclude\n" " -i <dir or file> Give a source file or source file directory to exclude\n"
" from the check. This applies only to source files so\n" " from the check. This applies only to source files so\n"
" header files included by source files are not matched.\n" " header files included by source files are not matched.\n"
" Directory name is matched to all parts of the path.\n" " Directory name is matched to all parts of the path.\n"
" --inconclusive Allow that Cppcheck reports even though the analysis is\n" " --inconclusive Allow that Cppcheck reports even though the analysis is\n"
" inconclusive.\n" " inconclusive.\n"
" There are false positives with this option. Each result\n" " There are false positives with this option. Each result\n"
" must be carefully investigated before you know if it is\n" " must be carefully investigated before you know if it is\n"
" good or bad.\n" " good or bad.\n"
" --inline-suppr Enable inline suppressions. Use them by placing one or\n" " --inline-suppr Enable inline suppressions. Use them by placing one or\n"
" more comments, like: '// cppcheck-suppress warningId'\n" " more comments, like: '// cppcheck-suppress warningId'\n"
" on the lines before the warning to suppress.\n" " on the lines before the warning to suppress.\n"
" -j <jobs> Start <jobs> threads to do the checking simultaneously.\n" " -j <jobs> Start <jobs> threads to do the checking simultaneously.\n"
#ifdef THREADING_MODEL_FORK #ifdef THREADING_MODEL_FORK
" -l <load> Specifies that no new threads should be started if\n" " -l <load> Specifies that no new threads should be started if\n"
" there are other threads running and the load average is\n" " there are other threads running and the load average is\n"
" at least <load>.\n" " at least <load>.\n"
#endif #endif
" --language=<language>, -x <language>\n" " --language=<language>, -x <language>\n"
" Forces cppcheck to check all files as the given\n" " Forces cppcheck to check all files as the given\n"
" language. Valid values are: c, c++\n" " language. Valid values are: c, c++\n"
" --library=<cfg> Load file <cfg> that contains information about types\n" " --library=<cfg> Load file <cfg> that contains information about types\n"
" and functions. With such information Cppcheck\n" " and functions. With such information Cppcheck\n"
" understands your code better and therefore you\n" " understands your code better and therefore you\n"
" get better results. The std.cfg file that is\n" " get better results. The std.cfg file that is\n"
" distributed with Cppcheck is loaded automatically.\n" " distributed with Cppcheck is loaded automatically.\n"
" For more information about library files, read the\n" " For more information about library files, read the\n"
" manual.\n" " manual.\n"
" --max-ctu-depth=N Max depth in whole program analysis. The default value\n" " --max-ctu-depth=N Max depth in whole program analysis. The default value\n"
" is 2. A larger value will mean more errors can be found\n" " is 2. A larger value will mean more errors can be found\n"
" but also means the analysis will be slower.\n" " but also means the analysis will be slower.\n"
" --output-file=<file> Write results to file, rather than standard error.\n" " --output-file=<file> Write results to file, rather than standard error.\n"
" --project=<file> Run Cppcheck on project. The <file> can be a Visual\n" " --project=<file> Run Cppcheck on project. The <file> can be a Visual\n"
" Studio Solution (*.sln), Visual Studio Project\n" " Studio Solution (*.sln), Visual Studio Project\n"
" (*.vcxproj), compile database (compile_commands.json),\n" " (*.vcxproj), compile database (compile_commands.json),\n"
" or Borland C++ Builder 6 (*.bpr). The files to analyse,\n" " or Borland C++ Builder 6 (*.bpr). The files to analyse,\n"
" include paths, defines, platform and undefines in\n" " include paths, defines, platform and undefines in\n"
" the specified file will be used.\n" " the specified file will be used.\n"
" --project-configuration=<config>\n" " --project-configuration=<config>\n"
" If used together with a Visual Studio Solution (*.sln)\n" " If used together with a Visual Studio Solution (*.sln)\n"
" or Visual Studio Project (*.vcxproj) you can limit\n" " or Visual Studio Project (*.vcxproj) you can limit\n"
" the configuration cppcheck should check.\n" " the configuration cppcheck should check.\n"
" For example: '--project-configuration=Release|Win32'\n" " For example: '--project-configuration=Release|Win32'\n"
" --max-configs=<limit>\n" " --max-configs=<limit>\n"
" Maximum number of configurations to check in a file\n" " Maximum number of configurations to check in a file\n"
" before skipping it. Default is '12'. If used together\n" " before skipping it. Default is '12'. If used together\n"
" with '--force', the last option is the one that is\n" " with '--force', the last option is the one that is\n"
" effective.\n" " effective.\n"
" --platform=<type>, --platform=<file>\n" " --platform=<type>, --platform=<file>\n"
" Specifies platform specific types and sizes. The\n" " Specifies platform specific types and sizes. The\n"
" available builtin platforms are:\n" " available builtin platforms are:\n"
" * unix32\n" " * unix32\n"
" 32 bit unix variant\n" " 32 bit unix variant\n"
" * unix64\n" " * unix64\n"
" 64 bit unix variant\n" " 64 bit unix variant\n"
" * win32A\n" " * win32A\n"
" 32 bit Windows ASCII character encoding\n" " 32 bit Windows ASCII character encoding\n"
" * win32W\n" " * win32W\n"
" 32 bit Windows UNICODE character encoding\n" " 32 bit Windows UNICODE character encoding\n"
" * win64\n" " * win64\n"
" 64 bit Windows\n" " 64 bit Windows\n"
" * avr8\n" " * avr8\n"
" 8 bit AVR microcontrollers\n" " 8 bit AVR microcontrollers\n"
" * elbrus-e1cp\n" " * elbrus-e1cp\n"
" Elbrus e1c+ architecture\n" " Elbrus e1c+ architecture\n"
" * pic8\n" " * pic8\n"
" 8 bit PIC microcontrollers\n" " 8 bit PIC microcontrollers\n"
" Baseline and mid-range architectures\n" " Baseline and mid-range architectures\n"
" * pic8-enhanced\n" " * pic8-enhanced\n"
" 8 bit PIC microcontrollers\n" " 8 bit PIC microcontrollers\n"
" Enhanced mid-range and high end (PIC18) architectures\n" " Enhanced mid-range and high end (PIC18) architectures\n"
" * pic16\n" " * pic16\n"
" 16 bit PIC microcontrollers\n" " 16 bit PIC microcontrollers\n"
" * mips32\n" " * mips32\n"
" 32 bit MIPS microcontrollers\n" " 32 bit MIPS microcontrollers\n"
" * native\n" " * native\n"
" Type sizes of host system are assumed, but no\n" " Type sizes of host system are assumed, but no\n"
" further assumptions.\n" " further assumptions.\n"
" * unspecified\n" " * unspecified\n"
" Unknown type sizes\n" " Unknown type sizes\n"
" --plist-output=<path>\n" " --plist-output=<path>\n"
" Generate Clang-plist output files in folder.\n" " Generate Clang-plist output files in folder.\n"
" -q, --quiet Do not show progress reports.\n" " -q, --quiet Do not show progress reports.\n"
" -rp=<paths>, --relative-paths=<paths>\n" " -rp=<paths>, --relative-paths=<paths>\n"
" Use relative paths in output. When given, <paths> are\n" " Use relative paths in output. When given, <paths> are\n"
" used as base. You can separate multiple paths by ';'.\n" " used as base. You can separate multiple paths by ';'.\n"
" Otherwise path where source files are searched is used.\n" " Otherwise path where source files are searched is used.\n"
" We use string comparison to create relative paths, so\n" " We use string comparison to create relative paths, so\n"
" using e.g. ~ for home folder does not work. It is\n" " using e.g. ~ for home folder does not work. It is\n"
" currently only possible to apply the base paths to\n" " currently only possible to apply the base paths to\n"
" files that are on a lower level in the directory tree.\n" " files that are on a lower level in the directory tree.\n"
" --report-progress Report progress messages while checking a file.\n" " --report-progress Report progress messages while checking a file.\n"
#ifdef HAVE_RULES #ifdef HAVE_RULES
" --rule=<rule> Match regular expression.\n" " --rule=<rule> Match regular expression.\n"
" --rule-file=<file> Use given rule file. For more information, see:\n" " --rule-file=<file> Use given rule file. For more information, see:\n"
" http://sourceforge.net/projects/cppcheck/files/Articles/\n" " http://sourceforge.net/projects/cppcheck/files/Articles/\n"
#endif #endif
" --std=<id> Set standard.\n" " --std=<id> Set standard.\n"
" The available options are:\n" " The available options are:\n"
" * c89\n" " * c89\n"
" C code is C89 compatible\n" " C code is C89 compatible\n"
" * c99\n" " * c99\n"
" C code is C99 compatible\n" " C code is C99 compatible\n"
" * c11\n" " * c11\n"
" C code is C11 compatible (default)\n" " C code is C11 compatible (default)\n"
" * c++03\n" " * c++03\n"
" C++ code is C++03 compatible\n" " C++ code is C++03 compatible\n"
" * c++11\n" " * c++11\n"
" C++ code is C++11 compatible\n" " C++ code is C++11 compatible\n"
" * c++14\n" " * c++14\n"
" C++ code is C++14 compatible\n" " C++ code is C++14 compatible\n"
" * c++17\n" " * c++17\n"
" C++ code is C++17 compatible\n" " C++ code is C++17 compatible\n"
" * c++20\n" " * c++20\n"
" C++ code is C++20 compatible (default)\n" " C++ code is C++20 compatible (default)\n"
" --suppress=<spec> Suppress warnings that match <spec>. The format of\n" " --suppress=<spec> Suppress warnings that match <spec>. The format of\n"
" <spec> is:\n" " <spec> is:\n"
" [error id]:[filename]:[line]\n" " [error id]:[filename]:[line]\n"
" The [filename] and [line] are optional. If [error id]\n" " The [filename] and [line] are optional. If [error id]\n"
" is a wildcard '*', all error ids match.\n" " is a wildcard '*', all error ids match.\n"
" --suppressions-list=<file>\n" " --suppressions-list=<file>\n"
" Suppress warnings listed in the file. Each suppression\n" " Suppress warnings listed in the file. Each suppression\n"
" is in the same format as <spec> above.\n" " is in the same format as <spec> above.\n"
" --suppress-xml=<file>\n" " --suppress-xml=<file>\n"
" Suppress warnings listed in a xml file. XML file should\n" " Suppress warnings listed in a xml file. XML file should\n"
" follow the manual.pdf format specified in section.\n" " follow the manual.pdf format specified in section.\n"
" `6.4 XML suppressions` .\n" " `6.4 XML suppressions` .\n"
" --template='<text>' Format the error messages. Available fields:\n" " --template='<text>' Format the error messages. Available fields:\n"
" {file} file name\n" " {file} file name\n"
" {line} line number\n" " {line} line number\n"
" {column} column number\n" " {column} column number\n"
" {callstack} show a callstack. Example:\n" " {callstack} show a callstack. Example:\n"
" [file.c:1] -> [file.c:100]\n" " [file.c:1] -> [file.c:100]\n"
" {inconclusive:text} if warning is inconclusive, text\n" " {inconclusive:text} if warning is inconclusive, text\n"
" is written\n" " is written\n"
" {severity} severity\n" " {severity} severity\n"
" {message} warning message\n" " {message} warning message\n"
" {id} warning id\n" " {id} warning id\n"
" {cwe} CWE id (Common Weakness Enumeration)\n" " {cwe} CWE id (Common Weakness Enumeration)\n"
" {code} show the real code\n" " {code} show the real code\n"
" \\t insert tab\n" " \\t insert tab\n"
" \\n insert newline\n" " \\n insert newline\n"
" \\r insert carriage return\n" " \\r insert carriage return\n"
" Example formats:\n" " Example formats:\n"
" '{file}:{line},{severity},{id},{message}' or\n" " '{file}:{line},{severity},{id},{message}' or\n"
" '{file}({line}):({severity}) {message}' or\n" " '{file}({line}):({severity}) {message}' or\n"
" '{callstack} {message}'\n" " '{callstack} {message}'\n"
" Pre-defined templates: gcc (default), cppcheck1 (old default), vs, edit.\n" " Pre-defined templates: gcc (default), cppcheck1 (old default), vs, edit.\n"
// Note: template daca2 also exists, but is for internal use (cppcheck scripts). // Note: template daca2 also exists, but is for internal use (cppcheck scripts).
" --template-location='<text>'\n" " --template-location='<text>'\n"
" Format error message location. If this is not provided\n" " Format error message location. If this is not provided\n"
" then no extra location info is shown.\n" " then no extra location info is shown.\n"
" Available fields:\n" " Available fields:\n"
" {file} file name\n" " {file} file name\n"
" {line} line number\n" " {line} line number\n"
" {column} column number\n" " {column} column number\n"
" {info} location info\n" " {info} location info\n"
" {code} show the real code\n" " {code} show the real code\n"
" \\t insert tab\n" " \\t insert tab\n"
" \\n insert newline\n" " \\n insert newline\n"
" \\r insert carriage return\n" " \\r insert carriage return\n"
" Example format (gcc-like):\n" " Example format (gcc-like):\n"
" '{file}:{line}:{column}: note: {info}\\n{code}'\n" " '{file}:{line}:{column}: note: {info}\\n{code}'\n"
" -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n" " -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n"
" hide certain #ifdef <ID> code paths from checking.\n" " hide certain #ifdef <ID> code paths from checking.\n"
" Example: '-UDEBUG'\n" " Example: '-UDEBUG'\n"
" -v, --verbose Output more detailed error information.\n" " -v, --verbose Output more detailed error information.\n"
" --version Print out version number.\n" " --version Print out version number.\n"
" --xml Write results in xml format to error stream (stderr).\n" " --xml Write results in xml format to error stream (stderr).\n"
"\n" "\n"
"Example usage:\n" "Example usage:\n"
" # Recursively check the current folder. Print the progress on the screen and\n" " # Recursively check the current folder. Print the progress on the screen and\n"
" # write errors to a file:\n" " # write errors to a file:\n"
" cppcheck . 2> err.txt\n" " cppcheck . 2> err.txt\n"
"\n" "\n"
" # Recursively check ../myproject/ and don't print progress:\n" " # Recursively check ../myproject/ and don't print progress:\n"
" cppcheck --quiet ../myproject/\n" " cppcheck --quiet ../myproject/\n"
"\n" "\n"
" # Check test.cpp, enable all checks:\n" " # Check test.cpp, enable all checks:\n"
" cppcheck --enable=all --inconclusive --library=posix test.cpp\n" " cppcheck --enable=all --inconclusive --library=posix test.cpp\n"
"\n" "\n"
" # Check f.cpp and search include files from inc1/ and inc2/:\n" " # Check f.cpp and search include files from inc1/ and inc2/:\n"
" cppcheck -I inc1/ -I inc2/ f.cpp\n" " cppcheck -I inc1/ -I inc2/ f.cpp\n"
"\n" "\n"
"For more information:\n" "For more information:\n"
" http://cppcheck.net/manual.pdf\n" " http://cppcheck.net/manual.pdf\n"
"\n" "\n"
"Many thanks to the 3rd party libraries we use:\n" "Many thanks to the 3rd party libraries we use:\n"
" * tinyxml2 -- loading project/library/ctu files.\n" " * tinyxml2 -- loading project/library/ctu files.\n"
" * picojson -- loading compile database.\n" " * picojson -- loading compile database.\n"
" * pcre -- rules.\n" " * pcre -- rules.\n"
" * qt -- used in GUI\n" " * qt -- used in GUI\n"
" * z3 -- theorem prover from Microsoft Research used in bug hunting.\n"; " * z3 -- theorem prover from Microsoft Research used in bug hunting.\n";
} }

View File

@ -81,8 +81,7 @@
CppCheckExecutor::CppCheckExecutor() CppCheckExecutor::CppCheckExecutor()
: mSettings(nullptr), mLatestProgressOutputTime(0), mErrorOutput(nullptr), mBugHuntingReport(nullptr), mShowAllErrors(false) : mSettings(nullptr), mLatestProgressOutputTime(0), mErrorOutput(nullptr), mBugHuntingReport(nullptr), mShowAllErrors(false)
{ {}
}
CppCheckExecutor::~CppCheckExecutor() CppCheckExecutor::~CppCheckExecutor()
{ {
@ -125,7 +124,7 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c
{ {
for (std::list<std::string>::iterator iter = settings.includePaths.begin(); for (std::list<std::string>::iterator iter = settings.includePaths.begin();
iter != settings.includePaths.end(); iter != settings.includePaths.end();
) { ) {
const std::string path(Path::toNativeSeparators(*iter)); const std::string path(Path::toNativeSeparators(*iter));
if (FileLister::isDirectory(path)) if (FileLister::isDirectory(path))
++iter; ++iter;
@ -250,7 +249,7 @@ void CppCheckExecutor::setSettings(const Settings &settings)
* \return size of array * \return size of array
* */ * */
template<typename T, int size> template<typename T, int size>
std::size_t getArrayLength(const T(&)[size]) std::size_t getArrayLength(const T (&)[size])
{ {
return size; return size;
} }
@ -548,7 +547,7 @@ static void CppcheckSignalHandler(int signo, siginfo_t * info, void * context)
(type==0) ? "reading " : "writing ", (type==0) ? "reading " : "writing ",
(unsigned long)info->si_addr, (unsigned long)info->si_addr,
(isAddressOnStack)?" Stackoverflow?":"" (isAddressOnStack)?" Stackoverflow?":""
); );
break; break;
case SIGUSR1: case SIGUSR1:
fputs("cppcheck received signal ", output); fputs("cppcheck received signal ", output);
@ -589,15 +588,15 @@ namespace {
}; };
typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64); 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; fpStackWalk64 pStackWalk64;
typedef DWORD64(WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64); typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
fpSymGetModuleBase64 pSymGetModuleBase64; fpSymGetModuleBase64 pSymGetModuleBase64;
typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64); typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
fpSymGetSymFromAddr64 pSymGetSymFromAddr64; fpSymGetSymFromAddr64 pSymGetSymFromAddr64;
typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64); typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
fpSymGetLineFromAddr64 pSymGetLineFromAddr64; fpSymGetLineFromAddr64 pSymGetLineFromAddr64;
typedef DWORD (WINAPI *fpUnDecorateSymbolName)(const TCHAR*, PTSTR, DWORD, DWORD) ; typedef DWORD (WINAPI *fpUnDecorateSymbolName)(const TCHAR*, PTSTR, DWORD, DWORD);
fpUnDecorateSymbolName pUnDecorateSymbolName; fpUnDecorateSymbolName pUnDecorateSymbolName;
typedef PVOID(WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64); typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
fpSymFunctionTableAccess64 pSymFunctionTableAccess64; fpSymFunctionTableAccess64 pSymFunctionTableAccess64;
typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL); typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
fpSymInitialize pSymInitialize; fpSymInitialize pSymInitialize;
@ -630,9 +629,9 @@ namespace {
hProcess, hProcess,
nullptr, nullptr,
TRUE TRUE
); );
CONTEXT context = *(ex->ContextRecord); CONTEXT context = *(ex->ContextRecord);
STACKFRAME64 stack= {0}; STACKFRAME64 stack= {0};
#ifdef _M_IX86 #ifdef _M_IX86
stack.AddrPC.Offset = context.Eip; stack.AddrPC.Offset = context.Eip;
stack.AddrPC.Mode = AddrModeFlat; stack.AddrPC.Mode = AddrModeFlat;
@ -657,18 +656,18 @@ namespace {
BOOL result = pStackWalk64 BOOL result = pStackWalk64
( (
#ifdef _M_IX86 #ifdef _M_IX86
IMAGE_FILE_MACHINE_I386, IMAGE_FILE_MACHINE_I386,
#else #else
IMAGE_FILE_MACHINE_AMD64, IMAGE_FILE_MACHINE_AMD64,
#endif #endif
hProcess, hProcess,
hThread, hThread,
&stack, &stack,
&context, &context,
nullptr, nullptr,
pSymFunctionTableAccess64, pSymFunctionTableAccess64,
pSymGetModuleBase64, pSymGetModuleBase64,
nullptr nullptr
); );
if (!result) // official end... if (!result) // official end...
break; break;

View File

@ -99,14 +99,14 @@ public:
*/ */
static void setExceptionOutput(FILE* exceptionOutput); static void setExceptionOutput(FILE* exceptionOutput);
/** /**
* @return file name to be used for output from exception handler. Has to be either "stdout" or "stderr". * @return file name to be used for output from exception handler. Has to be either "stdout" or "stderr".
*/ */
static FILE* getExceptionOutput(); static FILE* getExceptionOutput();
/** /**
* Tries to load a library and prints warning/error messages * Tries to load a library and prints warning/error messages
* @return false, if an error occurred (except unknown XML elements) * @return false, if an error occurred (except unknown XML elements)
*/ */
static bool tryLoadLibrary(Library& destination, const char* basepath, const char* filename); static bool tryLoadLibrary(Library& destination, const char* basepath, const char* filename);
/** /**
@ -152,17 +152,17 @@ private:
int check_wrapper(CppCheck& cppcheck, int argc, const char* const argv[]); int check_wrapper(CppCheck& cppcheck, int argc, const char* const argv[]);
/** /**
* Starts the checking. * Starts the checking.
* *
* @param cppcheck cppcheck instance * @param cppcheck cppcheck instance
* @param argc from main() * @param argc from main()
* @param argv from main() * @param argv from main()
* @return EXIT_FAILURE if arguments are invalid or no input files * @return EXIT_FAILURE if arguments are invalid or no input files
* were found. * were found.
* If errors are found and --error-exitcode is used, * If errors are found and --error-exitcode is used,
* given value is returned instead of default 0. * given value is returned instead of default 0.
* If no errors are found, 0 is returned. * If no errors are found, 0 is returned.
*/ */
int check_internal(CppCheck& cppcheck, int argc, const char* const argv[]); int check_internal(CppCheck& cppcheck, int argc, const char* const argv[]);
/** /**

View File

@ -193,7 +193,7 @@ static std::string addFiles2(std::map<std::string, std::size_t> &files,
const std::set<std::string> &extra, const std::set<std::string> &extra,
bool recursive, bool recursive,
const PathMatch& ignored const PathMatch& ignored
) )
{ {
struct stat file_stat; struct stat file_stat;
if (stat(path.c_str(), &file_stat) != -1) { if (stat(path.c_str(), &file_stat) != -1) {

View File

@ -81,9 +81,9 @@ public:
static bool isDirectory(const std::string &path); static bool isDirectory(const std::string &path);
/** /**
* @brief Check if the given path is a file and if it exists? * @brief Check if the given path is a file and if it exists?
* @return true if path points to file and the file exists. * @return true if path points to file and the file exists.
*/ */
static bool fileExists(const std::string &path); static bool fileExists(const std::string &path);
}; };

View File

@ -88,7 +88,7 @@ int main(int argc, char* argv[])
GetModuleFileNameA(nullptr, exename, sizeof(exename)/sizeof(exename[0])-1); GetModuleFileNameA(nullptr, exename, sizeof(exename)/sizeof(exename[0])-1);
argv[0] = exename; argv[0] = exename;
#endif #endif
// *INDENT-OFF*
#ifdef NDEBUG #ifdef NDEBUG
try { try {
#endif #endif
@ -103,12 +103,13 @@ int main(int argc, char* argv[])
} }
return EXIT_FAILURE; return EXIT_FAILURE;
#endif #endif
// *INDENT-ON*
} }
// Warn about deprecated compilers // Warn about deprecated compilers
#ifdef __clang__ #ifdef __clang__
# if ( __clang_major__ < 2 || ( __clang_major__ == 2 && __clang_minor__ < 9)) # if (__clang_major__ < 2 || (__clang_major__ == 2 && __clang_minor__ < 9))
# warning "Using Clang 2.8 or earlier. Support for this version has been removed." # warning "Using Clang 2.8 or earlier. Support for this version has been removed."
# endif # endif
#elif defined(__GNUC__) #elif defined(__GNUC__)

View File

@ -55,7 +55,7 @@ using std::memset;
ThreadExecutor::ThreadExecutor(const std::map<std::string, std::size_t> &files, Settings &settings, ErrorLogger &errorLogger) ThreadExecutor::ThreadExecutor(const std::map<std::string, std::size_t> &files, Settings &settings, ErrorLogger &errorLogger)
: mFiles(files), mSettings(settings), mErrorLogger(errorLogger), mFileCount(0) : mFiles(files), mSettings(settings), mErrorLogger(errorLogger), mFileCount(0)
// Not initialized mFileSync, mErrorSync, mReportSync // Not initialized mFileSync, mErrorSync, mReportSync
{ {
#if defined(THREADING_MODEL_FORK) #if defined(THREADING_MODEL_FORK)
mWpipe = 0; mWpipe = 0;
@ -81,7 +81,7 @@ ThreadExecutor::~ThreadExecutor()
void ThreadExecutor::addFileContent(const std::string &path, const std::string &content) void ThreadExecutor::addFileContent(const std::string &path, const std::string &content)
{ {
mFileContents[ path ] = content; mFileContents[path] = content;
} }
int ThreadExecutor::handleRead(int rpipe, unsigned int &result) int ThreadExecutor::handleRead(int rpipe, unsigned int &result)
@ -139,11 +139,11 @@ int ThreadExecutor::handleRead(int rpipe, unsigned int &result)
unsigned int fileResult = 0; unsigned int fileResult = 0;
iss >> fileResult; iss >> fileResult;
result += fileResult; result += fileResult;
delete [] buf; delete[] buf;
return -1; return -1;
} }
delete [] buf; delete[] buf;
return 1; return 1;
} }
@ -224,7 +224,7 @@ unsigned int ThreadExecutor::check()
resultOfCheck = fileChecker.check(*iFileSettings); resultOfCheck = fileChecker.check(*iFileSettings);
} else if (!mFileContents.empty() && mFileContents.find(iFile->first) != mFileContents.end()) { } else if (!mFileContents.empty() && mFileContents.find(iFile->first) != mFileContents.end()) {
// File content was given as a string // File content was given as a string
resultOfCheck = fileChecker.check(iFile->first, mFileContents[ iFile->first ]); resultOfCheck = fileChecker.check(iFile->first, mFileContents[iFile->first]);
} else { } else {
// Read file from a file // Read file from a file
resultOfCheck = fileChecker.check(iFile->first); resultOfCheck = fileChecker.check(iFile->first);
@ -327,18 +327,18 @@ unsigned int ThreadExecutor::check()
void ThreadExecutor::writeToPipe(PipeSignal type, const std::string &data) void ThreadExecutor::writeToPipe(PipeSignal type, const std::string &data)
{ {
unsigned int len = static_cast<unsigned int>(data.length() + 1); unsigned int len = static_cast<unsigned int>(data.length() + 1);
char *out = new char[ len + 1 + sizeof(len)]; char *out = new char[len + 1 + sizeof(len)];
out[0] = static_cast<char>(type); out[0] = static_cast<char>(type);
std::memcpy(&(out[1]), &len, sizeof(len)); std::memcpy(&(out[1]), &len, sizeof(len));
std::memcpy(&(out[1+sizeof(len)]), data.c_str(), len); std::memcpy(&(out[1+sizeof(len)]), data.c_str(), len);
if (write(mWpipe, out, len + 1 + sizeof(len)) <= 0) { if (write(mWpipe, out, len + 1 + sizeof(len)) <= 0) {
delete [] out; delete[] out;
out = nullptr; out = nullptr;
std::cerr << "#### ThreadExecutor::writeToPipe, Failed to write to pipe" << std::endl; std::cerr << "#### ThreadExecutor::writeToPipe, Failed to write to pipe" << std::endl;
std::exit(EXIT_FAILURE); std::exit(EXIT_FAILURE);
} }
delete [] out; delete[] out;
} }
void ThreadExecutor::reportOut(const std::string &outmsg, Color c) void ThreadExecutor::reportOut(const std::string &outmsg, Color c)
@ -523,7 +523,7 @@ void ThreadExecutor::reportInfo(const ErrorMessage &msg)
report(msg, MessageType::REPORT_INFO); report(msg, MessageType::REPORT_INFO);
} }
void ThreadExecutor::bughuntingReport(const std::string &/*str*/) void ThreadExecutor::bughuntingReport(const std::string & /*str*/)
{ {
// TODO // TODO
} }
@ -562,32 +562,23 @@ void ThreadExecutor::report(const ErrorMessage &msg, MessageType msgType)
#else #else
void ThreadExecutor::addFileContent(const std::string &/*path*/, const std::string &/*content*/) void ThreadExecutor::addFileContent(const std::string & /*path*/, const std::string & /*content*/)
{ {}
}
unsigned int ThreadExecutor::check() unsigned int ThreadExecutor::check()
{ {
return 0; return 0;
} }
void ThreadExecutor::reportOut(const std::string &/*outmsg*/, Color) void ThreadExecutor::reportOut(const std::string & /*outmsg*/, Color)
{ {}
void ThreadExecutor::reportErr(const ErrorMessage & /*msg*/)
{}
} void ThreadExecutor::reportInfo(const ErrorMessage & /*msg*/)
void ThreadExecutor::reportErr(const ErrorMessage &/*msg*/) {}
{
} void ThreadExecutor::bughuntingReport(const std::string & /*str*/)
{}
void ThreadExecutor::reportInfo(const ErrorMessage &/*msg*/)
{
}
void ThreadExecutor::bughuntingReport(const std::string &/*str*/)
{
}
#endif #endif

View File

@ -46,7 +46,7 @@ public:
void bughuntingReport(const std::string&) override {} void bughuntingReport(const std::string&) override {}
void reportOut(const std::string &outmsg) override { } void reportOut(const std::string &outmsg) override {}
void reportErr(const ErrorMessage &msg) override { void reportErr(const ErrorMessage &msg) override {
const std::string s = msg.toString(true); const std::string s = msg.toString(true);

View File

@ -29,9 +29,9 @@ class QWidget;
/// @{ /// @{
/** /**
* @brief About dialog * @brief About dialog
* *
*/ */
class AboutDialog : public QDialog { class AboutDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:

View File

@ -23,5 +23,4 @@ Application::Application(const QString &name, const QString &path,
: mName(name) : mName(name)
, mPath(path) , mPath(path)
, mParameters(params) , mParameters(params)
{ {}
}

View File

@ -22,73 +22,73 @@
#include <QString> #include <QString>
/** /**
* @brief A class containing information of the application to execute. * @brief A class containing information of the application to execute.
* *
* Each application has a name and a path. Name is displayed to the user * Each application has a name and a path. Name is displayed to the user
* and has no other meaning. It isn't used to start the application. * and has no other meaning. It isn't used to start the application.
* Path contains the full path to the application containing the executable name. * Path contains the full path to the application containing the executable name.
* Parameters contains the command line arguments for the executable. * Parameters contains the command line arguments for the executable.
* *
* User can also specify certain predefined strings to parameters. These strings * User can also specify certain predefined strings to parameters. These strings
* will be replaced with appropriate values concerning the error. Strings are: * will be replaced with appropriate values concerning the error. Strings are:
* (file) - Filename containing the error * (file) - Filename containing the error
* (line) - Line number containing the error * (line) - Line number containing the error
* (message) - Error message * (message) - Error message
* (severity) - Error severity * (severity) - Error severity
* *
* Example opening a file with Kate and make Kate scroll to the correct line. * Example opening a file with Kate and make Kate scroll to the correct line.
* Executable: kate * Executable: kate
* Parameters: -l(line) (file) * Parameters: -l(line) (file)
*/ */
class Application { class Application {
public: public:
Application() { } Application() {}
Application(const QString &name, const QString &path, const QString &params); Application(const QString &name, const QString &path, const QString &params);
/** /**
* @brief Get application name. * @brief Get application name.
* @return Application name. * @return Application name.
*/ */
QString getName() const { QString getName() const {
return mName; return mName;
} }
/** /**
* @brief Get application path. * @brief Get application path.
* @return Application path. * @return Application path.
*/ */
QString getPath() const { QString getPath() const {
return mPath; return mPath;
} }
/** /**
* @brief Get application command line parameters. * @brief Get application command line parameters.
* @return Application command line parameters. * @return Application command line parameters.
*/ */
QString getParameters() const { QString getParameters() const {
return mParameters; return mParameters;
} }
/** /**
* @brief Set application name. * @brief Set application name.
* @param name Application name. * @param name Application name.
*/ */
void setName(const QString &name) { void setName(const QString &name) {
mName = name; mName = name;
} }
/** /**
* @brief Set application path. * @brief Set application path.
* @param path Application path. * @param path Application path.
*/ */
void setPath(const QString &path) { void setPath(const QString &path) {
mPath = path; mPath = path;
} }
/** /**
* @brief Set application command line parameters. * @brief Set application command line parameters.
* @param parameters Application command line parameters. * @param parameters Application command line parameters.
*/ */
void setParameters(const QString &parameters) { void setParameters(const QString &parameters) {
mParameters = parameters; mParameters = parameters;
} }
@ -96,18 +96,18 @@ public:
private: private:
/** /**
* @brief Application's name * @brief Application's name
*/ */
QString mName; QString mName;
/** /**
* @brief Application's path * @brief Application's path
*/ */
QString mPath; QString mPath;
/** /**
* @brief Application's parameters * @brief Application's parameters
*/ */
QString mParameters; QString mParameters;
}; };

View File

@ -60,9 +60,9 @@ void ApplicationDialog::browse()
filter += tr("Executable files (*.exe);;All files(*.*)"); filter += tr("Executable files (*.exe);;All files(*.*)");
#endif // Q_OS_WIN #endif // Q_OS_WIN
QString selectedFile = QFileDialog::getOpenFileName(this, QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Select viewer application"), tr("Select viewer application"),
getPath(SETTINGS_LAST_APP_PATH), getPath(SETTINGS_LAST_APP_PATH),
filter); filter);
if (!selectedFile.isEmpty()) { if (!selectedFile.isEmpty()) {
setPath(SETTINGS_LAST_APP_PATH, selectedFile); setPath(SETTINGS_LAST_APP_PATH, selectedFile);

View File

@ -30,21 +30,21 @@ class Application;
/// @{ /// @{
/** /**
* @brief Dialog to edit a startable application. * @brief Dialog to edit a startable application.
* User can open errors with user specified applications. This is a dialog * User can open errors with user specified applications. This is a dialog
* to modify/add an application to open errors with. * to modify/add an application to open errors with.
* *
*/ */
class ApplicationDialog : public QDialog { class ApplicationDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
/** /**
* @brief Constructor. * @brief Constructor.
* @param title Title for the dialog. * @param title Title for the dialog.
* @param app Application definition. * @param app Application definition.
* @param parent Parent widget. * @param parent Parent widget.
*/ */
ApplicationDialog(const QString &title, ApplicationDialog(const QString &title,
Application &app, Application &app,
QWidget *parent = nullptr); QWidget *parent = nullptr);
@ -55,24 +55,24 @@ protected slots:
void ok(); void ok();
/** /**
* @brief Slot to browse for an application * @brief Slot to browse for an application
* *
*/ */
void browse(); void browse();
protected: protected:
/** /**
* @brief UI from the Qt designer * @brief UI from the Qt designer
* *
*/ */
Ui::ApplicationDialog mUI; Ui::ApplicationDialog mUI;
private: private:
/** /**
* @brief Underlying Application * @brief Underlying Application
*/ */
Application& mApplication; Application& mApplication;
}; };
/// @} /// @}

View File

@ -27,8 +27,8 @@
/** /**
* @brief List of applications user has specified to open errors with. * @brief List of applications user has specified to open errors with.
*/ */
class ApplicationList : public QObject { class ApplicationList : public QObject {
Q_OBJECT Q_OBJECT
public: public:
@ -37,81 +37,81 @@ public:
virtual ~ApplicationList(); virtual ~ApplicationList();
/** /**
* @brief Load all applications * @brief Load all applications
* *
* @return true if loading succeeded, false if there is problem with * @return true if loading succeeded, false if there is problem with
* application list. Most probably because of older version settings need * application list. Most probably because of older version settings need
* to be upgraded. * to be upgraded.
*/ */
bool loadSettings(); bool loadSettings();
/** /**
* @brief Save all applications * @brief Save all applications
*/ */
void saveSettings() const; void saveSettings() const;
/** /**
* @brief Get the amount of applications in the list * @brief Get the amount of applications in the list
* @return The count of applications * @return The count of applications
*/ */
int getApplicationCount() const; int getApplicationCount() const;
/** /**
* @brief Get specific application's name * @brief Get specific application's name
* *
* @param index Index of the application whose name to get * @param index Index of the application whose name to get
* @return Name of the application * @return Name of the application
*/ */
const Application& getApplication(const int index) const; const Application& getApplication(const int index) const;
Application& getApplication(const int index); Application& getApplication(const int index);
/** /**
* @brief Return the default application. * @brief Return the default application.
* @return Index of the default application. * @return Index of the default application.
*/ */
int getDefaultApplication() const { int getDefaultApplication() const {
return mDefaultApplicationIndex; return mDefaultApplicationIndex;
} }
/** /**
* @brief Add a new application * @brief Add a new application
* *
* @param app Application to add. * @param app Application to add.
*/ */
void addApplication(const Application &app); void addApplication(const Application &app);
/** /**
* @brief Remove an application from the list * @brief Remove an application from the list
* *
* @param index Index of the application to remove. * @param index Index of the application to remove.
*/ */
void removeApplication(const int index); void removeApplication(const int index);
/** /**
* @brief Set application as default application. * @brief Set application as default application.
* @param index Index of the application to make the default one * @param index Index of the application to make the default one
*/ */
void setDefault(const int index); void setDefault(const int index);
/** /**
* @brief Remove all applications from this list and copy all applications from * @brief Remove all applications from this list and copy all applications from
* list given as a parameter. * list given as a parameter.
* @param list Copying source * @param list Copying source
*/ */
void copy(const ApplicationList *list); void copy(const ApplicationList *list);
protected: protected:
/** /**
* @brief Clear the list * @brief Clear the list
* *
*/ */
void clear(); void clear();
/** /**
* @brief Find editor used by default in Windows. * @brief Find editor used by default in Windows.
* Check if Notepad++ is installed and use it. If not, use Notepad. * Check if Notepad++ is installed and use it. If not, use Notepad.
*/ */
bool findDefaultWindowsEditor(); bool findDefaultWindowsEditor();
private: private:
@ -119,15 +119,15 @@ private:
bool checkAndAddApplication(const QString& appPath, const QString& name, const QString& parameters); bool checkAndAddApplication(const QString& appPath, const QString& name, const QString& parameters);
/** /**
* @brief List of applications * @brief List of applications
* *
*/ */
QList<Application> mApplications; QList<Application> mApplications;
/** /**
* @brief Index of the default application. * @brief Index of the default application.
* *
*/ */
int mDefaultApplicationIndex; int mDefaultApplicationIndex;
}; };
/// @} /// @}

View File

@ -36,26 +36,26 @@ public:
explicit CheckStatistics(QObject *parent = nullptr); explicit CheckStatistics(QObject *parent = nullptr);
/** /**
* @brief Add new checked item to statistics. * @brief Add new checked item to statistics.
* *
* @param tool Tool. * @param tool Tool.
* @param type Type of the item to add. * @param type Type of the item to add.
*/ */
void addItem(const QString &tool, ShowTypes::ShowType type); void addItem(const QString &tool, ShowTypes::ShowType type);
/** /**
* @brief Clear the statistics. * @brief Clear the statistics.
* *
*/ */
void clear(); void clear();
/** /**
* @brief Return statistics for given type. * @brief Return statistics for given type.
* *
* @param tool Tool. * @param tool Tool.
* @param type Type for which the statistics are returned. * @param type Type for which the statistics are returned.
* @return Number of items of given type. * @return Number of items of given type.
*/ */
unsigned getCount(const QString &tool, ShowTypes::ShowType type) const; unsigned getCount(const QString &tool, ShowTypes::ShowType type) const;
/** Get tools with results */ /** Get tools with results */

View File

@ -241,12 +241,12 @@ void CheckThread::runAddonsAndTools(const ImportProject::FileSettings *fileSetti
if (addon == CLANG_ANALYZER) { if (addon == CLANG_ANALYZER) {
/* /*
// Using clang // Using clang
args.insert(0,"--analyze"); args.insert(0,"--analyze");
args.insert(1, "-Xanalyzer"); args.insert(1, "-Xanalyzer");
args.insert(2, "-analyzer-output=text"); args.insert(2, "-analyzer-output=text");
args << fileName; args << fileName;
*/ */
// Using clang-tidy // Using clang-tidy
args.insert(0,"-checks=-*,clang-analyzer-*"); args.insert(0,"-checks=-*,clang-analyzer-*");
args.insert(1, fileName); args.insert(1, fileName);

View File

@ -31,9 +31,9 @@ class ThreadResult;
/// @{ /// @{
/** /**
* @brief Thread to run cppcheck * @brief Thread to run cppcheck
* *
*/ */
class CheckThread : public QThread { class CheckThread : public QThread {
Q_OBJECT Q_OBJECT
public: public:
@ -41,16 +41,16 @@ public:
virtual ~CheckThread(); virtual ~CheckThread();
/** /**
* @brief Set settings for cppcheck * @brief Set settings for cppcheck
* *
* @param settings settings for cppcheck * @param settings settings for cppcheck
*/ */
void check(const Settings &settings); void check(const Settings &settings);
/** /**
* @brief Run whole program analysis * @brief Run whole program analysis
* @param files All files * @param files All files
*/ */
void analyseWholeProgram(const QStringList &files); void analyseWholeProgram(const QStringList &files);
void setAddonsAndTools(const QStringList &addonsAndTools) { void setAddonsAndTools(const QStringList &addonsAndTools) {
@ -70,9 +70,9 @@ public:
} }
/** /**
* @brief method that is run in a thread * @brief method that is run in a thread
* *
*/ */
void run(); void run();
void stop(); void stop();
@ -92,21 +92,21 @@ public:
signals: signals:
/** /**
* @brief cpp checking is done * @brief cpp checking is done
* *
*/ */
void done(); void done();
void fileChecked(const QString &file); void fileChecked(const QString &file);
protected: protected:
/** /**
* @brief States for the check thread. * @brief States for the check thread.
* Whole purpose of these states is to allow stopping of the checking. When * Whole purpose of these states is to allow stopping of the checking. When
* stopping we say for the thread (Stopping) that stop when current check * stopping we say for the thread (Stopping) that stop when current check
* has been completed. Thread must be stopped cleanly, just terminating thread * has been completed. Thread must be stopped cleanly, just terminating thread
* likely causes unpredictable side-effects. * likely causes unpredictable side-effects.
*/ */
enum State { enum State {
Running, /**< The thread is checking. */ Running, /**< The thread is checking. */
Stopping, /**< The thread will stop after current work. */ Stopping, /**< The thread will stop after current work. */
@ -115,14 +115,14 @@ protected:
}; };
/** /**
* @brief Thread's current execution state. * @brief Thread's current execution state.
*/ */
State mState; State mState;
ThreadResult &mResult; ThreadResult &mResult;
/** /**
* @brief Cppcheck itself * @brief Cppcheck itself
*/ */
CppCheck mCppcheck; CppCheck mCppcheck;
private: private:

View File

@ -94,9 +94,9 @@ CodeEditorStyle CodeEditorStyle::loadSettings(QSettings *settings)
// style section exists - load values // style section exists - load values
settings->beginGroup(SETTINGS_STYLE_GROUP); settings->beginGroup(SETTINGS_STYLE_GROUP);
QString type = settings->value( QString type = settings->value(
SETTINGS_STYLE_TYPE, SETTINGS_STYLE_TYPE,
QVariant(SETTINGS_STYLE_TYPE_LIGHT) QVariant(SETTINGS_STYLE_TYPE_LIGHT)
).toString(); ).toString();
if (type == SETTINGS_STYLE_TYPE_LIGHT) { if (type == SETTINGS_STYLE_TYPE_LIGHT) {
settings->endGroup(); settings->endGroup();
return theStyle; return theStyle;
@ -108,53 +108,53 @@ CodeEditorStyle CodeEditorStyle::loadSettings(QSettings *settings)
} }
if (type == SETTINGS_STYLE_TYPE_CUSTOM) { if (type == SETTINGS_STYLE_TYPE_CUSTOM) {
theStyle.widgetFGColor = settings->value( theStyle.widgetFGColor = settings->value(
SETTINGS_STYLE_WIDGETFG, SETTINGS_STYLE_WIDGETFG,
QVariant(defaultStyleLight.widgetFGColor)).value<QColor>(); QVariant(defaultStyleLight.widgetFGColor)).value<QColor>();
theStyle.widgetBGColor = settings->value( theStyle.widgetBGColor = settings->value(
SETTINGS_STYLE_WIDGETBG, SETTINGS_STYLE_WIDGETBG,
QVariant(defaultStyleLight.widgetBGColor)).value<QColor>(); QVariant(defaultStyleLight.widgetBGColor)).value<QColor>();
theStyle.highlightBGColor = settings->value( theStyle.highlightBGColor = settings->value(
SETTINGS_STYLE_HILIFG, SETTINGS_STYLE_HILIFG,
QVariant(defaultStyleLight.highlightBGColor)).value<QColor>(); QVariant(defaultStyleLight.highlightBGColor)).value<QColor>();
theStyle.lineNumFGColor = settings->value( theStyle.lineNumFGColor = settings->value(
SETTINGS_STYLE_LINENUMFG, SETTINGS_STYLE_LINENUMFG,
QVariant(defaultStyleLight.lineNumFGColor)).value<QColor>(); QVariant(defaultStyleLight.lineNumFGColor)).value<QColor>();
theStyle.lineNumBGColor = settings->value( theStyle.lineNumBGColor = settings->value(
SETTINGS_STYLE_LINENUMBG, SETTINGS_STYLE_LINENUMBG,
QVariant(defaultStyleLight.lineNumBGColor)).value<QColor>(); QVariant(defaultStyleLight.lineNumBGColor)).value<QColor>();
theStyle.keywordColor = settings->value( theStyle.keywordColor = settings->value(
SETTINGS_STYLE_KEYWORDFG, SETTINGS_STYLE_KEYWORDFG,
QVariant(defaultStyleLight.keywordColor)).value<QColor>(); QVariant(defaultStyleLight.keywordColor)).value<QColor>();
QVariant defKeyWWt(static_cast<int>(defaultStyleLight.keywordWeight)); QVariant defKeyWWt(static_cast<int>(defaultStyleLight.keywordWeight));
theStyle.keywordWeight = static_cast<QFont::Weight>( theStyle.keywordWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_KEYWORDWT, defKeyWWt).toInt()); settings->value(SETTINGS_STYLE_KEYWORDWT, defKeyWWt).toInt());
theStyle.classColor = settings->value( theStyle.classColor = settings->value(
SETTINGS_STYLE_CLASSFG, SETTINGS_STYLE_CLASSFG,
QVariant(defaultStyleLight.classColor)).value<QColor>(); QVariant(defaultStyleLight.classColor)).value<QColor>();
QVariant defClsWt(static_cast<int>(defaultStyleLight.classWeight)); QVariant defClsWt(static_cast<int>(defaultStyleLight.classWeight));
theStyle.classWeight = static_cast<QFont::Weight>( theStyle.classWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_CLASSWT, defClsWt).toInt()); settings->value(SETTINGS_STYLE_CLASSWT, defClsWt).toInt());
theStyle.quoteColor = settings->value( theStyle.quoteColor = settings->value(
SETTINGS_STYLE_QUOTEFG, SETTINGS_STYLE_QUOTEFG,
QVariant(defaultStyleLight.quoteColor)).value<QColor>(); QVariant(defaultStyleLight.quoteColor)).value<QColor>();
QVariant defQteWt(static_cast<int>(defaultStyleLight.quoteWeight)); QVariant defQteWt(static_cast<int>(defaultStyleLight.quoteWeight));
theStyle.quoteWeight = static_cast<QFont::Weight>( theStyle.quoteWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_QUOTEWT, defQteWt).toInt()); settings->value(SETTINGS_STYLE_QUOTEWT, defQteWt).toInt());
theStyle.commentColor = settings->value( theStyle.commentColor = settings->value(
SETTINGS_STYLE_COMMENTFG, SETTINGS_STYLE_COMMENTFG,
QVariant(defaultStyleLight.commentColor)).value<QColor>(); QVariant(defaultStyleLight.commentColor)).value<QColor>();
QVariant defCmtWt(static_cast<int>(defaultStyleLight.commentWeight)); QVariant defCmtWt(static_cast<int>(defaultStyleLight.commentWeight));
theStyle.commentWeight = static_cast<QFont::Weight>( theStyle.commentWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_COMMENTWT, defCmtWt).toInt()); settings->value(SETTINGS_STYLE_COMMENTWT, defCmtWt).toInt());
theStyle.symbolFGColor = settings->value( theStyle.symbolFGColor = settings->value(
SETTINGS_STYLE_SYMBOLFG, SETTINGS_STYLE_SYMBOLFG,
QVariant(defaultStyleLight.symbolFGColor)).value<QColor>(); QVariant(defaultStyleLight.symbolFGColor)).value<QColor>();
theStyle.symbolBGColor = settings->value( theStyle.symbolBGColor = settings->value(
SETTINGS_STYLE_SYMBOLBG, SETTINGS_STYLE_SYMBOLBG,
QVariant(defaultStyleLight.symbolBGColor)).value<QColor>(); QVariant(defaultStyleLight.symbolBGColor)).value<QColor>();
QVariant defSymWt(static_cast<int>(defaultStyleLight.symbolWeight)); QVariant defSymWt(static_cast<int>(defaultStyleLight.symbolWeight));
theStyle.symbolWeight = static_cast<QFont::Weight>( theStyle.symbolWeight = static_cast<QFont::Weight>(
settings->value(SETTINGS_STYLE_SYMBOLWT, defSymWt).toInt()); settings->value(SETTINGS_STYLE_SYMBOLWT, defSymWt).toInt());
} }
settings->endGroup(); settings->endGroup();
return theStyle; return theStyle;

View File

@ -73,47 +73,47 @@ public:
static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle); static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle);
public: public:
bool mSystemTheme; bool mSystemTheme;
QColor widgetFGColor; QColor widgetFGColor;
QColor widgetBGColor; QColor widgetBGColor;
QColor highlightBGColor; QColor highlightBGColor;
QColor lineNumFGColor; QColor lineNumFGColor;
QColor lineNumBGColor; QColor lineNumBGColor;
QColor keywordColor; QColor keywordColor;
QFont::Weight keywordWeight; QFont::Weight keywordWeight;
QColor classColor; QColor classColor;
QFont::Weight classWeight; QFont::Weight classWeight;
QColor quoteColor; QColor quoteColor;
QFont::Weight quoteWeight; QFont::Weight quoteWeight;
QColor commentColor; QColor commentColor;
QFont::Weight commentWeight; QFont::Weight commentWeight;
QColor symbolFGColor; QColor symbolFGColor;
QColor symbolBGColor; QColor symbolBGColor;
QFont::Weight symbolWeight; QFont::Weight symbolWeight;
}; };
static const CodeEditorStyle defaultStyleLight( static const CodeEditorStyle defaultStyleLight(
/* editor FG/BG */ Qt::black, QColor(240, 240, 240), /* editor FG/BG */ Qt::black, QColor(240, 240, 240),
/* highlight BG */ QColor(255, 220, 220), /* highlight BG */ QColor(255, 220, 220),
/* line number FG/BG */ Qt::black, QColor(240, 240, 240), /* line number FG/BG */ Qt::black, QColor(240, 240, 240),
/* keyword FG/Weight */ Qt::darkBlue, QFont::Bold, /* keyword FG/Weight */ Qt::darkBlue, QFont::Bold,
/* class FG/Weight */ Qt::darkMagenta, QFont::Bold, /* class FG/Weight */ Qt::darkMagenta, QFont::Bold,
/* quote FG/Weight */ Qt::darkGreen, QFont::Normal, /* quote FG/Weight */ Qt::darkGreen, QFont::Normal,
/* comment FG/Weight */ Qt::gray, QFont::Normal, /* comment FG/Weight */ Qt::gray, QFont::Normal,
/* Symbol FG/BG/Weight */ Qt::red, QColor(220, 220, 255), QFont::Normal /* Symbol FG/BG/Weight */ Qt::red, QColor(220, 220, 255), QFont::Normal
); );
// Styling derived from Eclipse Color Theme - 'RecognEyes' // Styling derived from Eclipse Color Theme - 'RecognEyes'
// http://www.eclipsecolorthemes.org/?view=theme&id=30 // http://www.eclipsecolorthemes.org/?view=theme&id=30
static const CodeEditorStyle defaultStyleDark( static const CodeEditorStyle defaultStyleDark(
/* editor FG/BG */ QColor(218, 218, 218), QColor(16, 16, 32), /* editor FG/BG */ QColor(218, 218, 218), QColor(16, 16, 32),
/* highlight BG */ QColor(64, 64, 64), /* highlight BG */ QColor(64, 64, 64),
/* line number FG/BG */ QColor(43, 145, 175), QColor(16, 16, 32), /* line number FG/BG */ QColor(43, 145, 175), QColor(16, 16, 32),
/* keyword FG/Weight */ QColor(0, 204, 204), QFont::Bold, /* keyword FG/Weight */ QColor(0, 204, 204), QFont::Bold,
/* class FG/Weight */ QColor(218, 0, 218), QFont::Bold, /* class FG/Weight */ QColor(218, 0, 218), QFont::Bold,
/* quote FG/Weight */ QColor(0, 204, 0), QFont::Normal, /* quote FG/Weight */ QColor(0, 204, 0), QFont::Normal,
/* comment FG/Weight */ QColor(180, 180, 180), QFont::Normal, /* comment FG/Weight */ QColor(180, 180, 180), QFont::Normal,
/* Symbol FG/BG/Weight */ QColor(218, 32, 32), QColor(32, 32, 108), QFont::Normal /* Symbol FG/BG/Weight */ QColor(218, 32, 32), QColor(32, 32, 108), QFont::Normal
); );
#endif /* CODEEDITORSTYLE_H */ #endif /* CODEEDITORSTYLE_H */

View File

@ -30,9 +30,9 @@ SelectColorButton::SelectColorButton(QWidget* parent) :
void SelectColorButton::updateColor() void SelectColorButton::updateColor()
{ {
QString btnColorStyle = QString( QString btnColorStyle = QString(
"background-color:rgb(%1,%2,%3);" "background-color:rgb(%1,%2,%3);"
"border-style:outset;" "border-style:outset;"
"border-width: 1px;") "border-width: 1px;")
.arg(mColor.red()) .arg(mColor.red())
.arg(mColor.green()) .arg(mColor.green())
.arg(mColor.blue()); .arg(mColor.blue());

View File

@ -50,10 +50,10 @@ const QString StyleEditDialog::mSampleDocument(
"}\n"); "}\n");
const QStringList StyleEditDialog::mErrSymbolsList = ( const QStringList StyleEditDialog::mErrSymbolsList = (
QStringList(QStringList() QStringList(QStringList()
<< "nLife" << "nLife"
<< "dValue" << "dValue"
<< "nValue")); << "nValue"));
const int StyleEditDialog::mErrLineNum = 16; const int StyleEditDialog::mErrLineNum = 16;
StyleEditDialog::StyleEditDialog(const CodeEditorStyle& newStyle, StyleEditDialog::StyleEditDialog(const CodeEditorStyle& newStyle,

View File

@ -62,8 +62,8 @@ public slots:
void weightChangedSymbol(const QFont::Weight& newWeight); void weightChangedSymbol(const QFont::Weight& newWeight);
private: private:
CodeEditorStyle mStyleIncoming; CodeEditorStyle mStyleIncoming;
CodeEditorStyle mStyleOutgoing; CodeEditorStyle mStyleOutgoing;
CodeEditor *mSampleEditor; CodeEditor *mSampleEditor;
@ -87,9 +87,9 @@ private:
QPushButton *mBtnDefaultLight; QPushButton *mBtnDefaultLight;
QPushButton *mBtnDefaultDark; QPushButton *mBtnDefaultDark;
static const QString mSampleDocument; static const QString mSampleDocument;
static const QStringList mErrSymbolsList; static const QStringList mErrSymbolsList;
static const int mErrLineNum; static const int mErrLineNum;
}; };
#endif //CODEEDITSTYLEDIALOG_H #endif //CODEEDITSTYLEDIALOG_H

View File

@ -50,7 +50,7 @@ QString toFilterString(const QMap<QString,QString>& filters, bool addAllSupporte
if (addAllSupported) { if (addAllSupported) {
entries << QCoreApplication::translate("toFilterString", "All supported files (%1)") entries << QCoreApplication::translate("toFilterString", "All supported files (%1)")
.arg(QStringList(filters.values()).join(" ")); .arg(QStringList(filters.values()).join(" "));
} }
if (addAll) { if (addAll) {

View File

@ -29,8 +29,8 @@
#define CLANG_TIDY "clang-tidy" #define CLANG_TIDY "clang-tidy"
/** /**
* QSetting value names * QSetting value names
*/ */
// Window/dialog sizes // Window/dialog sizes
#define SETTINGS_WINDOW_MAXIMIZED "Window maximized" #define SETTINGS_WINDOW_MAXIMIZED "Window maximized"

View File

@ -27,8 +27,7 @@ const unsigned int CppcheckLibraryData::Function::Arg::ANY = ~0U;
const unsigned int CppcheckLibraryData::Function::Arg::VARIADIC = ~1U; const unsigned int CppcheckLibraryData::Function::Arg::VARIADIC = ~1U;
CppcheckLibraryData::CppcheckLibraryData() CppcheckLibraryData::CppcheckLibraryData()
{ {}
}
static std::string unhandledElement(const QXmlStreamReader &xmlReader) static std::string unhandledElement(const QXmlStreamReader &xmlReader)
{ {

View File

@ -40,7 +40,7 @@ public:
QString itEndPattern; QString itEndPattern;
bool access_arrayLike; bool access_arrayLike;
int size_templateParameter; int size_templateParameter;
struct { struct {
QString templateParameter; QString templateParameter;
@ -64,8 +64,7 @@ public:
struct Function { struct Function {
Function() : noreturn(Unknown), gccPure(false), gccConst(false), Function() : noreturn(Unknown), gccPure(false), gccConst(false),
leakignore(false), useretval(false) { leakignore(false), useretval(false) {}
}
QString comments; QString comments;
QString name; QString name;
@ -89,8 +88,7 @@ public:
} formatstr; } formatstr;
struct Arg { struct Arg {
Arg() : nr(0), notbool(false), notnull(false), notuninit(false), Arg() : nr(0), notbool(false), notnull(false), notuninit(false),
formatstr(false), strz(false) { formatstr(false), strz(false) {}
}
QString name; QString name;
unsigned int nr; unsigned int nr;

View File

@ -24,12 +24,10 @@
CsvReport::CsvReport(const QString &filename) : CsvReport::CsvReport(const QString &filename) :
Report(filename) Report(filename)
{ {}
}
CsvReport::~CsvReport() CsvReport::~CsvReport()
{ {}
}
bool CsvReport::create() bool CsvReport::create()
{ {
@ -54,9 +52,9 @@ void CsvReport::writeFooter()
void CsvReport::writeError(const ErrorItem &error) void CsvReport::writeError(const ErrorItem &error)
{ {
/* /*
Error as CSV line Error as CSV line
gui/test.cpp,23,error,Mismatching allocation and deallocation: k gui/test.cpp,23,error,Mismatching allocation and deallocation: k
*/ */
const QString file = QDir::toNativeSeparators(error.errorPath.back().file); const QString file = QDir::toNativeSeparators(error.errorPath.back().file);
QString line = QString("%1,%2,").arg(file).arg(error.errorPath.back().line); QString line = QString("%1,%2,").arg(file).arg(error.errorPath.back().line);

View File

@ -28,43 +28,43 @@
/** /**
* @brief CSV text file report. * @brief CSV text file report.
* This report exports results as CSV (comma separated values). CSV files are * This report exports results as CSV (comma separated values). CSV files are
* easy to import to many other programs. * easy to import to many other programs.
* @todo This class should be inherited from TxtReport? * @todo This class should be inherited from TxtReport?
*/ */
class CsvReport : public Report { class CsvReport : public Report {
public: public:
explicit CsvReport(const QString &filename); explicit CsvReport(const QString &filename);
virtual ~CsvReport(); virtual ~CsvReport();
/** /**
* @brief Create the report (file). * @brief Create the report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool create() override; virtual bool create() override;
/** /**
* @brief Write report header. * @brief Write report header.
*/ */
virtual void writeHeader() override; virtual void writeHeader() override;
/** /**
* @brief Write report footer. * @brief Write report footer.
*/ */
virtual void writeFooter() override; virtual void writeFooter() override;
/** /**
* @brief Write error to report. * @brief Write error to report.
* @param error Error data. * @param error Error data.
*/ */
virtual void writeError(const ErrorItem &error) override; virtual void writeError(const ErrorItem &error) override;
private: private:
/** /**
* @brief Text stream writer for writing the report in text format. * @brief Text stream writer for writing the report in text format.
*/ */
QTextStream mTxtWriter; QTextStream mTxtWriter;
}; };
/// @} /// @}

View File

@ -24,8 +24,7 @@ QErrorPathItem::QErrorPathItem(const ErrorMessage::FileLocation &loc)
, line(loc.line) , line(loc.line)
, column(loc.column) , column(loc.column)
, info(QString::fromStdString(loc.getinfo())) , info(QString::fromStdString(loc.getinfo()))
{ {}
}
bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2) bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2)
{ {
@ -38,8 +37,7 @@ ErrorItem::ErrorItem()
, inconclusive(false) , inconclusive(false)
, cwe(-1) , cwe(-1)
, hash(0) , hash(0)
{ {}
}
ErrorItem::ErrorItem(const ErrorMessage &errmsg) ErrorItem::ErrorItem(const ErrorMessage &errmsg)
: file0(QString::fromStdString(errmsg.file0)) : file0(QString::fromStdString(errmsg.file0))

View File

@ -45,8 +45,8 @@ public:
}; };
/** /**
* @brief A class containing data for one error path item * @brief A class containing data for one error path item
*/ */
class QErrorPathItem { class QErrorPathItem {
public: public:
QErrorPathItem() : line(0), column(-1) {} QErrorPathItem() : line(0), column(-1) {}
@ -60,22 +60,22 @@ public:
bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2); bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2);
/** /**
* @brief A class containing error data for one error. * @brief A class containing error data for one error.
* *
* The paths are stored with internal ("/") separators. Only when we show the * The paths are stored with internal ("/") separators. Only when we show the
* path or copy if for user (to clipboard) we convert to native separators. * path or copy if for user (to clipboard) we convert to native separators.
* Full path is stored instead of relative path for flexibility. It is easy * Full path is stored instead of relative path for flexibility. It is easy
* to get the relative path from full path when needed. * to get the relative path from full path when needed.
*/ */
class ErrorItem { class ErrorItem {
public: public:
ErrorItem(); ErrorItem();
explicit ErrorItem(const ErrorMessage &errmsg); explicit ErrorItem(const ErrorMessage &errmsg);
/** /**
* @brief Convert error item to string. * @brief Convert error item to string.
* @return Error item as string. * @return Error item as string.
*/ */
QString toString() const; QString toString() const;
QString tool() const; QString tool() const;
@ -105,8 +105,8 @@ public:
Q_DECLARE_METATYPE(ErrorItem) Q_DECLARE_METATYPE(ErrorItem)
/** /**
* @brief A class containing error data for one shown error line. * @brief A class containing error data for one shown error line.
*/ */
class ErrorLine { class ErrorLine {
public: public:
QString file; QString file;

View File

@ -38,57 +38,57 @@ class FileList {
public: public:
/** /**
* @brief Add filename to the list. * @brief Add filename to the list.
* @param filepath Full path to the file. * @param filepath Full path to the file.
*/ */
void addFile(const QString &filepath); void addFile(const QString &filepath);
/** /**
* @brief Add files in the directory to the list. * @brief Add files in the directory to the list.
* @param directory Full pathname to directory to add. * @param directory Full pathname to directory to add.
* @param recursive If true also files in subdirectories are added. * @param recursive If true also files in subdirectories are added.
*/ */
void addDirectory(const QString &directory, bool recursive = false); void addDirectory(const QString &directory, bool recursive = false);
/** /**
* @brief Add list of filenames and directories to the list. * @brief Add list of filenames and directories to the list.
* @param paths List of paths to add. * @param paths List of paths to add.
*/ */
void addPathList(const QStringList &paths); void addPathList(const QStringList &paths);
/** /**
* @brief Return list of filenames (to check). * @brief Return list of filenames (to check).
* @return list of filenames to check. * @return list of filenames to check.
*/ */
QStringList getFileList() const; QStringList getFileList() const;
/** /**
* @brief Add list of paths to exclusion list. * @brief Add list of paths to exclusion list.
* @param paths Paths to exclude. * @param paths Paths to exclude.
*/ */
void addExcludeList(const QStringList &paths); void addExcludeList(const QStringList &paths);
/** /**
* @brief Return list of default filename extensions included. * @brief Return list of default filename extensions included.
* @return list of default filename extensions included. * @return list of default filename extensions included.
*/ */
static QStringList getDefaultFilters(); static QStringList getDefaultFilters();
protected: protected:
/** /**
* @brief Test if filename matches the filename extensions filtering. * @brief Test if filename matches the filename extensions filtering.
* @return true if filename matches filtering. * @return true if filename matches filtering.
*/ */
static bool filterMatches(const QFileInfo &inf); static bool filterMatches(const QFileInfo &inf);
/** /**
* @brief Get filtered list of paths. * @brief Get filtered list of paths.
* This method takes the list of paths and applies the exclude lists to * This method takes the list of paths and applies the exclude lists to
* it. And then returns the list of paths that did not match the * it. And then returns the list of paths that did not match the
* exclude filters. * exclude filters.
* @return Filtered list of paths. * @return Filtered list of paths.
*/ */
QStringList applyExcludeList() const; QStringList applyExcludeList() const;
private: private:

View File

@ -31,11 +31,11 @@ class QTextEdit;
/** /**
* @brief File view -dialog. * @brief File view -dialog.
* This dialog shows text files. It is used for showing the license file and * This dialog shows text files. It is used for showing the license file and
* the authors list. * the authors list.
* *
*/ */
class FileViewDialog : public QDialog { class FileViewDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
@ -47,11 +47,11 @@ public:
protected: protected:
/** /**
* @brief Load text file contents to edit control. * @brief Load text file contents to edit control.
* *
* @param filename File to load. * @param filename File to load.
* @param edit Control where to load the file contents. * @param edit Control where to load the file contents.
*/ */
void loadTextFile(const QString &filename, QTextEdit *edit); void loadTextFile(const QString &filename, QTextEdit *edit);
Ui::Fileview mUI; Ui::Fileview mUI;

View File

@ -82,7 +82,7 @@ HelpDialog::HelpDialog(QWidget *parent) :
SLOT(setSource(QUrl))); SLOT(setSource(QUrl)));
connect(mHelpEngine->indexWidget(), connect(mHelpEngine->indexWidget(),
SIGNAL(linkActivated(QUrl, QString)), SIGNAL(linkActivated(QUrl,QString)),
mUi->textBrowser, mUi->textBrowser,
SLOT(setSource(QUrl))); SLOT(setSource(QUrl)));
} }

View File

@ -79,10 +79,10 @@ void LibraryDialog::openCfg()
QString selectedFilter; QString selectedFilter;
const QString filter(tr("Library files (*.cfg)")); const QString filter(tr("Library files (*.cfg)"));
const QString selectedFile = QFileDialog::getOpenFileName(this, const QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Open library file"), tr("Open library file"),
datadir, datadir,
filter, filter,
&selectedFilter); &selectedFilter);
if (selectedFile.isEmpty()) if (selectedFile.isEmpty())
return; return;
@ -119,8 +119,8 @@ void LibraryDialog::openCfg()
mUi->functions->clear(); mUi->functions->clear();
for (CppcheckLibraryData::Function &function : mData.functions) { for (CppcheckLibraryData::Function &function : mData.functions) {
mUi->functions->addItem(new FunctionListItem(mUi->functions, mUi->functions->addItem(new FunctionListItem(mUi->functions,
&function, &function,
false)); false));
} }
mUi->sortFunctions->setEnabled(!mData.functions.empty()); mUi->sortFunctions->setEnabled(!mData.functions.empty());
mUi->filter->setEnabled(!mData.functions.empty()); mUi->filter->setEnabled(!mData.functions.empty());
@ -152,9 +152,9 @@ void LibraryDialog::saveCfgAs()
const QString filter(tr("Library files (*.cfg)")); const QString filter(tr("Library files (*.cfg)"));
const QString path = Path::getPathFromFilename(mFileName.toStdString()).c_str(); const QString path = Path::getPathFromFilename(mFileName.toStdString()).c_str();
QString selectedFile = QFileDialog::getSaveFileName(this, QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save the library as"), tr("Save the library as"),
path, path,
filter); filter);
if (selectedFile.isEmpty()) if (selectedFile.isEmpty())
return; return;
@ -260,8 +260,8 @@ void LibraryDialog::sortFunctions(bool sort)
mUi->functions->clear(); mUi->functions->clear();
for (CppcheckLibraryData::Function &function : mData.functions) { for (CppcheckLibraryData::Function &function : mData.functions) {
mUi->functions->addItem(new FunctionListItem(mUi->functions, mUi->functions->addItem(new FunctionListItem(mUi->functions,
&function, &function,
selfunction == &function)); selfunction == &function));
} }
if (!mUi->filter->text().isEmpty()) if (!mUi->filter->text().isEmpty())
filterFunctions(mUi->filter->text()); filterFunctions(mUi->filter->text());

View File

@ -103,24 +103,24 @@ static bool CheckArgs(const QStringList &args)
static void ShowUsage() static void ShowUsage()
{ {
QString helpMessage = MainWindow::tr( QString helpMessage = MainWindow::tr(
"Cppcheck GUI.\n\n" "Cppcheck GUI.\n\n"
"Syntax:\n" "Syntax:\n"
" cppcheck-gui [OPTIONS] [files or paths]\n\n" " cppcheck-gui [OPTIONS] [files or paths]\n\n"
"Options:\n" "Options:\n"
" -h, --help Print this help\n" " -h, --help Print this help\n"
" -p <file> Open given project file and start checking it\n" " -p <file> Open given project file and start checking it\n"
" -l <file> Open given results xml file\n" " -l <file> Open given results xml file\n"
" -d <directory> Specify the directory that was checked to generate the results xml specified with -l\n" " -d <directory> Specify the directory that was checked to generate the results xml specified with -l\n"
" -v, --version Show program version\n" " -v, --version Show program version\n"
" --data-dir=<directory> This option is for installation scripts so they can configure the directory where\n" " --data-dir=<directory> This option is for installation scripts so they can configure the directory where\n"
" datafiles are located (translations, cfg). The GUI is not started when this option\n" " datafiles are located (translations, cfg). The GUI is not started when this option\n"
" is used."); " is used.");
#if defined(_WIN32) #if defined(_WIN32)
QMessageBox msgBox(QMessageBox::Information, QMessageBox msgBox(QMessageBox::Information,
MainWindow::tr("Cppcheck GUI - Command line parameters"), MainWindow::tr("Cppcheck GUI - Command line parameters"),
helpMessage, helpMessage,
QMessageBox::Ok QMessageBox::Ok
); );
(void)msgBox.exec(); (void)msgBox.exec();
#else #else
std::cout << helpMessage.toStdString() << std::endl; std::cout << helpMessage.toStdString() << std::endl;

View File

@ -515,7 +515,7 @@ void MainWindow::doAnalyzeFiles(const QStringList &files, const bool checkLibrar
checkSettings.loadSummaries(); checkSettings.loadSummaries();
std::list<std::string> sourcefiles; std::list<std::string> sourcefiles;
foreach (QString s, fileNames) foreach (QString s, fileNames)
sourcefiles.push_back(s.toStdString()); sourcefiles.push_back(s.toStdString());
AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, checkSettings.project.fileSettings); AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, checkSettings.project.fileSettings);
} }
@ -528,14 +528,14 @@ void MainWindow::analyzeCode(const QString& code, const QString& filename)
// Initialize dummy ThreadResult as ErrorLogger // Initialize dummy ThreadResult as ErrorLogger
ThreadResult result; ThreadResult result;
result.setFiles(QStringList(filename)); result.setFiles(QStringList(filename));
connect(&result, SIGNAL(progress(int, const QString&)), connect(&result, SIGNAL(progress(int,const QString&)),
mUI.mResults, SLOT(progress(int, const QString&))); mUI.mResults, SLOT(progress(int,const QString&)));
connect(&result, SIGNAL(error(const ErrorItem &)), connect(&result, SIGNAL(error(const ErrorItem&)),
mUI.mResults, SLOT(error(const ErrorItem &))); mUI.mResults, SLOT(error(const ErrorItem&)));
connect(&result, SIGNAL(log(const QString &)), connect(&result, SIGNAL(log(const QString&)),
mUI.mResults, SLOT(log(const QString &))); mUI.mResults, SLOT(log(const QString&)));
connect(&result, SIGNAL(debugError(const ErrorItem &)), connect(&result, SIGNAL(debugError(const ErrorItem&)),
mUI.mResults, SLOT(debugError(const ErrorItem &))); mUI.mResults, SLOT(debugError(const ErrorItem&)));
// Create CppCheck instance // Create CppCheck instance
CppCheck cppcheck(result, true, nullptr); CppCheck cppcheck(result, true, nullptr);
@ -578,10 +578,10 @@ QStringList MainWindow::selectFilesToAnalyze(QFileDialog::FileMode mode)
filters[tr("Borland C++ Builder 6")] = "*.bpr"; filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString lastFilter = mSettings->value(SETTINGS_LAST_ANALYZE_FILES_FILTER).toString(); QString lastFilter = mSettings->value(SETTINGS_LAST_ANALYZE_FILES_FILTER).toString();
selected = QFileDialog::getOpenFileNames(this, selected = QFileDialog::getOpenFileNames(this,
tr("Select files to analyze"), tr("Select files to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH), getPath(SETTINGS_LAST_CHECK_PATH),
toFilterString(filters), toFilterString(filters),
&lastFilter); &lastFilter);
mSettings->setValue(SETTINGS_LAST_ANALYZE_FILES_FILTER, lastFilter); mSettings->setValue(SETTINGS_LAST_ANALYZE_FILES_FILTER, lastFilter);
if (selected.isEmpty()) if (selected.isEmpty())
@ -593,8 +593,8 @@ QStringList MainWindow::selectFilesToAnalyze(QFileDialog::FileMode mode)
formatAndSetTitle(); formatAndSetTitle();
} else if (mode == QFileDialog::DirectoryOnly) { } else if (mode == QFileDialog::DirectoryOnly) {
QString dir = QFileDialog::getExistingDirectory(this, QString dir = QFileDialog::getExistingDirectory(this,
tr("Select directory to analyze"), tr("Select directory to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH)); getPath(SETTINGS_LAST_CHECK_PATH));
if (!dir.isEmpty()) { if (!dir.isEmpty()) {
qDebug() << "Setting current directory to: " << dir; qDebug() << "Setting current directory to: " << dir;
mCurrentDirectory = dir; mCurrentDirectory = dir;
@ -884,7 +884,7 @@ Settings MainWindow::getCppcheckSettings()
const QStringList undefines = mProjectFile->getUndefines(); const QStringList undefines = mProjectFile->getUndefines();
foreach (QString undefine, undefines) foreach (QString undefine, undefines)
result.userUndefs.insert(undefine.toStdString()); result.userUndefs.insert(undefine.toStdString());
const QStringList libraries = mProjectFile->getLibraries(); const QStringList libraries = mProjectFile->getLibraries();
foreach (QString library, libraries) { foreach (QString library, libraries) {
@ -938,7 +938,7 @@ Settings MainWindow::getCppcheckSettings()
result.safeChecks.internalFunctions = mProjectFile->safeChecks.internalFunctions; result.safeChecks.internalFunctions = mProjectFile->safeChecks.internalFunctions;
result.safeChecks.externalVariables = mProjectFile->safeChecks.externalVariables; result.safeChecks.externalVariables = mProjectFile->safeChecks.externalVariables;
foreach (QString s, mProjectFile->getCheckUnknownFunctionReturn()) foreach (QString s, mProjectFile->getCheckUnknownFunctionReturn())
result.checkUnknownFunctionReturn.insert(s.toStdString()); result.checkUnknownFunctionReturn.insert(s.toStdString());
QString filesDir(getDataDir()); QString filesDir(getDataDir());
const QString pythonCmd = mSettings->value(SETTINGS_PYTHON_PATH).toString(); const QString pythonCmd = mSettings->value(SETTINGS_PYTHON_PATH).toString();
@ -1210,10 +1210,10 @@ void MainWindow::openResults()
QString selectedFilter; QString selectedFilter;
const QString filter(tr("XML files (*.xml)")); const QString filter(tr("XML files (*.xml)"));
QString selectedFile = QFileDialog::getOpenFileName(this, QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Open the report file"), tr("Open the report file"),
getPath(SETTINGS_LAST_RESULT_PATH), getPath(SETTINGS_LAST_RESULT_PATH),
filter, filter,
&selectedFilter); &selectedFilter);
if (!selectedFile.isEmpty()) { if (!selectedFile.isEmpty()) {
loadResults(selectedFile); loadResults(selectedFile);
@ -1381,10 +1381,10 @@ void MainWindow::save()
QString selectedFilter; QString selectedFilter;
const QString filter(tr("XML files (*.xml);;Text files (*.txt);;CSV files (*.csv)")); const QString filter(tr("XML files (*.xml);;Text files (*.txt);;CSV files (*.csv)"));
QString selectedFile = QFileDialog::getSaveFileName(this, QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save the report file"), tr("Save the report file"),
getPath(SETTINGS_LAST_RESULT_PATH), getPath(SETTINGS_LAST_RESULT_PATH),
filter, filter,
&selectedFilter); &selectedFilter);
if (!selectedFile.isEmpty()) { if (!selectedFile.isEmpty()) {
Report::Type type = Report::TXT; Report::Type type = Report::TXT;
@ -1415,8 +1415,7 @@ void MainWindow::save()
} }
void MainWindow::resultsAdded() void MainWindow::resultsAdded()
{ {}
}
void MainWindow::toggleMainToolBar() void MainWindow::toggleMainToolBar()
{ {
@ -1501,9 +1500,9 @@ void MainWindow::openProjectFile()
{ {
const QString filter = tr("Project files (*.cppcheck);;All files(*.*)"); const QString filter = tr("Project files (*.cppcheck);;All files(*.*)");
const QString filepath = QFileDialog::getOpenFileName(this, const QString filepath = QFileDialog::getOpenFileName(this,
tr("Select Project File"), tr("Select Project File"),
getPath(SETTINGS_LAST_PROJECT_PATH), getPath(SETTINGS_LAST_PROJECT_PATH),
filter); filter);
if (!filepath.isEmpty()) { if (!filepath.isEmpty()) {
const QFileInfo fi(filepath); const QFileInfo fi(filepath);
@ -1650,9 +1649,9 @@ void MainWindow::newProjectFile()
{ {
const QString filter = tr("Project files (*.cppcheck)"); const QString filter = tr("Project files (*.cppcheck)");
QString filepath = QFileDialog::getSaveFileName(this, QString filepath = QFileDialog::getSaveFileName(this,
tr("Select Project Filename"), tr("Select Project Filename"),
getPath(SETTINGS_LAST_PROJECT_PATH), getPath(SETTINGS_LAST_PROJECT_PATH),
filter); filter);
if (filepath.isEmpty()) if (filepath.isEmpty())
return; return;

View File

@ -58,8 +58,8 @@ public:
MainWindow &operator=(const MainWindow &) = delete; MainWindow &operator=(const MainWindow &) = delete;
/** /**
* List of checked platforms. * List of checked platforms.
*/ */
Platforms mPlatforms; Platforms mPlatforms;
/** /**
@ -254,11 +254,11 @@ private:
void reAnalyzeSelected(QStringList files); void reAnalyzeSelected(QStringList files);
/** /**
* @brief Analyze the project. * @brief Analyze the project.
* @param projectFile Pointer to the project to analyze. * @param projectFile Pointer to the project to analyze.
* @param checkLibrary Flag to indicate if the library should be checked. * @param checkLibrary Flag to indicate if the library should be checked.
* @param checkConfiguration Flag to indicate if the configuration should be checked. * @param checkConfiguration Flag to indicate if the configuration should be checked.
*/ */
void analyzeProject(const ProjectFile *projectFile, const bool checkLibrary = false, const bool checkConfiguration = false); void analyzeProject(const ProjectFile *projectFile, const bool checkLibrary = false, const bool checkConfiguration = false);
/** /**
@ -373,9 +373,9 @@ private:
void loadResults(const QString &selectedFile, const QString &sourceDirectory); void loadResults(const QString &selectedFile, const QString &sourceDirectory);
/** /**
* @brief Load last project results to the GUI. * @brief Load last project results to the GUI.
* @return Returns true if last results was loaded * @return Returns true if last results was loaded
*/ */
bool loadLastResults(); bool loadLastResults();
/** /**

View File

@ -13,11 +13,11 @@ NewSuppressionDialog::NewSuppressionDialog(QWidget *parent) :
class QErrorLogger : public ErrorLogger { class QErrorLogger : public ErrorLogger {
public: public:
void reportOut(const std::string &/*outmsg*/, Color) override {} void reportOut(const std::string & /*outmsg*/, Color) override {}
void reportErr(const ErrorMessage &msg) override { void reportErr(const ErrorMessage &msg) override {
errorIds << QString::fromStdString(msg.id); errorIds << QString::fromStdString(msg.id);
} }
void bughuntingReport(const std::string &/*str*/) override {} void bughuntingReport(const std::string & /*str*/) override {}
QStringList errorIds; QStringList errorIds;
}; };

View File

@ -39,8 +39,8 @@ struct Platform {
}; };
/** /**
* @brief List of checked platforms. * @brief List of checked platforms.
*/ */
class Platforms : public QObject { class Platforms : public QObject {
Q_OBJECT Q_OBJECT

View File

@ -23,12 +23,10 @@
PrintableReport::PrintableReport() : PrintableReport::PrintableReport() :
Report(QString()) Report(QString())
{ {}
}
PrintableReport::~PrintableReport() PrintableReport::~PrintableReport()
{ {}
}
bool PrintableReport::create() bool PrintableReport::create()
{ {

View File

@ -26,46 +26,46 @@
/** /**
* @brief Printable (in-memory) report. * @brief Printable (in-memory) report.
* This report formats results and exposes them for printing. * This report formats results and exposes them for printing.
*/ */
class PrintableReport : public Report { class PrintableReport : public Report {
public: public:
PrintableReport(); PrintableReport();
virtual ~PrintableReport(); virtual ~PrintableReport();
/** /**
* @brief Create the report (file). * @brief Create the report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool create() override; virtual bool create() override;
/** /**
* @brief Write report header. * @brief Write report header.
*/ */
virtual void writeHeader() override; virtual void writeHeader() override;
/** /**
* @brief Write report footer. * @brief Write report footer.
*/ */
virtual void writeFooter() override; virtual void writeFooter() override;
/** /**
* @brief Write error to report. * @brief Write error to report.
* @param error Error data. * @param error Error data.
*/ */
virtual void writeError(const ErrorItem &error) override; virtual void writeError(const ErrorItem &error) override;
/** /**
* @brief Returns the formatted report. * @brief Returns the formatted report.
*/ */
QString getFormattedReportText() const; QString getFormattedReportText() const;
private: private:
/** /**
* @brief Stores the formatted report contents. * @brief Stores the formatted report contents.
*/ */
QString mFormattedReport; QString mFormattedReport;
}; };
/// @} /// @}

View File

@ -1070,7 +1070,7 @@ QStringList ProjectFile::fromNativeSeparators(const QStringList &paths)
{ {
QStringList ret; QStringList ret;
foreach (const QString &path, paths) foreach (const QString &path, paths)
ret << QDir::fromNativeSeparators(path); ret << QDir::fromNativeSeparators(path);
return ret; return ret;
} }
@ -1156,9 +1156,9 @@ QString ProjectFile::getAddonFilePath(QString filesDir, const QString &addon)
QStringList searchPaths; QStringList searchPaths;
searchPaths << filesDir << (filesDir + "addons/") << (filesDir + "../addons/") searchPaths << filesDir << (filesDir + "addons/") << (filesDir + "../addons/")
#ifdef FILESDIR #ifdef FILESDIR
<< (QLatin1String(FILESDIR) + "/addons/") << (QLatin1String(FILESDIR) + "/addons/")
#endif #endif
; ;
foreach (QString path, searchPaths) { foreach (QString path, searchPaths) {
QString f = path + addon + ".py"; QString f = path + addon + ".py";

View File

@ -36,10 +36,10 @@ class QXmlStreamWriter;
/** /**
* @brief A class that reads and writes project files. * @brief A class that reads and writes project files.
* The project files contain project-specific settings for checking. For * The project files contain project-specific settings for checking. For
* example a list of include paths. * example a list of include paths.
*/ */
class ProjectFile : public QObject { class ProjectFile : public QObject {
Q_OBJECT Q_OBJECT
@ -100,57 +100,57 @@ public:
} }
/** /**
* @brief Get list of include directories. * @brief Get list of include directories.
* @return list of directories. * @return list of directories.
*/ */
QStringList getIncludeDirs() const { QStringList getIncludeDirs() const {
return ProjectFile::fromNativeSeparators(mIncludeDirs); return ProjectFile::fromNativeSeparators(mIncludeDirs);
} }
/** /**
* @brief Get list of defines. * @brief Get list of defines.
* @return list of defines. * @return list of defines.
*/ */
QStringList getDefines() const { QStringList getDefines() const {
return mDefines; return mDefines;
} }
/** /**
* @brief Get list of undefines. * @brief Get list of undefines.
* @return list of undefines. * @return list of undefines.
*/ */
QStringList getUndefines() const { QStringList getUndefines() const {
return mUndefines; return mUndefines;
} }
/** /**
* @brief Get list of paths to check. * @brief Get list of paths to check.
* @return list of paths. * @return list of paths.
*/ */
QStringList getCheckPaths() const { QStringList getCheckPaths() const {
return ProjectFile::fromNativeSeparators(mPaths); return ProjectFile::fromNativeSeparators(mPaths);
} }
/** /**
* @brief Get list of paths to exclude from the check. * @brief Get list of paths to exclude from the check.
* @return list of paths. * @return list of paths.
*/ */
QStringList getExcludedPaths() const { QStringList getExcludedPaths() const {
return ProjectFile::fromNativeSeparators(mExcludedPaths); return ProjectFile::fromNativeSeparators(mExcludedPaths);
} }
/** /**
* @brief Get list of paths to exclude from the check. * @brief Get list of paths to exclude from the check.
* @return list of paths. * @return list of paths.
*/ */
QStringList getVsConfigurations() const { QStringList getVsConfigurations() const {
return mVsConfigurations; return mVsConfigurations;
} }
/** /**
* @brief Get list libraries. * @brief Get list libraries.
* @return list of libraries. * @return list of libraries.
*/ */
QStringList getLibraries() const { QStringList getLibraries() const {
return mLibraries; return mLibraries;
} }
@ -164,32 +164,32 @@ public:
} }
/** /**
* @brief Get "raw" suppressions. * @brief Get "raw" suppressions.
* @return list of suppressions. * @return list of suppressions.
*/ */
QList<Suppressions::Suppression> getSuppressions() const { QList<Suppressions::Suppression> getSuppressions() const {
return mSuppressions; return mSuppressions;
} }
/** /**
* @brief Get list addons. * @brief Get list addons.
* @return list of addons. * @return list of addons.
*/ */
QStringList getAddons() const { QStringList getAddons() const {
return mAddons; return mAddons;
} }
/** /**
* @brief Get path to addon python script * @brief Get path to addon python script
* @param filesDir Data files folder set by --data-dir * @param filesDir Data files folder set by --data-dir
* @param addon addon i.e. "misra" to lookup * @param addon addon i.e. "misra" to lookup
*/ */
static QString getAddonFilePath(QString filesDir, const QString &addon); static QString getAddonFilePath(QString filesDir, const QString &addon);
/** /**
* @brief Get list of addons and tools. * @brief Get list of addons and tools.
* @return list of addons and tools. * @return list of addons and tools.
*/ */
QStringList getAddonsAndTools() const; QStringList getAddonsAndTools() const;
bool getClangAnalyzer() const { bool getClangAnalyzer() const {
@ -249,17 +249,17 @@ public:
} }
/** /**
* @brief Get filename for the project file. * @brief Get filename for the project file.
* @return file name. * @return file name.
*/ */
QString getFilename() const { QString getFilename() const {
return mFilename; return mFilename;
} }
/** /**
* @brief Set project root path. * @brief Set project root path.
* @param rootpath new project root path. * @param rootpath new project root path.
*/ */
void setRootPath(const QString &rootpath) { void setRootPath(const QString &rootpath) {
mRootPath = rootpath; mRootPath = rootpath;
} }
@ -474,11 +474,11 @@ protected:
void readTagWarnings(QXmlStreamReader &reader, const QString &tag); void readTagWarnings(QXmlStreamReader &reader, const QString &tag);
/** /**
* @brief Read string list * @brief Read string list
* @param stringlist destination string list * @param stringlist destination string list
* @param reader XML stream reader * @param reader XML stream reader
* @param elementname elementname for each string * @param elementname elementname for each string
*/ */
void readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[]); void readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[]);
/** /**

View File

@ -309,19 +309,19 @@ void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
// Human knowledge.. // Human knowledge..
/* /*
mUI.mListUnknownFunctionReturn->clear(); mUI.mListUnknownFunctionReturn->clear();
mUI.mListUnknownFunctionReturn->addItem("rand()"); mUI.mListUnknownFunctionReturn->addItem("rand()");
for (int row = 0; row < mUI.mListUnknownFunctionReturn->count(); ++row) { for (int row = 0; row < mUI.mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI.mListUnknownFunctionReturn->item(row); QListWidgetItem *item = mUI.mListUnknownFunctionReturn->item(row);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
const bool unknownValues = projectFile->getCheckUnknownFunctionReturn().contains(item->text()); const bool unknownValues = projectFile->getCheckUnknownFunctionReturn().contains(item->text());
item->setCheckState(unknownValues ? Qt::Checked : Qt::Unchecked); // AND initialize check state item->setCheckState(unknownValues ? Qt::Checked : Qt::Unchecked); // AND initialize check state
} }
mUI.mCheckSafeClasses->setChecked(projectFile->getSafeChecks().classes); mUI.mCheckSafeClasses->setChecked(projectFile->getSafeChecks().classes);
mUI.mCheckSafeExternalFunctions->setChecked(projectFile->getSafeChecks().externalFunctions); mUI.mCheckSafeExternalFunctions->setChecked(projectFile->getSafeChecks().externalFunctions);
mUI.mCheckSafeInternalFunctions->setChecked(projectFile->getSafeChecks().internalFunctions); mUI.mCheckSafeInternalFunctions->setChecked(projectFile->getSafeChecks().internalFunctions);
mUI.mCheckSafeExternalVariables->setChecked(projectFile->getSafeChecks().externalVariables); mUI.mCheckSafeExternalVariables->setChecked(projectFile->getSafeChecks().externalVariables);
*/ */
// Addons.. // Addons..
QSettings settings; QSettings settings;
@ -383,20 +383,20 @@ void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
projectFile->setSuppressions(getSuppressions()); projectFile->setSuppressions(getSuppressions());
// Human knowledge // Human knowledge
/* /*
QStringList unknownReturnValues; QStringList unknownReturnValues;
for (int row = 0; row < mUI.mListUnknownFunctionReturn->count(); ++row) { for (int row = 0; row < mUI.mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI.mListUnknownFunctionReturn->item(row); QListWidgetItem *item = mUI.mListUnknownFunctionReturn->item(row);
if (item->checkState() == Qt::Checked) if (item->checkState() == Qt::Checked)
unknownReturnValues << item->text(); unknownReturnValues << item->text();
} }
projectFile->setCheckUnknownFunctionReturn(unknownReturnValues); projectFile->setCheckUnknownFunctionReturn(unknownReturnValues);
ProjectFile::SafeChecks safeChecks; ProjectFile::SafeChecks safeChecks;
safeChecks.classes = mUI.mCheckSafeClasses->isChecked(); safeChecks.classes = mUI.mCheckSafeClasses->isChecked();
safeChecks.externalFunctions = mUI.mCheckSafeExternalFunctions->isChecked(); safeChecks.externalFunctions = mUI.mCheckSafeExternalFunctions->isChecked();
safeChecks.internalFunctions = mUI.mCheckSafeInternalFunctions->isChecked(); safeChecks.internalFunctions = mUI.mCheckSafeInternalFunctions->isChecked();
safeChecks.externalVariables = mUI.mCheckSafeExternalVariables->isChecked(); safeChecks.externalVariables = mUI.mCheckSafeExternalVariables->isChecked();
projectFile->setSafeChecks(safeChecks); projectFile->setSafeChecks(safeChecks);
*/ */
// Addons // Addons
QStringList list; QStringList list;
if (mUI.mAddonThreadSafety->isChecked()) if (mUI.mAddonThreadSafety->isChecked())
@ -425,8 +425,8 @@ QString ProjectFileDialog::getExistingDirectory(const QString &caption, bool tra
const QFileInfo inf(mProjectFile->getFilename()); const QFileInfo inf(mProjectFile->getFilename());
const QString rootpath = inf.absolutePath(); const QString rootpath = inf.absolutePath();
QString selectedDir = QFileDialog::getExistingDirectory(this, QString selectedDir = QFileDialog::getExistingDirectory(this,
caption, caption,
rootpath); rootpath);
if (selectedDir.isEmpty()) if (selectedDir.isEmpty())
return QString(); return QString();
@ -491,8 +491,8 @@ void ProjectFileDialog::browseImportProject()
filters[tr("Compile database")] = "compile_commands.json"; filters[tr("Compile database")] = "compile_commands.json";
filters[tr("Borland C++ Builder 6")] = "*.bpr"; filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString fileName = QFileDialog::getOpenFileName(this, tr("Import Project"), QString fileName = QFileDialog::getOpenFileName(this, tr("Import Project"),
dir.canonicalPath(), dir.canonicalPath(),
toFilterString(filters)); toFilterString(filters));
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
mUI.mEditImportProject->setText(dir.relativeFilePath(fileName)); mUI.mEditImportProject->setText(dir.relativeFilePath(fileName));
updatePathsAndDefines(); updatePathsAndDefines();
@ -681,9 +681,9 @@ void ProjectFileDialog::addSingleSuppression(const Suppressions::Suppression &su
(suppression.fileName.find(sep) == std::string::npos)) { (suppression.fileName.find(sep) == std::string::npos)) {
QFileInfo inf(mProjectFile->getFilename()); QFileInfo inf(mProjectFile->getFilename());
QString rootpath = inf.absolutePath(); QString rootpath = inf.absolutePath();
if (QFile::exists(QString{"%1%2%3"} .arg(rootpath, if (QFile::exists(QString{"%1%2%3"}.arg(rootpath,
QDir::separator(), QDir::separator(),
QString::fromStdString(suppression.fileName)))) { QString::fromStdString(suppression.fileName)))) {
Suppressions::Suppression sup = suppression; Suppressions::Suppression sup = suppression;
sup.fileName = rootpath.toLatin1().constData(); sup.fileName = rootpath.toLatin1().constData();
sup.fileName += sep; sup.fileName += sep;
@ -849,9 +849,9 @@ int ProjectFileDialog::getSuppressionIndex(const QString &shortText) const
void ProjectFileDialog::browseMisraFile() void ProjectFileDialog::browseMisraFile()
{ {
const QString fileName = QFileDialog::getOpenFileName(this, const QString fileName = QFileDialog::getOpenFileName(this,
tr("Select MISRA rule texts file"), tr("Select MISRA rule texts file"),
QDir::homePath(), QDir::homePath(),
tr("MISRA rule texts file (%1)").arg("*.txt")); tr("MISRA rule texts file (%1)").arg("*.txt"));
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
QSettings settings; QSettings settings;
mUI.mEditMisraFile->setText(fileName); mUI.mEditMisraFile->setText(fileName);

View File

@ -37,8 +37,8 @@ class QCheckBox;
class ProjectFile; class ProjectFile;
/** /**
* @brief A dialog for editing project file data. * @brief A dialog for editing project file data.
*/ */
class ProjectFileDialog : public QDialog { class ProjectFileDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
@ -53,9 +53,9 @@ private:
void updatePathsAndDefines(); void updatePathsAndDefines();
/** /**
* @brief Return project root path from the dialog control. * @brief Return project root path from the dialog control.
* @return Project root path. * @return Project root path.
*/ */
QString getRootPath() const; QString getRootPath() const;
QStringList getProjectConfigurations() const; QStringList getProjectConfigurations() const;
@ -67,53 +67,53 @@ private:
QString getBuildDir() const; QString getBuildDir() const;
/** /**
* @brief Return include paths from the dialog control. * @brief Return include paths from the dialog control.
* @return List of include paths. * @return List of include paths.
*/ */
QStringList getIncludePaths() const; QStringList getIncludePaths() const;
/** /**
* @brief Return define names from the dialog control. * @brief Return define names from the dialog control.
* @return List of define names. * @return List of define names.
*/ */
QStringList getDefines() const; QStringList getDefines() const;
/** /**
* @brief Return undefine names from the dialog control. * @brief Return undefine names from the dialog control.
* @return List of undefine names. * @return List of undefine names.
*/ */
QStringList getUndefines() const; QStringList getUndefines() const;
/** /**
* @brief Return check paths from the dialog control. * @brief Return check paths from the dialog control.
* @return List of check paths. * @return List of check paths.
*/ */
QStringList getCheckPaths() const; QStringList getCheckPaths() const;
/** /**
* @brief Return excluded paths from the dialog control. * @brief Return excluded paths from the dialog control.
* @return List of excluded paths. * @return List of excluded paths.
*/ */
QStringList getExcludedPaths() const; QStringList getExcludedPaths() const;
/** /**
* @brief Return selected libraries from the dialog control. * @brief Return selected libraries from the dialog control.
* @return List of libraries. * @return List of libraries.
*/ */
QStringList getLibraries() const; QStringList getLibraries() const;
/** /**
* @brief Return suppressions from the dialog control. * @brief Return suppressions from the dialog control.
* @return List of suppressions. * @return List of suppressions.
*/ */
QList<Suppressions::Suppression> getSuppressions() const { QList<Suppressions::Suppression> getSuppressions() const {
return mSuppressions; return mSuppressions;
} }
/** /**
* @brief Set project root path to dialog control. * @brief Set project root path to dialog control.
* @param root Project root path to set to dialog control. * @param root Project root path to set to dialog control.
*/ */
void setRootPath(const QString &root); void setRootPath(const QString &root);
/** Set build dir */ /** Set build dir */
@ -122,51 +122,51 @@ private:
void setImportProject(const QString &importProject); void setImportProject(const QString &importProject);
/** /**
* @brief Set include paths to dialog control. * @brief Set include paths to dialog control.
* @param includes List of include paths to set to dialog control. * @param includes List of include paths to set to dialog control.
*/ */
void setIncludepaths(const QStringList &includes); void setIncludepaths(const QStringList &includes);
/** /**
* @brief Set define names to dialog control. * @brief Set define names to dialog control.
* @param defines List of define names to set to dialog control. * @param defines List of define names to set to dialog control.
*/ */
void setDefines(const QStringList &defines); void setDefines(const QStringList &defines);
/** /**
* @brief Set undefine names to dialog control. * @brief Set undefine names to dialog control.
* @param undefines List of undefine names to set to dialog control. * @param undefines List of undefine names to set to dialog control.
*/ */
void setUndefines(const QStringList &undefines); void setUndefines(const QStringList &undefines);
/** /**
* @brief Set check paths to dialog control. * @brief Set check paths to dialog control.
* @param paths List of path names to set to dialog control. * @param paths List of path names to set to dialog control.
*/ */
void setCheckPaths(const QStringList &paths); void setCheckPaths(const QStringList &paths);
/** /**
* @brief Set excluded paths to dialog control. * @brief Set excluded paths to dialog control.
* @param paths List of path names to set to dialog control. * @param paths List of path names to set to dialog control.
*/ */
void setExcludedPaths(const QStringList &paths); void setExcludedPaths(const QStringList &paths);
/** /**
* @brief Set libraries to dialog control. * @brief Set libraries to dialog control.
* @param libraries List of libraries to set to dialog control. * @param libraries List of libraries to set to dialog control.
*/ */
void setLibraries(const QStringList &libraries); void setLibraries(const QStringList &libraries);
/** /**
* @brief Add a single suppression to dialog control. * @brief Add a single suppression to dialog control.
* @param suppression A suppressions to add to dialog control. * @param suppression A suppressions to add to dialog control.
*/ */
void addSingleSuppression(const Suppressions::Suppression &suppression); void addSingleSuppression(const Suppressions::Suppression &suppression);
/** /**
* @brief Set suppressions to dialog control. * @brief Set suppressions to dialog control.
* @param suppressions List of suppressions to set to dialog control. * @param suppressions List of suppressions to set to dialog control.
*/ */
void setSuppressions(const QList<Suppressions::Suppression> &suppressions); void setSuppressions(const QList<Suppressions::Suppression> &suppressions);
protected slots: protected slots:
@ -175,89 +175,89 @@ protected slots:
void ok(); void ok();
/** /**
* @brief Browse for build dir. * @brief Browse for build dir.
*/ */
void browseBuildDir(); void browseBuildDir();
/** /**
* @brief Clear 'import project'. * @brief Clear 'import project'.
*/ */
void clearImportProject(); void clearImportProject();
/** /**
* @brief Browse for solution / project / compile database. * @brief Browse for solution / project / compile database.
*/ */
void browseImportProject(); void browseImportProject();
/** /**
* @brief Add new path to check. * @brief Add new path to check.
*/ */
void addCheckPath(); void addCheckPath();
/** /**
* @brief Edit path in the list. * @brief Edit path in the list.
*/ */
void editCheckPath(); void editCheckPath();
/** /**
* @brief Remove path from the list. * @brief Remove path from the list.
*/ */
void removeCheckPath(); void removeCheckPath();
/** /**
* @brief Browse for include directory. * @brief Browse for include directory.
* Allow user to add new include directory to the list. * Allow user to add new include directory to the list.
*/ */
void addIncludeDir(); void addIncludeDir();
/** /**
* @brief Remove include directory from the list. * @brief Remove include directory from the list.
*/ */
void removeIncludeDir(); void removeIncludeDir();
/** /**
* @brief Edit include directory in the list. * @brief Edit include directory in the list.
*/ */
void editIncludeDir(); void editIncludeDir();
/** /**
* @brief Add new path to exclude list. * @brief Add new path to exclude list.
*/ */
void addExcludePath(); void addExcludePath();
/** /**
* @brief Add new file to exclude list. * @brief Add new file to exclude list.
*/ */
void addExcludeFile(); void addExcludeFile();
/** /**
* @brief Edit excluded path in the list. * @brief Edit excluded path in the list.
*/ */
void editExcludePath(); void editExcludePath();
/** /**
* @brief Remove excluded path from the list. * @brief Remove excluded path from the list.
*/ */
void removeExcludePath(); void removeExcludePath();
/** /**
* @brief Move include path up in the list. * @brief Move include path up in the list.
*/ */
void moveIncludePathUp(); void moveIncludePathUp();
/** /**
* @brief Move include path down in the list. * @brief Move include path down in the list.
*/ */
void moveIncludePathDown(); void moveIncludePathDown();
/** /**
* @brief Add suppression to the list * @brief Add suppression to the list
*/ */
void addSuppression(); void addSuppression();
/** /**
* @brief Remove selected suppression from the list * @brief Remove selected suppression from the list
*/ */
void removeSuppression(); void removeSuppression();
/** /**
@ -288,21 +288,21 @@ protected:
void saveSettings() const; void saveSettings() const;
/** /**
* @brief Add new indlude directory. * @brief Add new indlude directory.
* @param dir Directory to add. * @param dir Directory to add.
*/ */
void addIncludeDir(const QString &dir); void addIncludeDir(const QString &dir);
/** /**
* @brief Add new path to check. * @brief Add new path to check.
* @param path Path to add. * @param path Path to add.
*/ */
void addCheckPath(const QString &path); void addCheckPath(const QString &path);
/** /**
* @brief Add new path to ignore list. * @brief Add new path to ignore list.
* @param path Path to add. * @param path Path to add.
*/ */
void addExcludePath(const QString &path); void addExcludePath(const QString &path);
/** /**

View File

@ -21,8 +21,7 @@
Report::Report(const QString &filename) : Report::Report(const QString &filename) :
QObject(), QObject(),
mFilename(filename) mFilename(filename)
{ {}
}
Report::~Report() Report::~Report()
{ {

View File

@ -29,8 +29,8 @@ class ErrorItem;
/// @{ /// @{
/** /**
* @brief A base class for reports. * @brief A base class for reports.
*/ */
class Report : public QObject { class Report : public QObject {
public: public:
enum Type { enum Type {
@ -43,55 +43,55 @@ public:
virtual ~Report(); virtual ~Report();
/** /**
* @brief Create the report (file). * @brief Create the report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool create(); virtual bool create();
/** /**
* @brief Open the existing report (file). * @brief Open the existing report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool open(); virtual bool open();
/** /**
* @brief Close the report (file). * @brief Close the report (file).
*/ */
void close(); void close();
/** /**
* @brief Write report header. * @brief Write report header.
*/ */
virtual void writeHeader() = 0; virtual void writeHeader() = 0;
/** /**
* @brief Write report footer. * @brief Write report footer.
*/ */
virtual void writeFooter() = 0; virtual void writeFooter() = 0;
/** /**
* @brief Write error to report. * @brief Write error to report.
* @param error Error data. * @param error Error data.
*/ */
virtual void writeError(const ErrorItem &error) = 0; virtual void writeError(const ErrorItem &error) = 0;
protected: protected:
/** /**
* @brief Get the file object where the report is written to. * @brief Get the file object where the report is written to.
*/ */
QFile* getFile(); QFile* getFile();
private: private:
/** /**
* @brief Filename of the report. * @brief Filename of the report.
*/ */
QString mFilename; QString mFilename;
/** /**
* @brief Fileobject for the report file. * @brief Fileobject for the report file.
*/ */
QFile mFile; QFile mFile;
}; };
/// @} /// @}

View File

@ -98,8 +98,7 @@ ResultsTree::ResultsTree(QWidget * parent) :
} }
ResultsTree::~ResultsTree() ResultsTree::~ResultsTree()
{ {}
}
void ResultsTree::keyPressEvent(QKeyEvent *event) void ResultsTree::keyPressEvent(QKeyEvent *event)
{ {
@ -198,10 +197,10 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
//file item as a parent //file item as a parent
QStandardItem* fileItem = ensureFileItem(loc.file, item.file0, hide); QStandardItem* fileItem = ensureFileItem(loc.file, item.file0, hide);
QStandardItem* stditem = addBacktraceFiles(fileItem, QStandardItem* stditem = addBacktraceFiles(fileItem,
line, line,
hide, hide,
severityToIcon(line.severity), severityToIcon(line.severity),
false); false);
if (!stditem) if (!stditem)
return false; return false;
@ -269,10 +268,10 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
} }
QStandardItem *ResultsTree::addBacktraceFiles(QStandardItem *parent, QStandardItem *ResultsTree::addBacktraceFiles(QStandardItem *parent,
const ErrorLine &item, const ErrorLine &item,
const bool hide, const bool hide,
const QString &icon, const QString &icon,
bool childOfMessage) bool childOfMessage)
{ {
if (!parent) { if (!parent) {
return nullptr; return nullptr;
@ -864,8 +863,8 @@ QString ResultsTree::askFileDir(const QString &file)
msgbox.exec(); msgbox.exec();
QString dir = QFileDialog::getExistingDirectory(this, title, QString dir = QFileDialog::getExistingDirectory(this, title,
getPath(SETTINGS_LAST_SOURCE_PATH), getPath(SETTINGS_LAST_SOURCE_PATH),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir.isEmpty()) if (dir.isEmpty())
return QString(); return QString();

View File

@ -41,9 +41,9 @@ class QSettings;
/** /**
* @brief Cppcheck's results are shown in this tree * @brief Cppcheck's results are shown in this tree
* *
*/ */
class ResultsTree : public QTreeView { class ResultsTree : public QTreeView {
Q_OBJECT Q_OBJECT
public: public:
@ -52,16 +52,16 @@ public:
void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler); void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler);
/** /**
* @brief Add a new item to the tree * @brief Add a new item to the tree
* *
* @param item Error item data * @param item Error item data
*/ */
bool addErrorItem(const ErrorItem &item); bool addErrorItem(const ErrorItem &item);
/** /**
* @brief Clear all errors from the tree * @brief Clear all errors from the tree
* *
*/ */
void clear(); void clear();
/** /**
@ -75,28 +75,28 @@ public:
void clearRecheckFile(const QString &filename); void clearRecheckFile(const QString &filename);
/** /**
* @brief Function to filter the displayed list of errors. * @brief Function to filter the displayed list of errors.
* Refreshes the tree. * Refreshes the tree.
* *
* @param filter String that must be found in the summary, description, file or id * @param filter String that must be found in the summary, description, file or id
*/ */
void filterResults(const QString& filter); void filterResults(const QString& filter);
/** /**
* @brief Function to show results that were previous hidden with HideResult() * @brief Function to show results that were previous hidden with HideResult()
*/ */
void showHiddenResults(); void showHiddenResults();
/** /**
* @brief Refresh tree by checking which of the items should be shown * @brief Refresh tree by checking which of the items should be shown
* and which should be hidden * and which should be hidden
*/ */
void refreshTree(); void refreshTree();
/** /**
* @brief Save results to a text stream * @brief Save results to a text stream
* *
*/ */
void saveResults(Report *report) const; void saveResults(Report *report) const;
/** /**
@ -105,69 +105,69 @@ public:
void updateFromOldReport(const QString &filename); void updateFromOldReport(const QString &filename);
/** /**
* @brief Update tree settings * @brief Update tree settings
* *
* @param showFullPath Show full path of files in the tree * @param showFullPath Show full path of files in the tree
* @param saveFullPath Save full path of files in reports * @param saveFullPath Save full path of files in reports
* @param saveAllErrors Save all visible errors * @param saveAllErrors Save all visible errors
* @param showErrorId Show error id * @param showErrorId Show error id
* @param showInconclusive Show inconclusive column * @param showInconclusive Show inconclusive column
*/ */
void updateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors, bool showErrorId, bool showInconclusive); void updateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors, bool showErrorId, bool showInconclusive);
/** /**
* @brief Set the directory we are checking * @brief Set the directory we are checking
* *
* This is used to split error file path to relative if necessary * This is used to split error file path to relative if necessary
* @param dir Directory we are checking * @param dir Directory we are checking
*/ */
void setCheckDirectory(const QString &dir); void setCheckDirectory(const QString &dir);
/** /**
* @brief Get the directory we are checking * @brief Get the directory we are checking
* *
* @return Directory containing source files * @return Directory containing source files
*/ */
QString getCheckDirectory(); QString getCheckDirectory();
/** /**
* @brief Check if there are any visible results in view. * @brief Check if there are any visible results in view.
* @return true if there is at least one visible warning/error. * @return true if there is at least one visible warning/error.
*/ */
bool hasVisibleResults() const; bool hasVisibleResults() const;
/** /**
* @brief Do we have results from check? * @brief Do we have results from check?
* @return true if there is at least one warning/error, hidden or visible. * @return true if there is at least one warning/error, hidden or visible.
*/ */
bool hasResults() const; bool hasResults() const;
/** /**
* @brief Save all settings * @brief Save all settings
* Column widths * Column widths
*/ */
void saveSettings() const; void saveSettings() const;
/** /**
* @brief Change all visible texts language * @brief Change all visible texts language
* *
*/ */
void translate(); void translate();
/** /**
* @brief Show optional column "Id" * @brief Show optional column "Id"
*/ */
void showIdColumn(bool show); void showIdColumn(bool show);
/** /**
* @brief Show optional column "Inconclusve" * @brief Show optional column "Inconclusve"
*/ */
void showInconclusiveColumn(bool show); void showInconclusiveColumn(bool show);
/** /**
* @brief Returns true if column "Id" is shown * @brief Returns true if column "Id" is shown
*/ */
bool showIdColumn() const { bool showIdColumn() const {
return mShowErrorId; return mShowErrorId;
} }
@ -181,24 +181,24 @@ public:
signals: signals:
/** /**
* @brief Signal that results have been hidden or shown * @brief Signal that results have been hidden or shown
* *
* @param hidden true if there are some hidden results, or false if there are not * @param hidden true if there are some hidden results, or false if there are not
*/ */
void resultsHidden(bool hidden); void resultsHidden(bool hidden);
/** /**
* @brief Signal to perform selected files recheck * @brief Signal to perform selected files recheck
* *
* @param selectedItems list of selected files * @param selectedItems list of selected files
*/ */
void checkSelected(QStringList selectedItems); void checkSelected(QStringList selectedItems);
/** /**
* @brief Signal for selection change in result tree. * @brief Signal for selection change in result tree.
* *
* @param current Model index to specify new selected item. * @param current Model index to specify new selected item.
*/ */
void treeSelectionChanged(const QModelIndex &current); void treeSelectionChanged(const QModelIndex &current);
/** Suppress Ids */ /** Suppress Ids */
@ -209,67 +209,67 @@ signals:
public slots: public slots:
/** /**
* @brief Function to show/hide certain type of errors * @brief Function to show/hide certain type of errors
* Refreshes the tree. * Refreshes the tree.
* *
* @param type Type of error to show/hide * @param type Type of error to show/hide
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showResults(ShowTypes::ShowType type, bool show); void showResults(ShowTypes::ShowType type, bool show);
/** /**
* @brief Show/hide cppcheck errors. * @brief Show/hide cppcheck errors.
* Refreshes the tree. * Refreshes the tree.
* *
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showCppcheckResults(bool show); void showCppcheckResults(bool show);
/** /**
* @brief Show/hide clang-tidy/clang-analyzer errors. * @brief Show/hide clang-tidy/clang-analyzer errors.
* Refreshes the tree. * Refreshes the tree.
* *
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showClangResults(bool show); void showClangResults(bool show);
protected slots: protected slots:
/** /**
* @brief Slot to quickstart an error with default application * @brief Slot to quickstart an error with default application
* *
* @param index Model index to specify which error item to open * @param index Model index to specify which error item to open
*/ */
void quickStartApplication(const QModelIndex &index); void quickStartApplication(const QModelIndex &index);
/** /**
* @brief Slot for context menu item to open an error with specified application * @brief Slot for context menu item to open an error with specified application
* *
* @param application Index of the application to open the error * @param application Index of the application to open the error
*/ */
void context(int application); void context(int application);
/** /**
* @brief Slot for context menu item to copy selection to clipboard * @brief Slot for context menu item to copy selection to clipboard
*/ */
void copy(); void copy();
/** /**
* @brief Slot for context menu item to hide the current error message * @brief Slot for context menu item to hide the current error message
* *
*/ */
void hideResult(); void hideResult();
/** /**
* @brief Slot for rechecking selected files * @brief Slot for rechecking selected files
* *
*/ */
void recheckSelectedFiles(); void recheckSelectedFiles();
/** /**
* @brief Slot for context menu item to hide all messages with the current message Id * @brief Slot for context menu item to hide all messages with the current message Id
* *
*/ */
void hideAllIdResult(); void hideAllIdResult();
/** Slot for context menu item to suppress all messages with the current message id */ /** Slot for context menu item to suppress all messages with the current message id */
@ -279,8 +279,8 @@ protected slots:
void suppressHash(); void suppressHash();
/** /**
* @brief Slot for context menu item to open the folder containing the current file. * @brief Slot for context menu item to open the folder containing the current file.
*/ */
void openContainingFolder(); void openContainingFolder();
/** /**
@ -289,94 +289,94 @@ protected slots:
void editContract(); void editContract();
/** /**
* @brief Slot for selection change in the results tree. * @brief Slot for selection change in the results tree.
* *
* @param current Model index to specify new selected item. * @param current Model index to specify new selected item.
* @param previous Model index to specify previous selected item. * @param previous Model index to specify previous selected item.
*/ */
virtual void currentChanged(const QModelIndex &current, const QModelIndex &previous); virtual void currentChanged(const QModelIndex &current, const QModelIndex &previous);
protected: protected:
/** /**
* @brief Hides/shows full file path on all error file items according to mShowFullPath * @brief Hides/shows full file path on all error file items according to mShowFullPath
* *
*/ */
void refreshFilePaths(); void refreshFilePaths();
/** /**
* @brief Hides/shows full file path on all error file items according to mShowFullPath * @brief Hides/shows full file path on all error file items according to mShowFullPath
* @param item Parent item whose children's paths to change * @param item Parent item whose children's paths to change
*/ */
void refreshFilePaths(QStandardItem *item); void refreshFilePaths(QStandardItem *item);
/** /**
* @brief Removes checking directory from given path if mShowFullPath is false * @brief Removes checking directory from given path if mShowFullPath is false
* *
* @param path Path to remove checking directory * @param path Path to remove checking directory
* @param saving are we saving? Check mSaveFullPath instead * @param saving are we saving? Check mSaveFullPath instead
* @return Path that has checking directory removed * @return Path that has checking directory removed
*/ */
QString stripPath(const QString &path, bool saving) const; QString stripPath(const QString &path, bool saving) const;
/** /**
* @brief Save all errors under specified item * @brief Save all errors under specified item
* @param report Report that errors are saved to * @param report Report that errors are saved to
* @param fileItem Item whose errors to save * @param fileItem Item whose errors to save
*/ */
void saveErrors(Report *report, const QStandardItem *fileItem) const; void saveErrors(Report *report, const QStandardItem *fileItem) const;
/** /**
* @brief Convert a severity string to a icon filename * @brief Convert a severity string to a icon filename
* *
* @param severity Severity * @param severity Severity
*/ */
QString severityToIcon(Severity::SeverityType severity) const; QString severityToIcon(Severity::SeverityType severity) const;
/** /**
* @brief Helper function to open an error within target with application* * @brief Helper function to open an error within target with application*
* *
* @param target Error tree item to open * @param target Error tree item to open
* @param application Index of the application to open with. Giving -1 * @param application Index of the application to open with. Giving -1
* (default value) will open the default application. * (default value) will open the default application.
*/ */
void startApplication(QStandardItem *target, int application = -1); void startApplication(QStandardItem *target, int application = -1);
/** /**
* @brief Helper function to copy filename/full path to the clipboard * @brief Helper function to copy filename/full path to the clipboard
* *
* @param target Error tree item to open * @param target Error tree item to open
* @param fullPath Are we copying full path or only filename? * @param fullPath Are we copying full path or only filename?
*/ */
void copyPathToClipboard(QStandardItem *target, bool fullPath); void copyPathToClipboard(QStandardItem *target, bool fullPath);
/** /**
* @brief Helper function returning the filename/full path of the error tree item \a target. * @brief Helper function returning the filename/full path of the error tree item \a target.
* *
* @param target The error tree item containing the filename/full path * @param target The error tree item containing the filename/full path
* @param fullPath Whether or not to retrieve the full path or only the filename. * @param fullPath Whether or not to retrieve the full path or only the filename.
*/ */
QString getFilePath(QStandardItem *target, bool fullPath); QString getFilePath(QStandardItem *target, bool fullPath);
/** /**
* @brief Context menu event (user right clicked on the tree) * @brief Context menu event (user right clicked on the tree)
* *
* @param e Event * @param e Event
*/ */
void contextMenuEvent(QContextMenuEvent * e); void contextMenuEvent(QContextMenuEvent * e);
/** /**
* @brief Add a new error item beneath a file or a backtrace item beneath an error * @brief Add a new error item beneath a file or a backtrace item beneath an error
* *
* @param parent Parent for the item. Either a file item or an error item * @param parent Parent for the item. Either a file item or an error item
* @param item Error line data * @param item Error line data
* @param hide Should this be hidden (true) or shown (false) * @param hide Should this be hidden (true) or shown (false)
* @param icon Should a default backtrace item icon be added * @param icon Should a default backtrace item icon be added
* @param childOfMessage Is this a child element of a message? * @param childOfMessage Is this a child element of a message?
* @return newly created QStandardItem * * @return newly created QStandardItem *
*/ */
QStandardItem *addBacktraceFiles(QStandardItem *parent, QStandardItem *addBacktraceFiles(QStandardItem *parent,
const ErrorLine &item, const ErrorLine &item,
const bool hide, const bool hide,
@ -384,135 +384,135 @@ protected:
bool childOfMessage); bool childOfMessage);
/** /**
* @brief Convert Severity to translated string for GUI. * @brief Convert Severity to translated string for GUI.
* @param severity Severity to convert * @param severity Severity to convert
* @return Severity as translated string * @return Severity as translated string
*/ */
static QString severityToTranslatedString(Severity::SeverityType severity); static QString severityToTranslatedString(Severity::SeverityType severity);
/** /**
* @brief Load all settings * @brief Load all settings
* Column widths * Column widths
*/ */
void loadSettings(); void loadSettings();
/** /**
* @brief Ask directory where file is located. * @brief Ask directory where file is located.
* @param file File name. * @param file File name.
* @return Directory user chose. * @return Directory user chose.
*/ */
QString askFileDir(const QString &file); QString askFileDir(const QString &file);
/** /**
* @brief Create new normal item. * @brief Create new normal item.
* *
* Normal item has left alignment and text set also as tooltip. * Normal item has left alignment and text set also as tooltip.
* @param name name for the item * @param name name for the item
* @return new QStandardItem * @return new QStandardItem
*/ */
static QStandardItem *createNormalItem(const QString &name); static QStandardItem *createNormalItem(const QString &name);
/** /**
* @brief Create new normal item. * @brief Create new normal item.
* *
* Normal item has left alignment and text set also as tooltip. * Normal item has left alignment and text set also as tooltip.
* @param checked checked * @param checked checked
* @return new QStandardItem * @return new QStandardItem
*/ */
static QStandardItem *createCheckboxItem(bool checked); static QStandardItem *createCheckboxItem(bool checked);
/** /**
* @brief Create new line number item. * @brief Create new line number item.
* *
* Line number item has right align and text set as tooltip. * Line number item has right align and text set as tooltip.
* @param linenumber name for the item * @param linenumber name for the item
* @return new QStandardItem * @return new QStandardItem
*/ */
static QStandardItem *createLineNumberItem(const QString &linenumber); static QStandardItem *createLineNumberItem(const QString &linenumber);
/** /**
* @brief Finds a file item * @brief Finds a file item
* *
* @param name name of the file item to find * @param name name of the file item to find
* @return pointer to file item or null if none found * @return pointer to file item or null if none found
*/ */
QStandardItem *findFileItem(const QString &name) const; QStandardItem *findFileItem(const QString &name) const;
/** /**
* @brief Ensures there's a item in the model for the specified file * @brief Ensures there's a item in the model for the specified file
* *
* @param fullpath Full path to the file item. * @param fullpath Full path to the file item.
* @param file0 Source file * @param file0 Source file
* @param hide is the error (we want this file item for) hidden? * @param hide is the error (we want this file item for) hidden?
* @return QStandardItem to be used as a parent for all errors for specified file * @return QStandardItem to be used as a parent for all errors for specified file
*/ */
QStandardItem *ensureFileItem(const QString &fullpath, const QString &file0, bool hide); QStandardItem *ensureFileItem(const QString &fullpath, const QString &file0, bool hide);
/** /**
* @brief Item model for tree * @brief Item model for tree
* *
*/ */
QStandardItemModel mModel; QStandardItemModel mModel;
/** /**
* @brief Program settings * @brief Program settings
* *
*/ */
QSettings *mSettings; QSettings *mSettings;
/** /**
* @brief A string used to filter the results for display. * @brief A string used to filter the results for display.
* *
*/ */
QString mFilter; QString mFilter;
/** /**
* @brief List of applications to open errors with * @brief List of applications to open errors with
* *
*/ */
ApplicationList *mApplications; ApplicationList *mApplications;
/** /**
* @brief Right clicked item (used by context menu slots) * @brief Right clicked item (used by context menu slots)
* *
*/ */
QStandardItem *mContextItem; QStandardItem *mContextItem;
/** /**
* @brief Should full path of files be shown (true) or relative (false) * @brief Should full path of files be shown (true) or relative (false)
* *
*/ */
bool mShowFullPath; bool mShowFullPath;
/** /**
* @brief Should full path of files be saved * @brief Should full path of files be saved
* *
*/ */
bool mSaveFullPath; bool mSaveFullPath;
/** /**
* @brief Save all errors (true) or only visible (false) * @brief Save all errors (true) or only visible (false)
* *
*/ */
bool mSaveAllErrors; bool mSaveAllErrors;
/** /**
* @brief true if optional column "Id" is shown * @brief true if optional column "Id" is shown
* *
*/ */
bool mShowErrorId; bool mShowErrorId;
/** /**
* @brief Path we are currently checking * @brief Path we are currently checking
* *
*/ */
QString mCheckPath; QString mCheckPath;
/** /**
* @brief Are there any visible errors * @brief Are there any visible errors
* *
*/ */
bool mVisibleErrors; bool mVisibleErrors;
private: private:

View File

@ -328,7 +328,7 @@ void ResultsView::checkingFinished()
msg.exec(); msg.exec();
} //If we have errors but they aren't visible, tell user about it } //If we have errors but they aren't visible, tell user about it
else if (!mUI.mTree->hasVisibleResults()) { else if (!mUI.mTree->hasVisibleResults()) {
QString text = tr("Errors were found, but they are configured to be hidden.\n"\ QString text = tr("Errors were found, but they are configured to be hidden.\n" \
"To toggle what kind of errors are shown, open view menu."); "To toggle what kind of errors are shown, open view menu.");
QMessageBox msg(QMessageBox::Information, QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"), tr("Cppcheck"),

View File

@ -36,9 +36,9 @@ class CheckStatistics;
/// @{ /// @{
/** /**
* @brief Widget to show cppcheck progressbar and result * @brief Widget to show cppcheck progressbar and result
* *
*/ */
class ResultsView : public QWidget { class ResultsView : public QWidget {
Q_OBJECT Q_OBJECT
public: public:
@ -72,18 +72,18 @@ public:
void clearContracts(); void clearContracts();
/** /**
* @brief Write statistics in file * @brief Write statistics in file
* *
* @param filename Filename to save statistics to * @param filename Filename to save statistics to
*/ */
void saveStatistics(const QString &filename) const; void saveStatistics(const QString &filename) const;
/** /**
* @brief Save results to a file * @brief Save results to a file
* *
* @param filename Filename to save results to * @param filename Filename to save results to
* @param type Type of the report. * @param type Type of the report.
*/ */
void save(const QString &filename, Report::Type type) const; void save(const QString &filename, Report::Type type) const;
/** /**
@ -92,15 +92,15 @@ public:
void updateFromOldReport(const QString &filename) const; void updateFromOldReport(const QString &filename) const;
/** /**
* @brief Update tree settings * @brief Update tree settings
* *
* @param showFullPath Show full path of files in the tree * @param showFullPath Show full path of files in the tree
* @param saveFullPath Save full path of files in reports * @param saveFullPath Save full path of files in reports
* @param saveAllErrors Save all visible errors * @param saveAllErrors Save all visible errors
* @param showNoErrorsMessage Show "no errors"? * @param showNoErrorsMessage Show "no errors"?
* @param showErrorId Show error id? * @param showErrorId Show error id?
* @param showInconclusive Show inconclusive? * @param showInconclusive Show inconclusive?
*/ */
void updateSettings(bool showFullPath, void updateSettings(bool showFullPath,
bool saveFullPath, bool saveFullPath,
bool saveAllErrors, bool saveAllErrors,
@ -119,68 +119,68 @@ public:
void updateStyleSetting(QSettings *settings); void updateStyleSetting(QSettings *settings);
/** /**
* @brief Set the directory we are checking * @brief Set the directory we are checking
* *
* This is used to split error file path to relative if necessary * This is used to split error file path to relative if necessary
* @param dir Directory we are checking * @param dir Directory we are checking
*/ */
void setCheckDirectory(const QString &dir); void setCheckDirectory(const QString &dir);
/** /**
* @brief Get the directory we are checking * @brief Get the directory we are checking
* *
* @return Directory containing source files * @return Directory containing source files
*/ */
QString getCheckDirectory(); QString getCheckDirectory();
/** /**
* @brief Inform the view that checking has started * @brief Inform the view that checking has started
* *
* @param count Count of files to be checked. * @param count Count of files to be checked.
*/ */
void checkingStarted(int count); void checkingStarted(int count);
/** /**
* @brief Inform the view that checking finished. * @brief Inform the view that checking finished.
* *
*/ */
void checkingFinished(); void checkingFinished();
/** /**
* @brief Do we have visible results to show? * @brief Do we have visible results to show?
* *
* @return true if there is at least one warning/error to show. * @return true if there is at least one warning/error to show.
*/ */
bool hasVisibleResults() const; bool hasVisibleResults() const;
/** /**
* @brief Do we have results from check? * @brief Do we have results from check?
* *
* @return true if there is at least one warning/error, hidden or visible. * @return true if there is at least one warning/error, hidden or visible.
*/ */
bool hasResults() const; bool hasResults() const;
/** /**
* @brief Save View's settings * @brief Save View's settings
* *
* @param settings program settings. * @param settings program settings.
*/ */
void saveSettings(QSettings *settings); void saveSettings(QSettings *settings);
/** /**
* @brief Translate this view * @brief Translate this view
* *
*/ */
void translate(); void translate();
void disableProgressbar(); void disableProgressbar();
/** /**
* @brief Read errors from report XML file. * @brief Read errors from report XML file.
* @param filename Report file to read. * @param filename Report file to read.
* *
*/ */
void readErrorsXml(const QString &filename); void readErrorsXml(const QString &filename);
/** /**
@ -205,23 +205,23 @@ public:
signals: signals:
/** /**
* @brief Signal to be emitted when we have results * @brief Signal to be emitted when we have results
* *
*/ */
void gotResults(); void gotResults();
/** /**
* @brief Signal that results have been hidden or shown * @brief Signal that results have been hidden or shown
* *
* @param hidden true if there are some hidden results, or false if there are not * @param hidden true if there are some hidden results, or false if there are not
*/ */
void resultsHidden(bool hidden); void resultsHidden(bool hidden);
/** /**
* @brief Signal to perform recheck of selected files * @brief Signal to perform recheck of selected files
* *
* @param selectedFilesList list of selected files * @param selectedFilesList list of selected files
*/ */
void checkSelected(QStringList selectedFilesList); void checkSelected(QStringList selectedFilesList);
/** Suppress Ids */ /** Suppress Ids */
@ -240,88 +240,88 @@ signals:
void deleteVariableContract(QString var); void deleteVariableContract(QString var);
/** /**
* @brief Show/hide certain type of errors * @brief Show/hide certain type of errors
* Refreshes the tree. * Refreshes the tree.
* *
* @param type Type of error to show/hide * @param type Type of error to show/hide
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showResults(ShowTypes::ShowType type, bool show); void showResults(ShowTypes::ShowType type, bool show);
/** /**
* @brief Show/hide cppcheck errors. * @brief Show/hide cppcheck errors.
* Refreshes the tree. * Refreshes the tree.
* *
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showCppcheckResults(bool show); void showCppcheckResults(bool show);
/** /**
* @brief Show/hide clang-tidy/clang-analyzer errors. * @brief Show/hide clang-tidy/clang-analyzer errors.
* Refreshes the tree. * Refreshes the tree.
* *
* @param show Should specified errors be shown (true) or hidden (false) * @param show Should specified errors be shown (true) or hidden (false)
*/ */
void showClangResults(bool show); void showClangResults(bool show);
/** /**
* @brief Collapse all results in the result list. * @brief Collapse all results in the result list.
*/ */
void collapseAllResults(); void collapseAllResults();
/** /**
* @brief Expand all results in the result list. * @brief Expand all results in the result list.
*/ */
void expandAllResults(); void expandAllResults();
/** /**
* @brief Show hidden results in the result list. * @brief Show hidden results in the result list.
*/ */
void showHiddenResults(); void showHiddenResults();
public slots: public slots:
/** /**
* @brief Slot for updating the checking progress * @brief Slot for updating the checking progress
* *
* @param value Current progress value * @param value Current progress value
* @param description Description to accompany the progress * @param description Description to accompany the progress
*/ */
void progress(int value, const QString& description); void progress(int value, const QString& description);
/** /**
* @brief Slot for new error to be displayed * @brief Slot for new error to be displayed
* *
* @param item Error data * @param item Error data
*/ */
void error(const ErrorItem &item); void error(const ErrorItem &item);
/** /**
* @brief Filters the results in the result list. * @brief Filters the results in the result list.
*/ */
void filterResults(const QString& filter); void filterResults(const QString& filter);
/** /**
* @brief Update detailed message when selected item is changed. * @brief Update detailed message when selected item is changed.
* *
* @param index Position of new selected item. * @param index Position of new selected item.
*/ */
void updateDetails(const QModelIndex &index); void updateDetails(const QModelIndex &index);
/** /**
* @brief Slot opening a print dialog to print the current report * @brief Slot opening a print dialog to print the current report
*/ */
void print(); void print();
/** /**
* @brief Slot printing the current report to the printer. * @brief Slot printing the current report to the printer.
* @param printer The printer used for printing the report. * @param printer The printer used for printing the report.
*/ */
void print(QPrinter* printer); void print(QPrinter* printer);
/** /**
* @brief Slot opening a print preview dialog * @brief Slot opening a print preview dialog
*/ */
void printPreview(); void printPreview();
/** /**
@ -364,8 +364,8 @@ public slots:
protected: protected:
/** /**
* @brief Should we show a "No errors found dialog" every time no errors were found? * @brief Should we show a "No errors found dialog" every time no errors were found?
*/ */
bool mShowNoErrorsMessage; bool mShowNoErrorsMessage;
Ui::ResultsView mUI; Ui::ResultsView mUI;

View File

@ -28,22 +28,22 @@ class MainWindow;
/// @{ /// @{
/** /**
* @brief A window with a text field that . * @brief A window with a text field that .
*/ */
class ScratchPad : public QDialog { class ScratchPad : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
explicit ScratchPad(MainWindow& mainWindow); explicit ScratchPad(MainWindow& mainWindow);
/** /**
* @brief Translate dialog * @brief Translate dialog
*/ */
void translate(); void translate();
private slots: private slots:
/** /**
* @brief Called when check button is clicked. * @brief Called when check button is clicked.
*/ */
void checkButtonClicked(); void checkButtonClicked();
private: private:

View File

@ -70,7 +70,7 @@ SettingsDialog::SettingsDialog(ApplicationList *list,
mCurrentStyle = new CodeEditorStyle(CodeEditorStyle::loadSettings(&settings)); mCurrentStyle = new CodeEditorStyle(CodeEditorStyle::loadSettings(&settings));
manageStyleControls(); manageStyleControls();
connect(mUI.mEditPythonPath, SIGNAL(textEdited(const QString &)), connect(mUI.mEditPythonPath, SIGNAL(textEdited(const QString&)),
this, SLOT(validateEditPythonPath())); this, SLOT(validateEditPythonPath()));
connect(mUI.mButtons, &QDialogButtonBox::accepted, this, &SettingsDialog::ok); connect(mUI.mButtons, &QDialogButtonBox::accepted, this, &SettingsDialog::ok);
@ -83,7 +83,7 @@ SettingsDialog::SettingsDialog(ApplicationList *list,
this, SLOT(editApplication())); this, SLOT(editApplication()));
connect(mUI.mBtnDefaultApplication, SIGNAL(clicked()), connect(mUI.mBtnDefaultApplication, SIGNAL(clicked()),
this, SLOT(defaultApplication())); this, SLOT(defaultApplication()));
connect(mUI.mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), connect(mUI.mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(editApplication())); this, SLOT(editApplication()));
connect(mUI.mBtnBrowsePythonPath, &QPushButton::clicked, this, &SettingsDialog::browsePythonPath); connect(mUI.mBtnBrowsePythonPath, &QPushButton::clicked, this, &SettingsDialog::browsePythonPath);
@ -379,8 +379,8 @@ void SettingsDialog::editCodeEditorStyle()
void SettingsDialog::browseClangPath() void SettingsDialog::browseClangPath()
{ {
QString selectedDir = QFileDialog::getExistingDirectory(this, QString selectedDir = QFileDialog::getExistingDirectory(this,
tr("Select clang path"), tr("Select clang path"),
QDir::rootPath()); QDir::rootPath());
if (!selectedDir.isEmpty()) { if (!selectedDir.isEmpty()) {
mUI.mEditClangPath->setText(selectedDir); mUI.mEditClangPath->setText(selectedDir);

View File

@ -33,9 +33,9 @@ class CodeEditorStyle;
/// @{ /// @{
/** /**
* @brief Settings dialog * @brief Settings dialog
* *
*/ */
class SettingsDialog : public QDialog { class SettingsDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
@ -47,87 +47,87 @@ public:
SettingsDialog &operator=(const SettingsDialog &) = delete; SettingsDialog &operator=(const SettingsDialog &) = delete;
/** /**
* @brief Save all values to QSettings * @brief Save all values to QSettings
* *
*/ */
void saveSettingValues() const; void saveSettingValues() const;
/** /**
* @brief Get checkbox value for mShowFullPath * @brief Get checkbox value for mShowFullPath
* *
* @return should full path of errors be shown in the tree * @return should full path of errors be shown in the tree
*/ */
bool showFullPath() const; bool showFullPath() const;
/** /**
* @brief Get checkbox value for mSaveFullPath * @brief Get checkbox value for mSaveFullPath
* *
* @return should full path of files be saved when creating a report * @return should full path of files be saved when creating a report
*/ */
bool saveFullPath() const; bool saveFullPath() const;
/** /**
* @brief Get checkbox value for mNoErrorsMessage * @brief Get checkbox value for mNoErrorsMessage
* *
* @return Should "no errors message" be hidden * @return Should "no errors message" be hidden
*/ */
bool showNoErrorsMessage() const; bool showNoErrorsMessage() const;
/** /**
* @brief Get checkbox value for mShowIdColumn * @brief Get checkbox value for mShowIdColumn
* *
* @return Should error id column be displayed * @return Should error id column be displayed
*/ */
bool showErrorId() const; bool showErrorId() const;
/** /**
* @brief Get checkbox value for mEnableInconclusive * @brief Get checkbox value for mEnableInconclusive
* *
* @return Should inconclusive column be displayed * @return Should inconclusive column be displayed
*/ */
bool showInconclusive() const; bool showInconclusive() const;
/** /**
* @brief Get checkbox value for mSaveAllErrors * @brief Get checkbox value for mSaveAllErrors
* *
* @return should all errors be saved to report * @return should all errors be saved to report
*/ */
bool saveAllErrors() const; bool saveAllErrors() const;
protected slots: protected slots:
/** /**
* @brief Slot for clicking OK. * @brief Slot for clicking OK.
* *
*/ */
void ok(); void ok();
/** @brief Slot for validating input value in @c editPythonPath */ /** @brief Slot for validating input value in @c editPythonPath */
void validateEditPythonPath(); void validateEditPythonPath();
/** /**
* @brief Slot for adding a new application to the list * @brief Slot for adding a new application to the list
* *
*/ */
void addApplication(); void addApplication();
/** /**
* @brief Slot for deleting an application from the list * @brief Slot for deleting an application from the list
* *
*/ */
void removeApplication(); void removeApplication();
/** /**
* @brief Slot for modifying an application in the list * @brief Slot for modifying an application in the list
* *
*/ */
void editApplication(); void editApplication();
/** /**
* @brief Slot for making the selected application as the default (first) * @brief Slot for making the selected application as the default (first)
* *
*/ */
void defaultApplication(); void defaultApplication();
/** @brief Slot for browsing for the python binary */ /** @brief Slot for browsing for the python binary */
@ -153,22 +153,22 @@ protected slots:
protected: protected:
/** /**
* @brief Clear all applications from the list and re insert them from mTempApplications * @brief Clear all applications from the list and re insert them from mTempApplications
* *
*/ */
void populateApplicationList(); void populateApplicationList();
/** /**
* @brief Load saved values * @brief Load saved values
* Loads dialog size and column widths. * Loads dialog size and column widths.
* *
*/ */
void loadSettings(); void loadSettings();
/** /**
* @brief Save settings * @brief Save settings
* Save dialog size and column widths. * Save dialog size and column widths.
*/ */
void saveSettings() const; void saveSettings() const;
/** /**
@ -181,24 +181,24 @@ protected:
static void saveCheckboxValue(QSettings *settings, QCheckBox *box, const QString &name); static void saveCheckboxValue(QSettings *settings, QCheckBox *box, const QString &name);
/** /**
* @brief Convert bool to Qt::CheckState * @brief Convert bool to Qt::CheckState
* *
* @param yes value to convert * @param yes value to convert
* @return value converted to Qt::CheckState * @return value converted to Qt::CheckState
*/ */
static Qt::CheckState boolToCheckState(bool yes); static Qt::CheckState boolToCheckState(bool yes);
/** /**
* @brief Converts Qt::CheckState to bool * @brief Converts Qt::CheckState to bool
* *
* @param state Qt::CheckState to convert * @param state Qt::CheckState to convert
* @return converted value * @return converted value
*/ */
static bool checkStateToBool(Qt::CheckState state); static bool checkStateToBool(Qt::CheckState state);
/** /**
* @brief Populate the translations list. * @brief Populate the translations list.
*/ */
void initTranslationsList(); void initTranslationsList();
/** /**
@ -207,28 +207,28 @@ protected:
CodeEditorStyle *mCurrentStyle; CodeEditorStyle *mCurrentStyle;
/** /**
* @brief List of applications user has specified * @brief List of applications user has specified
* *
*/ */
ApplicationList *mApplications; ApplicationList *mApplications;
/** /**
* @brief Temporary list of applications * @brief Temporary list of applications
* This will be copied to actual list of applications (mApplications) * This will be copied to actual list of applications (mApplications)
* when user clicks ok. * when user clicks ok.
*/ */
ApplicationList *mTempApplications; ApplicationList *mTempApplications;
/** /**
* @brief List of translations. * @brief List of translations.
* *
*/ */
TranslationHandler *mTranslator; TranslationHandler *mTranslator;
/** /**
* @brief Dialog from UI designer * @brief Dialog from UI designer
* *
*/ */
Ui::Settings mUI; Ui::Settings mUI;
private: private:
void manageStyleControls(); void manageStyleControls();

View File

@ -27,20 +27,20 @@
/// @{ /// @{
/** /**
* @brief A class for different show types we have. * @brief A class for different show types we have.
* This class contains enum type for the different show types we have. Each * This class contains enum type for the different show types we have. Each
* show type presents one severity selectable in the GUI. In addition there * show type presents one severity selectable in the GUI. In addition there
* are several supporting functions. * are several supporting functions.
* *
* Notice that the "visibility" settings are automatically loaded when the * Notice that the "visibility" settings are automatically loaded when the
* class is constructed and saved when the class is destroyed. * class is constructed and saved when the class is destroyed.
*/ */
class ShowTypes { class ShowTypes {
public: public:
/** /**
* @brief Show types we have (i.e. severities in the GUI). * @brief Show types we have (i.e. severities in the GUI).
*/ */
enum ShowType { enum ShowType {
ShowStyle = 0, ShowStyle = 0,
ShowWarnings, ShowWarnings,

View File

@ -35,7 +35,7 @@ static const QString CPPCHECK("cppcheck");
StatsDialog::StatsDialog(QWidget *parent) StatsDialog::StatsDialog(QWidget *parent)
: QDialog(parent), : QDialog(parent),
mStatistics(nullptr) mStatistics(nullptr)
{ {
mUI.setupUi(this); mUI.setupUi(this);
@ -129,13 +129,13 @@ void StatsDialog::setScanDuration(double seconds)
void StatsDialog::pdfExport() void StatsDialog::pdfExport()
{ {
const QString Stat = QString( const QString Stat = QString(
"<center><h1>%1 %2</h1></center>\n" "<center><h1>%1 %2</h1></center>\n"
"<font color=\"red\"><h3>%3 : %4</h3></font>\n" "<font color=\"red\"><h3>%3 : %4</h3></font>\n"
"<font color=\"green\"><h3>%5 : %6</h3></font>\n" "<font color=\"green\"><h3>%5 : %6</h3></font>\n"
"<font color=\"orange\"><h3>%7 : %8</h3></font>\n" "<font color=\"orange\"><h3>%7 : %8</h3></font>\n"
"<font color=\"blue\"><h3>%9 : %10</h3></font>\n" "<font color=\"blue\"><h3>%9 : %10</h3></font>\n"
"<font color=\"blue\"><h3>%11 : %12</h3></font>\n" "<font color=\"blue\"><h3>%11 : %12</h3></font>\n"
"<font color=\"purple\"><h3>%13 : %14</h3></font>\n") "<font color=\"purple\"><h3>%13 : %14</h3></font>\n")
.arg(tr("Statistics")) .arg(tr("Statistics"))
.arg(QDate::currentDate().toString("dd.MM.yyyy")) .arg(QDate::currentDate().toString("dd.MM.yyyy"))
.arg(tr("Errors")) .arg(tr("Errors"))
@ -193,13 +193,13 @@ void StatsDialog::copyToClipboard()
// Plain text summary // Plain text summary
const QString settings = QString( const QString settings = QString(
"%1\n" "%1\n"
"\t%2:\t%3\n" "\t%2:\t%3\n"
"\t%4:\t%5\n" "\t%4:\t%5\n"
"\t%6:\t%7\n" "\t%6:\t%7\n"
"\t%8:\t%9\n" "\t%8:\t%9\n"
"\t%10:\t%11\n" "\t%10:\t%11\n"
) )
.arg(projSettings) .arg(projSettings)
.arg(project) .arg(project)
.arg(mUI.mProject->text()) .arg(mUI.mProject->text())
@ -213,11 +213,11 @@ void StatsDialog::copyToClipboard()
.arg(mUI.mUndefines->text()); .arg(mUI.mUndefines->text());
const QString previous = QString( const QString previous = QString(
"%1\n" "%1\n"
"\t%2:\t%3\n" "\t%2:\t%3\n"
"\t%4:\t%5\n" "\t%4:\t%5\n"
"\t%6:\t%7\n" "\t%6:\t%7\n"
) )
.arg(prevScan) .arg(prevScan)
.arg(selPath) .arg(selPath)
.arg(mUI.mPath->text()) .arg(mUI.mPath->text())
@ -227,14 +227,14 @@ void StatsDialog::copyToClipboard()
.arg(mUI.mScanDuration->text()); .arg(mUI.mScanDuration->text());
const QString statistics = QString( const QString statistics = QString(
"%1\n" "%1\n"
"\t%2:\t%3\n" "\t%2:\t%3\n"
"\t%4:\t%5\n" "\t%4:\t%5\n"
"\t%6:\t%7\n" "\t%6:\t%7\n"
"\t%8:\t%9\n" "\t%8:\t%9\n"
"\t%10:\t%11\n" "\t%10:\t%11\n"
"\t%12:\t%13\n" "\t%12:\t%13\n"
) )
.arg(stats) .arg(stats)
.arg(errors) .arg(errors)
.arg(mStatistics->getCount(CPPCHECK,ShowTypes::ShowErrors)) .arg(mStatistics->getCount(CPPCHECK,ShowTypes::ShowErrors))
@ -253,15 +253,15 @@ void StatsDialog::copyToClipboard()
// HTML summary // HTML summary
const QString htmlSettings = QString( const QString htmlSettings = QString(
"<h3>%1<h3>\n" "<h3>%1<h3>\n"
"<table>\n" "<table>\n"
" <tr><th>%2:</th><td>%3</td></tr>\n" " <tr><th>%2:</th><td>%3</td></tr>\n"
" <tr><th>%4:</th><td>%5</td></tr>\n" " <tr><th>%4:</th><td>%5</td></tr>\n"
" <tr><th>%6:</th><td>%7</td></tr>\n" " <tr><th>%6:</th><td>%7</td></tr>\n"
" <tr><th>%8:</th><td>%9</td></tr>\n" " <tr><th>%8:</th><td>%9</td></tr>\n"
" <tr><th>%10:</th><td>%11</td></tr>\n" " <tr><th>%10:</th><td>%11</td></tr>\n"
"</table>\n" "</table>\n"
) )
.arg(projSettings) .arg(projSettings)
.arg(project) .arg(project)
.arg(mUI.mProject->text()) .arg(mUI.mProject->text())
@ -275,13 +275,13 @@ void StatsDialog::copyToClipboard()
.arg(mUI.mUndefines->text()); .arg(mUI.mUndefines->text());
const QString htmlPrevious = QString( const QString htmlPrevious = QString(
"<h3>%1</h3>\n" "<h3>%1</h3>\n"
"<table>\n" "<table>\n"
" <tr><th>%2:</th><td>%3</td></tr>\n" " <tr><th>%2:</th><td>%3</td></tr>\n"
" <tr><th>%4:</th><td>%5</td></tr>\n" " <tr><th>%4:</th><td>%5</td></tr>\n"
" <tr><th>%6:</th><td>%7</td></tr>\n" " <tr><th>%6:</th><td>%7</td></tr>\n"
"</table>\n" "</table>\n"
) )
.arg(prevScan) .arg(prevScan)
.arg(selPath) .arg(selPath)
.arg(mUI.mPath->text()) .arg(mUI.mPath->text())
@ -291,15 +291,15 @@ void StatsDialog::copyToClipboard()
.arg(mUI.mScanDuration->text()); .arg(mUI.mScanDuration->text());
const QString htmlStatistics = QString( const QString htmlStatistics = QString(
"<h3>%1</h3>\n" "<h3>%1</h3>\n"
" <tr><th>%2:</th><td>%3</td></tr>\n" " <tr><th>%2:</th><td>%3</td></tr>\n"
" <tr><th>%4:</th><td>%5</td></tr>\n" " <tr><th>%4:</th><td>%5</td></tr>\n"
" <tr><th>%6:</th><td>%7</td></tr>\n" " <tr><th>%6:</th><td>%7</td></tr>\n"
" <tr><th>%8:</th><td>%9</td></tr>\n" " <tr><th>%8:</th><td>%9</td></tr>\n"
" <tr><th>%10:</th><td>%11</td></tr>\n" " <tr><th>%10:</th><td>%11</td></tr>\n"
" <tr><th>%12:</th><td>%13</td></tr>\n" " <tr><th>%12:</th><td>%13</td></tr>\n"
"</table>\n" "</table>\n"
) )
.arg(stats) .arg(stats)
.arg(errors) .arg(errors)
.arg(mStatistics->getCount(CPPCHECK,ShowTypes::ShowErrors)) .arg(mStatistics->getCount(CPPCHECK,ShowTypes::ShowErrors))

View File

@ -32,37 +32,37 @@ class CheckStatistics;
/// @{ /// @{
/** /**
* @brief A dialog that shows project and scan statistics. * @brief A dialog that shows project and scan statistics.
* *
*/ */
class StatsDialog : public QDialog { class StatsDialog : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
explicit StatsDialog(QWidget *parent = nullptr); explicit StatsDialog(QWidget *parent = nullptr);
/** /**
* @brief Sets the project to extract statistics from * @brief Sets the project to extract statistics from
*/ */
void setProject(const ProjectFile *projectFile); void setProject(const ProjectFile *projectFile);
/** /**
* @brief Sets the string to display beside "Path Selected:" * @brief Sets the string to display beside "Path Selected:"
*/ */
void setPathSelected(const QString& path); void setPathSelected(const QString& path);
/** /**
* @brief Sets the number to display beside "Number of Files Scanned:" * @brief Sets the number to display beside "Number of Files Scanned:"
*/ */
void setNumberOfFilesScanned(int num); void setNumberOfFilesScanned(int num);
/** /**
* @brief Sets the number of seconds to display beside "Scan Duration:" * @brief Sets the number of seconds to display beside "Scan Duration:"
*/ */
void setScanDuration(double seconds); void setScanDuration(double seconds);
/** /**
* @brief Sets the numbers of different error/warnings found." * @brief Sets the numbers of different error/warnings found."
*/ */
void setStatistics(const CheckStatistics *stats); void setStatistics(const CheckStatistics *stats);
private slots: private slots:

View File

@ -20,7 +20,7 @@
#include <QObject> #include <QObject>
#include "errorlogger.h" #include "errorlogger.h"
class BenchmarkSimple: public QObject, public ErrorLogger { class BenchmarkSimple : public QObject, public ErrorLogger {
Q_OBJECT Q_OBJECT
private slots: private slots:
@ -31,8 +31,6 @@ private slots:
private: private:
// Empty implementations of ErrorLogger methods. // Empty implementations of ErrorLogger methods.
// We don't care about the output in the benchmark tests. // We don't care about the output in the benchmark tests.
void reportOut(const std::string & outmsg) override { void reportOut(const std::string & outmsg) override {}
} void reportErr(const ErrorMessage &msg) override {}
void reportErr(const ErrorMessage &msg) override {
}
}; };

View File

@ -19,7 +19,7 @@
#include <QtTest/QtTest> #include <QtTest/QtTest>
#include "cppchecklibrarydata.h" #include "cppchecklibrarydata.h"
class TestCppcheckLibraryData: public QObject { class TestCppcheckLibraryData : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:

View File

@ -60,7 +60,7 @@ void CheckOther::incrementBooleanError(const Token *tok)
"incrementboolean", "incrementboolean",
"The use of a variable of type bool with the ++ postfix operator is always true and deprecated by the C++ Standard.\n" "The use of a variable of type bool with the ++ postfix operator is always true and deprecated by the C++ Standard.\n"
"The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true\n" "The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true\n"
); );
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -204,7 +204,7 @@ void CheckOther::checkSizeofForNumericParameter()
|| Token::Match(tok, "sizeof ( - %num% )") || Token::Match(tok, "sizeof ( - %num% )")
|| Token::Match(tok, "sizeof %num%") || Token::Match(tok, "sizeof %num%")
|| Token::Match(tok, "sizeof - %num%") || Token::Match(tok, "sizeof - %num%")
) { ) {
sizeofForNumericParameterError(tok); sizeofForNumericParameterError(tok);
} }
} }
@ -292,9 +292,9 @@ void CheckOther::checkRedundantAssignmentInSwitch()
} }
tok2 = endOfConditional; tok2 = endOfConditional;
} else } else
++ indentLevel; ++indentLevel;
} else if (tok2->str() == "}") { } else if (tok2->str() == "}") {
-- indentLevel; --indentLevel;
// End of the switch block // End of the switch block
if (indentLevel < 0) if (indentLevel < 0)
@ -343,7 +343,7 @@ void CheckOther::checkSwitchCaseFallThrough()
while (tok) { while (tok) {
// Check the contents of the switch statement // Check the contents of the switch statement
std::stack<std::pair<Token *, bool> > ifnest; std::stack<std::pair<Token *, bool>> ifnest;
std::stack<Token *> loopnest; std::stack<Token *> loopnest;
std::stack<Token *> scopenest; std::stack<Token *> scopenest;
bool justbreak = true; bool justbreak = true;
@ -618,14 +618,14 @@ void CheckOther::checkIncorrectLogicOperator()
enum Relation { Equal, NotEqual, Less, LessEqual, More, MoreEqual }; enum Relation { Equal, NotEqual, Less, LessEqual, More, MoreEqual };
struct Condition { struct Condition {
const char *before; const char *before;
Position position1; Position position1;
const char *op1TokStr; const char *op1TokStr;
const char *op2TokStr; const char *op2TokStr;
Position position2; Position position2;
const char *op3TokStr; const char *op3TokStr;
const char *after; const char *after;
Relation relation; Relation relation;
bool state; bool state;
} conditions[] = { } conditions[] = {
{ "!!&&", NA, "!=", "||", NA, "!=", "!!&&", NotEqual, true }, // (x != 1) || (x != 3) <- always true { "!!&&", NA, "!=", "||", NA, "!=", "!!&&", NotEqual, true }, // (x != 1) || (x != 3) <- always true
{ "(", NA, "==", "&&", NA, "==", ")", NotEqual, false }, // (x == 1) && (x == 3) <- always false { "(", NA, "==", "&&", NA, "==", ")", NotEqual, false }, // (x == 1) && (x == 3) <- always false
@ -669,11 +669,11 @@ void CheckOther::checkIncorrectLogicOperator()
if (!Token::Match(nextTok, conditions[i].after)) if (!Token::Match(nextTok, conditions[i].after))
continue; continue;
if ((conditions[i].relation == Equal && MathLib::isEqual(firstConstant, secondConstant)) || if ((conditions[i].relation == Equal && MathLib::isEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == NotEqual && MathLib::isNotEqual(firstConstant, secondConstant)) || (conditions[i].relation == NotEqual && MathLib::isNotEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == Less && MathLib::isLess(firstConstant, secondConstant)) || (conditions[i].relation == Less && MathLib::isLess(firstConstant, secondConstant)) ||
(conditions[i].relation == LessEqual && MathLib::isLessEqual(firstConstant, secondConstant)) || (conditions[i].relation == LessEqual && MathLib::isLessEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == More && MathLib::isGreater(firstConstant, secondConstant)) || (conditions[i].relation == More && MathLib::isGreater(firstConstant, secondConstant)) ||
(conditions[i].relation == MoreEqual && MathLib::isGreaterEqual(firstConstant, secondConstant))) (conditions[i].relation == MoreEqual && MathLib::isGreaterEqual(firstConstant, secondConstant)))
incorrectLogicOperatorError(term1Tok, conditions[i].state); incorrectLogicOperatorError(term1Tok, conditions[i].state);
} }
@ -878,7 +878,7 @@ void CheckOther::sizeofForNumericParameterError(const Token *tok)
" return sizeof(10);\n" " return sizeof(10);\n"
" }\n" " }\n"
" returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10." " returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10."
); );
} }
void CheckOther::sizeofForArrayParameterError(const Token *tok) void CheckOther::sizeofForArrayParameterError(const Token *tok)
@ -895,7 +895,7 @@ void CheckOther::sizeofForArrayParameterError(const Token *tok)
" }\n" " }\n"
" returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the " " returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the "
"size of the array in bytes)." "size of the array in bytes)."
); );
} }
void CheckOther::invalidScanfError(const Token *tok) void CheckOther::invalidScanfError(const Token *tok)
@ -984,8 +984,8 @@ void CheckOther::checkMemsetZeroBytes()
*/ */
class ScopeInfo { class ScopeInfo {
public: public:
ScopeInfo() : _token(NULL), _parent(NULL) { } ScopeInfo() : _token(NULL), _parent(NULL) {}
ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { } ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) {}
~ScopeInfo(); ~ScopeInfo();
ScopeInfo *parent() { ScopeInfo *parent() {
@ -1053,8 +1053,7 @@ public:
_read(read), _read(read),
_write(write), _write(write),
_modified(modified), _modified(modified),
_allocateMemory(allocateMemory) { _allocateMemory(allocateMemory) {}
}
/** variable is used.. set both read+write */ /** variable is used.. set both read+write */
void use() { void use() {
@ -1446,7 +1445,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference
if (addressOf || if (addressOf ||
var2->_type == Variables::array || var2->_type == Variables::array ||
var2->_type == Variables::pointer) { var2->_type == Variables::pointer) {
bool replace = true; bool replace = true;
// check if variable declared in same scope // check if variable declared in same scope
if (scope == var1->_scope) if (scope == var1->_scope)
@ -1640,7 +1639,7 @@ void CheckOther::functionVariableUsage()
while (tok->str() != "{") while (tok->str() != "{")
tok = tok->next(); tok = tok->next();
tok = tok->link(); tok = tok->link();
if (! tok) if (!tok)
break; break;
} }
@ -2253,7 +2252,7 @@ void CheckOther::checkVariableScope()
break; break;
} }
} }
if (! tok) if (!tok)
break; break;
} }
@ -2268,7 +2267,7 @@ void CheckOther::checkVariableScope()
if (indentlevel > 0 && Token::Match(tok, "[{};]")) { if (indentlevel > 0 && Token::Match(tok, "[{};]")) {
// First token of statement.. // First token of statement..
const Token *tok1 = tok->next(); const Token *tok1 = tok->next();
if (! tok1) if (!tok1)
continue; continue;
if ((tok1->str() == "return") || if ((tok1->str() == "return") ||
@ -2531,7 +2530,7 @@ void CheckOther::checkStructMemberUsage()
} }
} }
if (! used) { if (!used) {
unusedStructMemberError(tok->next(), structname, varname); unusedStructMemberError(tok->next(), structname, varname);
} }
} }
@ -2799,7 +2798,7 @@ void CheckOther::checkMathFunctions()
// pow ( x , y) If x is zero, and y is negative --> division by zero // pow ( x , y) If x is zero, and y is negative --> division by zero
else if (tok->varId() == 0 && else if (tok->varId() == 0 &&
Token::Match(tok, "pow ( %num% , %num% )") && Token::Match(tok, "pow ( %num% , %num% )") &&
MathLib::isNullValue(tok->tokAt(2)->str()) && MathLib::isNullValue(tok->tokAt(2)->str()) &&
MathLib::isNegative(tok->tokAt(4)->str())) { MathLib::isNegative(tok->tokAt(4)->str())) {
mathfunctionCallError(tok, 2); mathfunctionCallError(tok, 2);
} }

View File

@ -1 +1 @@
Dummy test file. Dummy test file .

View File

@ -1 +1 @@
Dummy test file. Dummy test file .

View File

@ -1 +1 @@
Dummy test file. Dummy test file .

View File

@ -1 +1 @@
Dummy test file. Dummy test file .

View File

@ -1 +1 @@
Dummy test file. Dummy test file .

View File

@ -109,8 +109,8 @@ void TestFileList::filterFiles()
QCOMPARE(files.size(), 5); QCOMPARE(files.size(), 5);
QDir dir(QString(SRCDIR) + "/../data/files"); QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath(); QString base = dir.canonicalPath();
QVERIFY(! files.contains(base + "/foo1.cpp")); QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(! files.contains(base + "/foo3.cpp")); QVERIFY(!files.contains(base + "/foo3.cpp"));
} }
void TestFileList::filterFiles2() void TestFileList::filterFiles2()
@ -124,8 +124,8 @@ void TestFileList::filterFiles2()
QCOMPARE(files.size(), 5); QCOMPARE(files.size(), 5);
QDir dir(QString(SRCDIR) + "/../data/files"); QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath(); QString base = dir.canonicalPath();
QVERIFY(! files.contains(base + "/foo1.cpp")); QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(! files.contains(base + "/foo3.cpp")); QVERIFY(!files.contains(base + "/foo3.cpp"));
} }
void TestFileList::filterFiles3() void TestFileList::filterFiles3()
@ -139,10 +139,10 @@ void TestFileList::filterFiles3()
QCOMPARE(files.size(), 6); QCOMPARE(files.size(), 6);
QDir dir(QString(SRCDIR) + "/../data/files"); QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath(); QString base = dir.canonicalPath();
QVERIFY(! files.contains(base + "/foo1.cpp")); QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(! files.contains(base + "/foo3.cpp")); QVERIFY(!files.contains(base + "/foo3.cpp"));
QVERIFY(! files.contains(base + "/dir1/foo1.cpp")); QVERIFY(!files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(! files.contains(base + "/dir2/foo1.cpp")); QVERIFY(!files.contains(base + "/dir2/foo1.cpp"));
} }
void TestFileList::filterFiles4() void TestFileList::filterFiles4()
@ -156,12 +156,12 @@ void TestFileList::filterFiles4()
QCOMPARE(files.size(), 8); QCOMPARE(files.size(), 8);
QDir dir(QString(SRCDIR) + "/../data/files"); QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath(); QString base = dir.canonicalPath();
QVERIFY(! files.contains(base + "/dir1/foo1.cpp")); QVERIFY(!files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(! files.contains(base + "/dir1/dir11/foo11.cpp")); QVERIFY(!files.contains(base + "/dir1/dir11/foo11.cpp"));
} }
/* /*
void TestFileList::filterFiles5() void TestFileList::filterFiles5()
{ {
FileList list; FileList list;
QStringList filters; QStringList filters;
filters << QDir(QString(SRCDIR) + "/../data/files/dir1/").absolutePath() + "/"; filters << QDir(QString(SRCDIR) + "/../data/files/dir1/").absolutePath() + "/";
@ -173,6 +173,6 @@ void TestFileList::filterFiles5()
QString base = dir.canonicalPath(); QString base = dir.canonicalPath();
QVERIFY(! files.contains(base + "/dir1/foo1.cpp")); QVERIFY(! files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(! files.contains(base + "/dir1/dir11/foo11.cpp")); QVERIFY(! files.contains(base + "/dir1/dir11/foo11.cpp"));
} }
*/ */
QTEST_MAIN(TestFileList) QTEST_MAIN(TestFileList)

View File

@ -19,7 +19,7 @@
#include <QtTest/QtTest> #include <QtTest/QtTest>
#include <QObject> #include <QObject>
class TestFileList: public QObject { class TestFileList : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:

View File

@ -19,7 +19,7 @@
#include <QtTest/QtTest> #include <QtTest/QtTest>
#include <QObject> #include <QObject>
class TestProjectFile: public QObject { class TestProjectFile : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:

View File

@ -19,7 +19,7 @@
#include <QtTest/QtTest> #include <QtTest/QtTest>
#include <QObject> #include <QObject>
class TestTranslationHandler: public QObject { class TestTranslationHandler : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:

View File

@ -19,7 +19,7 @@
#include <QtTest/QtTest> #include <QtTest/QtTest>
#include <QObject> #include <QObject>
class TestXmlReportV2: public QObject { class TestXmlReportV2 : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:

View File

@ -38,9 +38,9 @@ class ImportProject;
/** /**
* @brief This class handles creating threadresult and starting threads * @brief This class handles creating threadresult and starting threads
* *
*/ */
class ThreadHandler : public QObject { class ThreadHandler : public QObject {
Q_OBJECT Q_OBJECT
public: public:
@ -48,28 +48,28 @@ public:
virtual ~ThreadHandler(); virtual ~ThreadHandler();
/** /**
* @brief Set the number of threads to use * @brief Set the number of threads to use
* @param count The number of threads to use * @param count The number of threads to use
*/ */
void setThreadCount(const int count); void setThreadCount(const int count);
/** /**
* @brief Initialize the threads (connect all signals to resultsview's slots) * @brief Initialize the threads (connect all signals to resultsview's slots)
* *
* @param view View to show error results * @param view View to show error results
*/ */
void initialize(ResultsView *view); void initialize(ResultsView *view);
/** /**
* @brief Load settings * @brief Load settings
* @param settings QSettings to load settings from * @param settings QSettings to load settings from
*/ */
void loadSettings(const QSettings &settings); void loadSettings(const QSettings &settings);
/** /**
* @brief Save settings * @brief Save settings
* @param settings QSettings to save settings to * @param settings QSettings to save settings to
*/ */
void saveSettings(QSettings &settings) const; void saveSettings(QSettings &settings) const;
void setAddonsAndTools(const QStringList &addonsAndTools) { void setAddonsAndTools(const QStringList &addonsAndTools) {
@ -89,72 +89,72 @@ public:
} }
/** /**
* @brief Clear all files from cppcheck * @brief Clear all files from cppcheck
* *
*/ */
void clearFiles(); void clearFiles();
/** /**
* @brief Set files to check * @brief Set files to check
* *
* @param files files to check * @param files files to check
*/ */
void setFiles(const QStringList &files); void setFiles(const QStringList &files);
/** /**
* @brief Set project to check * @brief Set project to check
* *
* @param prj project to check * @param prj project to check
*/ */
void setProject(const ImportProject &prj); void setProject(const ImportProject &prj);
/** /**
* @brief Start the threads to check the files * @brief Start the threads to check the files
* *
* @param settings Settings for checking * @param settings Settings for checking
*/ */
void check(const Settings &settings); void check(const Settings &settings);
/** /**
* @brief Set files to check * @brief Set files to check
* *
* @param all true if all files, false if modified files * @param all true if all files, false if modified files
*/ */
void setCheckFiles(bool all); void setCheckFiles(bool all);
/** /**
* @brief Set selected files to check * @brief Set selected files to check
* *
* @param files list of files to be checked * @param files list of files to be checked
*/ */
void setCheckFiles(const QStringList& files); void setCheckFiles(const QStringList& files);
/** /**
* @brief Is checking running? * @brief Is checking running?
* *
* @return true if check is running, false otherwise. * @return true if check is running, false otherwise.
*/ */
bool isChecking() const; bool isChecking() const;
/** /**
* @brief Have we checked files already? * @brief Have we checked files already?
* *
* @return true check has been previously run and recheck can be done * @return true check has been previously run and recheck can be done
*/ */
bool hasPreviousFiles() const; bool hasPreviousFiles() const;
/** /**
* @brief Return count of files we checked last time. * @brief Return count of files we checked last time.
* *
* @return count of files that were checked last time. * @return count of files that were checked last time.
*/ */
int getPreviousFilesCount() const; int getPreviousFilesCount() const;
/** /**
* @brief Return the time elapsed while scanning the previous time. * @brief Return the time elapsed while scanning the previous time.
* *
* @return the time elapsed in milliseconds. * @return the time elapsed in milliseconds.
*/ */
int getPreviousScanDuration() const; int getPreviousScanDuration() const;
/** /**
@ -164,24 +164,24 @@ public:
QStringList getReCheckFiles(bool all) const; QStringList getReCheckFiles(bool all) const;
/** /**
* @brief Get start time of last check * @brief Get start time of last check
* *
* @return start time of last check * @return start time of last check
*/ */
QDateTime getCheckStartTime() const; QDateTime getCheckStartTime() const;
/** /**
* @brief Set start time of check * @brief Set start time of check
* *
* @param checkStartTime saved start time of the last check * @param checkStartTime saved start time of the last check
*/ */
void setCheckStartTime(QDateTime checkStartTime); void setCheckStartTime(QDateTime checkStartTime);
signals: signals:
/** /**
* @brief Signal that all threads are done * @brief Signal that all threads are done
* *
*/ */
void done(); void done();
void log(const QString &msg); void log(const QString &msg);
@ -193,21 +193,21 @@ signals:
public slots: public slots:
/** /**
* @brief Slot to stop all threads * @brief Slot to stop all threads
* *
*/ */
void stop(); void stop();
protected slots: protected slots:
/** /**
* @brief Slot that a single thread is done * @brief Slot that a single thread is done
* *
*/ */
void threadDone(); void threadDone();
protected: protected:
/** /**
* @brief List of files checked last time (used when rechecking) * @brief List of files checked last time (used when rechecking)
* *
*/ */
QStringList mLastFiles; QStringList mLastFiles;
/** @brief date and time when current checking started */ /** @brief date and time when current checking started */
@ -219,39 +219,39 @@ protected:
QDateTime mLastCheckTime; QDateTime mLastCheckTime;
/** /**
* @brief Timer used for measuring scan duration * @brief Timer used for measuring scan duration
* *
*/ */
QTime mTime; QTime mTime;
/** /**
* @brief The previous scan duration in milliseconds. * @brief The previous scan duration in milliseconds.
* *
*/ */
int mScanDuration; int mScanDuration;
/** /**
* @brief Function to delete all threads * @brief Function to delete all threads
* *
*/ */
void removeThreads(); void removeThreads();
/** /**
* @brief Thread results are stored here * @brief Thread results are stored here
* *
*/ */
ThreadResult mResults; ThreadResult mResults;
/** /**
* @brief List of threads currently in use * @brief List of threads currently in use
* *
*/ */
QList<CheckThread *> mThreads; QList<CheckThread *> mThreads;
/** /**
* @brief The amount of threads currently running * @brief The amount of threads currently running
* *
*/ */
int mRunningThreadCount; int mRunningThreadCount;
bool mAnalyseWholeProgram; bool mAnalyseWholeProgram;

View File

@ -43,7 +43,7 @@ void ThreadResult::fileChecked(const QString &file)
QMutexLocker locker(&mutex); QMutexLocker locker(&mutex);
mProgress += QFile(file).size(); mProgress += QFile(file).size();
mFilesChecked ++; mFilesChecked++;
if (mMaxProgress > 0) { if (mMaxProgress > 0) {
const int value = static_cast<int>(PROGRESS_MAX * mProgress / mMaxProgress); const int value = static_cast<int>(PROGRESS_MAX * mProgress / mMaxProgress);

View File

@ -33,9 +33,9 @@ class ErrorItem;
/// @{ /// @{
/** /**
* @brief Threads use this class to obtain new files to process and to publish results * @brief Threads use this class to obtain new files to process and to publish results
* *
*/ */
class ThreadResult : public QObject, public ErrorLogger { class ThreadResult : public QObject, public ErrorLogger {
Q_OBJECT Q_OBJECT
public: public:
@ -43,36 +43,36 @@ public:
virtual ~ThreadResult(); virtual ~ThreadResult();
/** /**
* @brief Get next unprocessed file * @brief Get next unprocessed file
* @return File path * @return File path
*/ */
QString getNextFile(); QString getNextFile();
ImportProject::FileSettings getNextFileSettings(); ImportProject::FileSettings getNextFileSettings();
/** /**
* @brief Set list of files to check * @brief Set list of files to check
* @param files List of files to check * @param files List of files to check
*/ */
void setFiles(const QStringList &files); void setFiles(const QStringList &files);
void setProject(const ImportProject &prj); void setProject(const ImportProject &prj);
/** /**
* @brief Clear files to check * @brief Clear files to check
* *
*/ */
void clearFiles(); void clearFiles();
/** /**
* @brief Get the number of files to check * @brief Get the number of files to check
* *
*/ */
int getFileCount() const; int getFileCount() const;
/** /**
* ErrorLogger methods * ErrorLogger methods
*/ */
void reportOut(const std::string &outmsg, Color c = Color::Reset) override; void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
void reportErr(const ErrorMessage &msg) override; void reportErr(const ErrorMessage &msg) override;
void bughuntingReport(const std::string &str) override; void bughuntingReport(const std::string &str) override;
@ -80,37 +80,37 @@ public:
public slots: public slots:
/** /**
* @brief Slot threads use to signal this class that a specific file is checked * @brief Slot threads use to signal this class that a specific file is checked
* @param file File that is checked * @param file File that is checked
*/ */
void fileChecked(const QString &file); void fileChecked(const QString &file);
signals: signals:
/** /**
* @brief Progress signal * @brief Progress signal
* @param value Current progress * @param value Current progress
* @param description Description of the current stage * @param description Description of the current stage
*/ */
void progress(int value, const QString& description); void progress(int value, const QString& description);
/** /**
* @brief Signal of a new error * @brief Signal of a new error
* *
* @param item Error data * @param item Error data
*/ */
void error(const ErrorItem &item); void error(const ErrorItem &item);
/** /**
* @brief Signal of a new log message * @brief Signal of a new log message
* *
* @param logline Log line * @param logline Log line
*/ */
void log(const QString &logline); void log(const QString &logline);
/** /**
* @brief Signal of a debug error * @brief Signal of a debug error
* *
* @param item Error data * @param item Error data
*/ */
void debugError(const ErrorItem &item); void debugError(const ErrorItem &item);
/** @brief bug hunting report */ /** @brief bug hunting report */
@ -119,41 +119,41 @@ signals:
protected: protected:
/** /**
* @brief Mutex * @brief Mutex
* *
*/ */
mutable QMutex mutex; mutable QMutex mutex;
/** /**
* @brief List of files to check * @brief List of files to check
* *
*/ */
QStringList mFiles; QStringList mFiles;
std::list<ImportProject::FileSettings> mFileSettings; std::list<ImportProject::FileSettings> mFileSettings;
/** /**
* @brief Max progress * @brief Max progress
* *
*/ */
quint64 mMaxProgress; quint64 mMaxProgress;
/** /**
* @brief Current progress * @brief Current progress
* *
*/ */
quint64 mProgress; quint64 mProgress;
/** /**
* @brief Current number of files checked * @brief Current number of files checked
* *
*/ */
unsigned long mFilesChecked; unsigned long mFilesChecked;
/** /**
* @brief Total number of files * @brief Total number of files
* *
*/ */
unsigned long mTotalFiles; unsigned long mTotalFiles;
}; };
/// @} /// @}

View File

@ -31,12 +31,12 @@
static void unused() static void unused()
{ {
// NOTE: Keeping semi-colons at end of macro for style preference // NOTE: Keeping semi-colons at end of macro for style preference
#if ((QT_VERSION >= 0x040000)&&(QT_VERSION < 0x050000)) #if ((QT_VERSION >= 0x040000) && (QT_VERSION < 0x050000))
Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "OK")); Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "OK"));
Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Cancel")); Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Cancel"));
Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Close")); Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Close"));
Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Save")); Q_UNUSED(QT_TRANSLATE_NOOP("QDialogButtonBox", "Save"));
#elif ((QT_VERSION >= 0x050000)&&(QT_VERSION < 0x060000)) #elif ((QT_VERSION >= 0x050000) && (QT_VERSION < 0x060000))
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "OK")); Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "OK"));
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Cancel")); Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Cancel"));
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Close")); Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Close"));
@ -69,8 +69,7 @@ TranslationHandler::TranslationHandler(QObject *parent) :
} }
TranslationHandler::~TranslationHandler() TranslationHandler::~TranslationHandler()
{ {}
}
const QStringList TranslationHandler::getNames() const const QStringList TranslationHandler::getNames() const
{ {

View File

@ -29,36 +29,36 @@ class QTranslator;
/// @{ /// @{
/** /**
* @brief Information for one translation. * @brief Information for one translation.
* *
*/ */
struct TranslationInfo { struct TranslationInfo {
/** /**
* @brief Readable name for the translation (e.g. "English"). * @brief Readable name for the translation (e.g. "English").
* *
*/ */
QString mName; QString mName;
/** /**
* @brief Filename for the translation. * @brief Filename for the translation.
* *
*/ */
QString mFilename; QString mFilename;
/** /**
* @brief ISO 639 language code for the translation (e.g. "en"). * @brief ISO 639 language code for the translation (e.g. "en").
* *
*/ */
QString mCode; QString mCode;
}; };
/** /**
* @brief A class handling the available translations. * @brief A class handling the available translations.
* *
* This class contains a list of available translations. The class also keeps * This class contains a list of available translations. The class also keeps
* track which translation is the currently active translation. * track which translation is the currently active translation.
* *
*/ */
class TranslationHandler : QObject { class TranslationHandler : QObject {
Q_OBJECT Q_OBJECT
public: public:
@ -66,82 +66,82 @@ public:
virtual ~TranslationHandler(); virtual ~TranslationHandler();
/** /**
* @brief Get a list of available translation names. * @brief Get a list of available translation names.
* @return List of available translation names. * @return List of available translation names.
* *
*/ */
const QStringList getNames() const; const QStringList getNames() const;
/** /**
* @brief Get a list of available translations. * @brief Get a list of available translations.
* @return List of available translations. * @return List of available translations.
* *
*/ */
QList<TranslationInfo> getTranslations() const { QList<TranslationInfo> getTranslations() const {
return mTranslations; return mTranslations;
} }
/** /**
* @brief Set active translation. * @brief Set active translation.
* @param code ISO 639 language code for new selected translation. * @param code ISO 639 language code for new selected translation.
* @return true if succeeds, false otherwise. * @return true if succeeds, false otherwise.
* *
*/ */
bool setLanguage(const QString &code); bool setLanguage(const QString &code);
/** /**
* @brief Get currently selected translation. * @brief Get currently selected translation.
* @return ISO 639 language code for current translation. * @return ISO 639 language code for current translation.
* *
*/ */
QString getCurrentLanguage() const; QString getCurrentLanguage() const;
/** /**
* @brief Get translation suggestion for the system. * @brief Get translation suggestion for the system.
* This function checks the current system locale and determines which of * This function checks the current system locale and determines which of
* the available translations is best as current translation. If none of * the available translations is best as current translation. If none of
* the available translations is good then it returns English ("en"). * the available translations is good then it returns English ("en").
* @return Suggested translation ISO 639 language code. * @return Suggested translation ISO 639 language code.
* *
*/ */
QString suggestLanguage() const; QString suggestLanguage() const;
protected: protected:
/** /**
* @brief Add new translation to list of available translations. * @brief Add new translation to list of available translations.
* @param name Name of the translation ("English"). * @param name Name of the translation ("English").
* @param filename Filename of the translation. * @param filename Filename of the translation.
* *
*/ */
void addTranslation(const char *name, const char *filename); void addTranslation(const char *name, const char *filename);
/** /**
* @brief Find language in the list and return its index. * @brief Find language in the list and return its index.
* @param code ISO 639 language code. * @param code ISO 639 language code.
* @return Index at list, or -1 if not found. * @return Index at list, or -1 if not found.
* *
*/ */
int getLanguageIndexByCode(const QString &code) const; int getLanguageIndexByCode(const QString &code) const;
private: private:
/** /**
* @brief ISO 639 language code of the currently selected translation. * @brief ISO 639 language code of the currently selected translation.
* *
*/ */
QString mCurrentLanguage; QString mCurrentLanguage;
/** /**
* @brief List of available translations. * @brief List of available translations.
* *
*/ */
QList<TranslationInfo> mTranslations; QList<TranslationInfo> mTranslations;
/** /**
* @brief Translator class instance. * @brief Translator class instance.
* *
*/ */
QTranslator *mTranslator; QTranslator *mTranslator;
}; };

View File

@ -23,12 +23,10 @@
TxtReport::TxtReport(const QString &filename) : TxtReport::TxtReport(const QString &filename) :
Report(filename) Report(filename)
{ {}
}
TxtReport::~TxtReport() TxtReport::~TxtReport()
{ {}
}
bool TxtReport::create() bool TxtReport::create()
{ {
@ -52,9 +50,9 @@ void TxtReport::writeFooter()
void TxtReport::writeError(const ErrorItem &error) void TxtReport::writeError(const ErrorItem &error)
{ {
/* /*
Error example from the core program in text Error example from the core program in text
[gui/test.cpp:23] -> [gui/test.cpp:14]: (error) Mismatching allocation and deallocation: k [gui/test.cpp:23] -> [gui/test.cpp:14]: (error) Mismatching allocation and deallocation: k
*/ */
QString line; QString line;

View File

@ -28,9 +28,9 @@
/** /**
* @brief Text file report. * @brief Text file report.
* This report mimics the output of the command line cppcheck. * This report mimics the output of the command line cppcheck.
*/ */
class TxtReport : public Report { class TxtReport : public Report {
Q_OBJECT Q_OBJECT
@ -39,32 +39,32 @@ public:
virtual ~TxtReport(); virtual ~TxtReport();
/** /**
* @brief Create the report (file). * @brief Create the report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool create() override; virtual bool create() override;
/** /**
* @brief Write report header. * @brief Write report header.
*/ */
virtual void writeHeader() override; virtual void writeHeader() override;
/** /**
* @brief Write report footer. * @brief Write report footer.
*/ */
virtual void writeFooter() override; virtual void writeFooter() override;
/** /**
* @brief Write error to report. * @brief Write error to report.
* @param error Error data. * @param error Error data.
*/ */
virtual void writeError(const ErrorItem &error) override; virtual void writeError(const ErrorItem &error) override;
private: private:
/** /**
* @brief Text stream writer for writing the report in text format. * @brief Text stream writer for writing the report in text format.
*/ */
QTextStream mTxtWriter; QTextStream mTxtWriter;
}; };
/// @} /// @}

View File

@ -27,8 +27,7 @@ static const char VersionAttribute[] = "version";
XmlReport::XmlReport(const QString &filename) : XmlReport::XmlReport(const QString &filename) :
Report(filename) Report(filename)
{ {}
}
QString XmlReport::quoteMessage(const QString &message) QString XmlReport::quoteMessage(const QString &message)
{ {

View File

@ -30,8 +30,8 @@ class ErrorItem;
/** /**
* @brief Base class for XML report classes. * @brief Base class for XML report classes.
*/ */
class XmlReport : public Report { class XmlReport : public Report {
public: public:
explicit XmlReport(const QString &filename); explicit XmlReport(const QString &filename);

View File

@ -51,8 +51,7 @@ XmlReportV2::XmlReportV2(const QString &filename) :
XmlReport(filename), XmlReport(filename),
mXmlReader(nullptr), mXmlReader(nullptr),
mXmlWriter(nullptr) mXmlWriter(nullptr)
{ {}
}
XmlReportV2::~XmlReportV2() XmlReportV2::~XmlReportV2()
{ {
@ -100,13 +99,13 @@ void XmlReportV2::writeFooter()
void XmlReportV2::writeError(const ErrorItem &error) void XmlReportV2::writeError(const ErrorItem &error)
{ {
/* /*
Error example from the core program in xml Error example from the core program in xml
<error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k" <error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k"
verbose="Mismatching allocation and deallocation: k"> verbose="Mismatching allocation and deallocation: k">
<location file="..\..\test\test.cxx" line="16"/> <location file="..\..\test\test.cxx" line="16"/>
<location file="..\..\test\test.cxx" line="32"/> <location file="..\..\test\test.cxx" line="32"/>
</error> </error>
*/ */
mXmlWriter->writeStartElement(ErrorElementName); mXmlWriter->writeStartElement(ErrorElementName);
mXmlWriter->writeAttribute(IdAttribute, error.errorId); mXmlWriter->writeAttribute(IdAttribute, error.errorId);
@ -192,13 +191,13 @@ QList<ErrorItem> XmlReportV2::read()
ErrorItem XmlReportV2::readError(QXmlStreamReader *reader) ErrorItem XmlReportV2::readError(QXmlStreamReader *reader)
{ {
/* /*
Error example from the core program in xml Error example from the core program in xml
<error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k" <error id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k"
verbose="Mismatching allocation and deallocation: k"> verbose="Mismatching allocation and deallocation: k">
<location file="..\..\test\test.cxx" line="16"/> <location file="..\..\test\test.cxx" line="16"/>
<location file="..\..\test\test.cxx" line="32"/> <location file="..\..\test\test.cxx" line="32"/>
</error> </error>
*/ */
ErrorItem item; ErrorItem item;

View File

@ -30,63 +30,63 @@ class QXmlStreamWriter;
/** /**
* @brief XML file report version 2. * @brief XML file report version 2.
* This report outputs XML-formatted report. The XML format must match command * This report outputs XML-formatted report. The XML format must match command
* line version's XML output. * line version's XML output.
*/ */
class XmlReportV2 : public XmlReport { class XmlReportV2 : public XmlReport {
public: public:
explicit XmlReportV2(const QString &filename); explicit XmlReportV2(const QString &filename);
virtual ~XmlReportV2(); virtual ~XmlReportV2();
/** /**
* @brief Create the report (file). * @brief Create the report (file).
* @return true if succeeded, false if file could not be created. * @return true if succeeded, false if file could not be created.
*/ */
virtual bool create() override; virtual bool create() override;
/** /**
* @brief Open existing report file. * @brief Open existing report file.
*/ */
virtual bool open() override; virtual bool open() override;
/** /**
* @brief Write report header. * @brief Write report header.
*/ */
virtual void writeHeader() override; virtual void writeHeader() override;
/** /**
* @brief Write report footer. * @brief Write report footer.
*/ */
virtual void writeFooter() override; virtual void writeFooter() override;
/** /**
* @brief Write error to report. * @brief Write error to report.
* @param error Error data. * @param error Error data.
*/ */
virtual void writeError(const ErrorItem &error) override; virtual void writeError(const ErrorItem &error) override;
/** /**
* @brief Read contents of the report file. * @brief Read contents of the report file.
*/ */
virtual QList<ErrorItem> read() override; virtual QList<ErrorItem> read() override;
protected: protected:
/** /**
* @brief Read and parse error item from XML stream. * @brief Read and parse error item from XML stream.
* @param reader XML stream reader to use. * @param reader XML stream reader to use.
*/ */
ErrorItem readError(QXmlStreamReader *reader); ErrorItem readError(QXmlStreamReader *reader);
private: private:
/** /**
* @brief XML stream reader for reading the report in XML format. * @brief XML stream reader for reading the report in XML format.
*/ */
QXmlStreamReader *mXmlReader; QXmlStreamReader *mXmlReader;
/** /**
* @brief XML stream writer for writing the report in XML format. * @brief XML stream writer for writing the report in XML format.
*/ */
QXmlStreamWriter *mXmlWriter; QXmlStreamWriter *mXmlWriter;
}; };
/// @} /// @}

View File

@ -23,7 +23,7 @@
#include <vector> #include <vector>
class Token; class Token;
template <class T> template<class T>
class ValuePtr; class ValuePtr;
struct Analyzer { struct Analyzer {
@ -86,7 +86,9 @@ struct Analyzer {
return get(Incremental); return get(Incremental);
} }
bool isSymbolicMatch() const { return get(SymbolicMatch); } bool isSymbolicMatch() const {
return get(SymbolicMatch);
}
bool matches() const { bool matches() const {
return get(Match); return get(Match);

View File

@ -1,20 +1,20 @@
/* /*
* Cppcheck - A tool for static C/C++ code analysis * Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team. * Copyright (C) 2007-2021 Cppcheck team.
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "analyzerinfo.h" #include "analyzerinfo.h"

View File

@ -1,20 +1,20 @@
/* /*
* Cppcheck - A tool for static C/C++ code analysis * Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team. * Copyright (C) 2007-2021 Cppcheck team.
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#ifndef analyzerinfoH #ifndef analyzerinfoH
@ -34,18 +34,18 @@ class ErrorMessage;
/// @{ /// @{
/** /**
* @brief Analyzer information * @brief Analyzer information
* *
* Store various analysis information: * Store various analysis information:
* - checksum * - checksum
* - error messages * - error messages
* - whole program analysis data * - whole program analysis data
* *
* The information can be used for various purposes. It allows: * The information can be used for various purposes. It allows:
* - 'make' - only analyze TUs that are changed and generate full report * - 'make' - only analyze TUs that are changed and generate full report
* - should be possible to add distributed analysis later * - should be possible to add distributed analysis later
* - multi-threaded whole program analysis * - multi-threaded whole program analysis
*/ */
class CPPCHECKLIB AnalyzerInformation { class CPPCHECKLIB AnalyzerInformation {
public: public:
~AnalyzerInformation(); ~AnalyzerInformation();

View File

@ -37,7 +37,7 @@
#include <stack> #include <stack>
#include <utility> #include <utility>
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*>)> template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
void visitAstNodesGeneric(T *ast, std::function<ChildrenToVisit(T *)> visitor) void visitAstNodesGeneric(T *ast, std::function<ChildrenToVisit(T *)> visitor)
{ {
std::stack<T *> tokens; std::stack<T *> tokens;
@ -344,7 +344,7 @@ static bool hasToken(const Token * startTok, const Token * stopTok, const Token
return false; return false;
} }
template <class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*>)> template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* previousBeforeAstLeftmostLeafGeneric(T* tok) static T* previousBeforeAstLeftmostLeafGeneric(T* tok)
{ {
if (!tok) if (!tok)
@ -364,7 +364,7 @@ Token* previousBeforeAstLeftmostLeaf(Token* tok)
return previousBeforeAstLeftmostLeafGeneric(tok); return previousBeforeAstLeftmostLeafGeneric(tok);
} }
template <class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*>)> template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* nextAfterAstRightmostLeafGeneric(T* tok) static T* nextAfterAstRightmostLeafGeneric(T* tok)
{ {
const Token * rightmostLeaf = tok; const Token * rightmostLeaf = tok;
@ -474,7 +474,7 @@ bool astIsRHS(const Token* tok)
return parent->astOperand2() == tok; return parent->astOperand2() == tok;
} }
template <class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*>)> template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokImpl(T* tok) static T* getCondTokImpl(T* tok)
{ {
if (!tok) if (!tok)
@ -489,7 +489,7 @@ static T* getCondTokImpl(T* tok)
return tok->next()->astOperand2(); return tok->next()->astOperand2();
} }
template <class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*>)> template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokFromEndImpl(T* endBlock) static T* getCondTokFromEndImpl(T* endBlock)
{ {
if (!Token::simpleMatch(endBlock, "}")) if (!Token::simpleMatch(endBlock, "}"))
@ -1065,7 +1065,7 @@ bool isSameExpression(bool cpp, bool macro, const Token *tok1, const Token *tok2
return isSameExpression(cpp, macro, refTok1, refTok2, library, pure, followVar, errors); return isSameExpression(cpp, macro, refTok1, refTok2, library, pure, followVar, errors);
} }
if (tok1->varId() != tok2->varId() || tok1->str() != tok2->str() || tok1->originalName() != tok2->originalName()) { if (tok1->varId() != tok2->varId() || tok1->str() != tok2->str() || tok1->originalName() != tok2->originalName()) {
if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) || if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) ||
(Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) { (Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) {
return isSameExpression(cpp, macro, tok1->astOperand1(), tok2->astOperand2(), library, pure, followVar, errors) && return isSameExpression(cpp, macro, tok1->astOperand1(), tok2->astOperand2(), library, pure, followVar, errors) &&
isSameExpression(cpp, macro, tok1->astOperand2(), tok2->astOperand1(), library, pure, followVar, errors); isSameExpression(cpp, macro, tok1->astOperand2(), tok2->astOperand1(), library, pure, followVar, errors);
@ -1244,10 +1244,10 @@ bool isOppositeCond(bool isNot, bool cpp, const Token * const cond1, const Token
if (!isNot && cond1->str() == "&&" && cond2->str() == "&&") { if (!isNot && cond1->str() == "&&" && cond2->str() == "&&") {
for (const Token* tok1: { for (const Token* tok1: {
cond1->astOperand1(), cond1->astOperand2() cond1->astOperand1(), cond1->astOperand2()
}) { }) {
for (const Token* tok2: { for (const Token* tok2: {
cond2->astOperand1(), cond2->astOperand2() cond2->astOperand1(), cond2->astOperand2()
}) { }) {
if (isSameExpression(cpp, true, tok1, tok2, library, pure, followVar, errors)) { if (isSameExpression(cpp, true, tok1, tok2, library, pure, followVar, errors)) {
if (isOppositeCond(isNot, cpp, tok1->astSibling(), tok2->astSibling(), library, pure, followVar, errors)) if (isOppositeCond(isNot, cpp, tok1->astSibling(), tok2->astSibling(), library, pure, followVar, errors))
@ -1372,15 +1372,15 @@ bool isOppositeCond(bool isNot, bool cpp, const Token * const cond1, const Token
// is condition opposite? // is condition opposite?
return ((comp1 == "==" && comp2 == "!=") || return ((comp1 == "==" && comp2 == "!=") ||
(comp1 == "!=" && comp2 == "==") || (comp1 == "!=" && comp2 == "==") ||
(comp1 == "<" && comp2 == ">=") || (comp1 == "<" && comp2 == ">=") ||
(comp1 == "<=" && comp2 == ">") || (comp1 == "<=" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<=") || (comp1 == ">" && comp2 == "<=") ||
(comp1 == ">=" && comp2 == "<") || (comp1 == ">=" && comp2 == "<") ||
(!isNot && ((comp1 == "<" && comp2 == ">") || (!isNot && ((comp1 == "<" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<") || (comp1 == ">" && comp2 == "<") ||
(comp1 == "==" && (comp2 == "!=" || comp2 == ">" || comp2 == "<")) || (comp1 == "==" && (comp2 == "!=" || comp2 == ">" || comp2 == "<")) ||
((comp1 == "!=" || comp1 == ">" || comp1 == "<") && comp2 == "==") ((comp1 == "!=" || comp1 == ">" || comp1 == "<") && comp2 == "==")
))); )));
} }
bool isOppositeExpression(bool cpp, const Token * const tok1, const Token * const tok2, const Library& library, bool pure, bool followVar, ErrorPath* errors) bool isOppositeExpression(bool cpp, const Token * const tok1, const Token * const tok2, const Library& library, bool pure, bool followVar, ErrorPath* errors)
@ -1425,7 +1425,7 @@ bool isConstFunctionCall(const Token* ftok, const Library& library)
if (!Function::returnsConst(f)) { if (!Function::returnsConst(f)) {
std::vector<const Function*> fs = f->getOverloadedFunctions(); std::vector<const Function*> fs = f->getOverloadedFunctions();
if (std::any_of(fs.begin(), fs.end(), [&](const Function* g) { if (std::any_of(fs.begin(), fs.end(), [&](const Function* g) {
if (f == g) if (f == g)
return false; return false;
if (f->argumentList.size() != g->argumentList.size()) if (f->argumentList.size() != g->argumentList.size())
return false; return false;
@ -1435,7 +1435,7 @@ bool isConstFunctionCall(const Token* ftok, const Library& library)
return true; return true;
return false; return false;
})) }))
return true; return true;
} }
return false; return false;
} else if (f->argumentList.empty()) { } else if (f->argumentList.empty()) {
@ -1551,11 +1551,11 @@ bool isUniqueExpression(const Token* tok)
if (varType) if (varType)
return v.type() && v.type()->name() == varType->name() && v.name() != var->name(); return v.type() && v.type()->name() == varType->name() && v.name() != var->name();
return v.isFloatingType() == var->isFloatingType() && return v.isFloatingType() == var->isFloatingType() &&
v.isEnumType() == var->isEnumType() && v.isEnumType() == var->isEnumType() &&
v.isClass() == var->isClass() && v.isClass() == var->isClass() &&
v.isArray() == var->isArray() && v.isArray() == var->isArray() &&
v.isPointer() == var->isPointer() && v.isPointer() == var->isPointer() &&
v.name() != var->name(); v.name() != var->name();
}); });
if (other) if (other)
return false; return false;
@ -2102,7 +2102,9 @@ Token* findVariableChanged(Token *start, const Token *end, int indirect, const n
return nullptr; return nullptr;
if (depth < 0) if (depth < 0)
return start; return start;
auto getExprTok = memoize([&] { return findExpression(start, exprid); }); auto getExprTok = memoize([&] {
return findExpression(start, exprid);
});
for (Token *tok = start; tok != end; tok = tok->next()) { for (Token *tok = start; tok != end; tok = tok->next()) {
if (tok->exprId() != exprid) { if (tok->exprId() != exprid) {
if (globalvar && Token::Match(tok, "%name% (")) if (globalvar && Token::Match(tok, "%name% ("))
@ -2279,7 +2281,7 @@ const Token *findLambdaStartToken(const Token *last)
return nullptr; return nullptr;
} }
template <class T> template<class T>
T* findLambdaEndTokenGeneric(T* first) T* findLambdaEndTokenGeneric(T* first)
{ {
if (!first || first->str() != "[") if (!first || first->str() != "[")
@ -2548,7 +2550,7 @@ bool isGlobalData(const Token *expr, bool cpp)
bool globalData = false; bool globalData = false;
bool var = false; bool var = false;
visitAstNodes(expr, visitAstNodes(expr,
[expr, cpp, &globalData, &var](const Token *tok) { [expr, cpp, &globalData, &var](const Token *tok) {
if (tok->varId()) if (tok->varId())
var = true; var = true;
if (tok->varId() && !tok->variable()) { if (tok->varId() && !tok->variable()) {
@ -2905,7 +2907,7 @@ static bool hasVolatileCastOrVar(const Token *expr)
{ {
bool ret = false; bool ret = false;
visitAstNodes(expr, visitAstNodes(expr,
[&ret](const Token *tok) { [&ret](const Token *tok) {
if (Token::simpleMatch(tok, "( volatile")) if (Token::simpleMatch(tok, "( volatile"))
ret = true; ret = true;
else if (tok->variable() && tok->variable()->isVolatile()) else if (tok->variable() && tok->variable()->isVolatile())
@ -2927,7 +2929,7 @@ std::set<nonneg int> FwdAnalysis::getExprVarIds(const Token* expr, bool* localOu
bool local = true; bool local = true;
bool unknownVarId = false; bool unknownVarId = false;
visitAstNodes(expr, visitAstNodes(expr,
[&](const Token *tok) { [&](const Token *tok) {
if (tok->str() == "[" && mWhat == What::UnusedValue) if (tok->str() == "[" && mWhat == What::UnusedValue)
return ChildrenToVisit::op1; return ChildrenToVisit::op1;
if (tok->varId() == 0 && tok->isName() && tok->previous()->str() != ".") { if (tok->varId() == 0 && tok->isName() && tok->previous()->str() != ".") {

View File

@ -62,8 +62,7 @@ public:
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
Check(const std::string &aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) Check(const std::string &aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger), mName(aname) { : mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger), mName(aname) {}
}
virtual ~Check() { virtual ~Check() {
if (!mTokenizer) if (!mTokenizer)
@ -116,7 +115,7 @@ public:
} }
// Return true if an error is reported. // Return true if an error is reported.
virtual bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<FileInfo*> &fileInfo, const Settings& /*settings*/, ErrorLogger &/*errorLogger*/) { virtual bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<FileInfo*> &fileInfo, const Settings& /*settings*/, ErrorLogger & /*errorLogger*/) {
(void)ctu; (void)ctu;
(void)fileInfo; (void)fileInfo;
//(void)settings; //(void)settings;

View File

@ -43,13 +43,11 @@ class Tokenizer;
class CPPCHECKLIB Check64BitPortability : public Check { class CPPCHECKLIB Check64BitPortability : public Check {
public: public:
/** This constructor is used when registering the Check64BitPortability */ /** This constructor is used when registering the Check64BitPortability */
Check64BitPortability() : Check(myName()) { Check64BitPortability() : Check(myName()) {}
}
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
Check64BitPortability(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) Check64BitPortability(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
/** @brief Run checks against the normal token list */ /** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {

View File

@ -42,12 +42,10 @@ class Tokenizer;
class CPPCHECKLIB CheckAssert : public Check { class CPPCHECKLIB CheckAssert : public Check {
public: public:
CheckAssert() : Check(myName()) { CheckAssert() : Check(myName()) {}
}
CheckAssert(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckAssert(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
/** run checks, the token list is not simplified */ /** run checks, the token list is not simplified */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {

View File

@ -42,13 +42,11 @@ class Variable;
class CPPCHECKLIB CheckAutoVariables : public Check { class CPPCHECKLIB CheckAutoVariables : public Check {
public: public:
/** This constructor is used when registering the CheckClass */ /** This constructor is used when registering the CheckClass */
CheckAutoVariables() : Check(myName()) { CheckAutoVariables() : Check(myName()) {}
}
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
/** @brief Run checks against the normal token list */ /** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {

View File

@ -69,7 +69,7 @@ void CheckBool::incrementBooleanError(const Token *tok)
"Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n" "Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n"
"The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value 'true' instead.", "The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value 'true' instead.",
CWE398, Certainty::normal CWE398, Certainty::normal
); );
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

View File

@ -41,13 +41,11 @@ class Tokenizer;
class CPPCHECKLIB CheckBool : public Check { class CPPCHECKLIB CheckBool : public Check {
public: public:
/** @brief This constructor is used when registering the CheckClass */ /** @brief This constructor is used when registering the CheckClass */
CheckBool() : Check(myName()) { CheckBool() : Check(myName()) {}
}
/** @brief This constructor is used when running checks. */ /** @brief This constructor is used when running checks. */
CheckBool(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckBool(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
/** @brief Run checks against the normal token list */ /** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {

View File

@ -58,5 +58,5 @@ void CheckBoost::boostForeachError(const Token *tok)
{ {
reportError(tok, Severity::error, "boostForeachError", reportError(tok, Severity::error, "boostForeachError",
"BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.", CWE664, Certainty::normal "BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.", CWE664, Certainty::normal
); );
} }

View File

@ -40,13 +40,11 @@ class Token;
class CPPCHECKLIB CheckBoost : public Check { class CPPCHECKLIB CheckBoost : public Check {
public: public:
/** This constructor is used when registering the CheckClass */ /** This constructor is used when registering the CheckClass */
CheckBoost() : Check(myName()) { CheckBoost() : Check(myName()) {}
}
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
CheckBoost(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckBoost(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
/** @brief Run checks against the normal token list */ /** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {

View File

@ -191,7 +191,7 @@ static bool getDimensionsEtc(const Token * const arrayToken, const Settings *set
*dimensions = array->variable()->dimensions(); *dimensions = array->variable()->dimensions();
if (dimensions->size() >= 1 && ((*dimensions)[0].num <= 1 || !(*dimensions)[0].tok)) { if (dimensions->size() >= 1 && ((*dimensions)[0].num <= 1 || !(*dimensions)[0].tok)) {
visitAstNodes(arrayToken, visitAstNodes(arrayToken,
[&](const Token *child) { [&](const Token *child) {
if (child->originalName() == "->") { if (child->originalName() == "->") {
*mightBeLarger = true; *mightBeLarger = true;
return ChildrenToVisit::none; return ChildrenToVisit::none;
@ -940,14 +940,14 @@ void CheckBufferOverrun::objectIndex()
std::copy_if(idx->values().begin(), std::copy_if(idx->values().begin(),
idx->values().end(), idx->values().end(),
std::back_inserter(idxValues), std::back_inserter(idxValues),
[&](const ValueFlow::Value& vidx) { [&](const ValueFlow::Value& vidx) {
if (!vidx.isIntValue()) if (!vidx.isIntValue())
return false; return false;
return vidx.path == v.path || vidx.path == 0; return vidx.path == v.path || vidx.path == 0;
}); });
if (idxValues.empty() || if (idxValues.empty() ||
std::any_of(idxValues.begin(), idxValues.end(), [&](const ValueFlow::Value& vidx) { std::any_of(idxValues.begin(), idxValues.end(), [&](const ValueFlow::Value& vidx) {
if (vidx.isImpossible()) if (vidx.isImpossible())
return (vidx.intvalue == 0); return (vidx.intvalue == 0);
else else
return (vidx.intvalue != 0); return (vidx.intvalue != 0);

View File

@ -60,13 +60,11 @@ class CPPCHECKLIB CheckBufferOverrun : public Check {
public: public:
/** This constructor is used when registering the CheckClass */ /** This constructor is used when registering the CheckClass */
CheckBufferOverrun() : Check(myName()) { CheckBufferOverrun() : Check(myName()) {}
}
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {
CheckBufferOverrun checkBufferOverrun(tokenizer, settings, errorLogger); CheckBufferOverrun checkBufferOverrun(tokenizer, settings, errorLogger);

View File

@ -105,10 +105,8 @@ static bool isVclTypeInit(const Type *type)
CheckClass::CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckClass::CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), : Check(myName(), tokenizer, settings, errorLogger),
mSymbolDatabase(tokenizer?tokenizer->getSymbolDatabase():nullptr) mSymbolDatabase(tokenizer?tokenizer->getSymbolDatabase():nullptr)
{ {}
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// ClassCheck: Check that all class constructors are ok. // ClassCheck: Check that all class constructors are ok.
@ -458,23 +456,23 @@ void CheckClass::copyconstructors()
copyConstructorShallowCopyError(cv, cv->str()); copyConstructorShallowCopyError(cv, cv->str());
// throw error if count mismatch // throw error if count mismatch
/* FIXME: This doesn't work. See #4154 /* FIXME: This doesn't work. See #4154
for (std::map<int, const Token*>::const_iterator i = allocatedVars.begin(); i != allocatedVars.end(); ++i) { for (std::map<int, const Token*>::const_iterator i = allocatedVars.begin(); i != allocatedVars.end(); ++i) {
copyConstructorMallocError(copyCtor, i->second, i->second->str()); copyConstructorMallocError(copyCtor, i->second, i->second->str());
} }
*/ */
} }
} }
} }
/* This doesn't work. See #4154 /* This doesn't work. See #4154
void CheckClass::copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& varname) void CheckClass::copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& varname)
{ {
std::list<const Token*> callstack; std::list<const Token*> callstack;
callstack.push_back(cctor); callstack.push_back(cctor);
callstack.push_back(alloc); callstack.push_back(alloc);
reportError(callstack, Severity::warning, "copyCtorNoAllocation", "Copy constructor does not allocate memory for member '" + varname + "' although memory has been allocated in other constructors."); reportError(callstack, Severity::warning, "copyCtorNoAllocation", "Copy constructor does not allocate memory for member '" + varname + "' although memory has been allocated in other constructors.");
} }
*/ */
void CheckClass::copyConstructorShallowCopyError(const Token *tok, const std::string& varname) void CheckClass::copyConstructorShallowCopyError(const Token *tok, const std::string& varname)
{ {
@ -1034,7 +1032,7 @@ void CheckClass::initializationListUsage()
// Access local var member in rhs => do not warn // Access local var member in rhs => do not warn
bool localmember = false; bool localmember = false;
visitAstNodes(tok->next()->astOperand2(), visitAstNodes(tok->next()->astOperand2(),
[&](const Token *rhs) { [&](const Token *rhs) {
if (rhs->str() == "." && rhs->astOperand1() && rhs->astOperand1()->variable() && rhs->astOperand1()->variable()->isLocal()) if (rhs->str() == "." && rhs->astOperand1() && rhs->astOperand1()->variable() && rhs->astOperand1()->variable()->isLocal())
localmember = true; localmember = true;
return ChildrenToVisit::op1_and_op2; return ChildrenToVisit::op1_and_op2;
@ -1044,7 +1042,7 @@ void CheckClass::initializationListUsage()
bool allowed = true; bool allowed = true;
visitAstNodes(tok->next()->astOperand2(), visitAstNodes(tok->next()->astOperand2(),
[&](const Token *tok2) { [&](const Token *tok2) {
const Variable* var2 = tok2->variable(); const Variable* var2 = tok2->variable();
if (var2) { if (var2) {
if (var2->scope() == owner && tok2->strAt(-1)!=".") { // Is there a dependency between two member variables? if (var2->scope() == owner && tok2->strAt(-1)!=".") { // Is there a dependency between two member variables?
@ -1111,7 +1109,7 @@ static bool checkFunctionUsage(const Function *privfunc, const Scope* scope)
} }
const std::map<std::string, Type*>::const_iterator end = scope->definedTypesMap.end(); const std::map<std::string, Type*>::const_iterator end = scope->definedTypesMap.end();
for (std::map<std::string, Type*>::const_iterator iter = scope->definedTypesMap.begin(); iter != end; ++ iter) { for (std::map<std::string, Type*>::const_iterator iter = scope->definedTypesMap.begin(); iter != end; ++iter) {
const Type *type = (*iter).second; const Type *type = (*iter).second;
if (type->enclosingScope == scope && checkFunctionUsage(privfunc, type->classScope)) if (type->enclosingScope == scope && checkFunctionUsage(privfunc, type->classScope))
return true; return true;
@ -1643,7 +1641,7 @@ CheckClass::Bool CheckClass::isInverted(const Token *tok, const Token *rhs)
if (Token::simpleMatch(itr, "!=") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) { if (Token::simpleMatch(itr, "!=") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) {
res = !res; res = !res;
} else if (Token::simpleMatch(itr, "!=") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size())) } else if (Token::simpleMatch(itr, "!=") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size()))
|| (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) { || (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) {
res = !res; res = !res;
} else if (Token::simpleMatch(itr, "!=") && (isFalseKeyword(itr->astOperand1()) || isFalseKeyword(itr->astOperand2()))) { } else if (Token::simpleMatch(itr, "!=") && (isFalseKeyword(itr->astOperand1()) || isFalseKeyword(itr->astOperand2()))) {
//Do nothing //Do nothing
@ -1654,7 +1652,7 @@ CheckClass::Bool CheckClass::isInverted(const Token *tok, const Token *rhs)
} else if (Token::simpleMatch(itr, "==") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) { } else if (Token::simpleMatch(itr, "==") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) {
//Do nothing //Do nothing
} else if (Token::simpleMatch(itr, "==") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size())) } else if (Token::simpleMatch(itr, "==") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size()))
|| (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) { || (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) {
//Do nothing //Do nothing
} else { } else {
return Bool::BAILOUT; return Bool::BAILOUT;
@ -1692,7 +1690,7 @@ bool CheckClass::hasAssignSelf(const Function *func, const Token *rhs, const Tok
bool ret = false; bool ret = false;
visitAstNodes(tok->next()->astOperand2(), visitAstNodes(tok->next()->astOperand2(),
[&](const Token *tok2) { [&](const Token *tok2) {
if (!Token::Match(tok2, "==|!=")) if (!Token::Match(tok2, "==|!="))
return ChildrenToVisit::op1_and_op2; return ChildrenToVisit::op1_and_op2;
if (Token::simpleMatch(tok2->astOperand1(), "this")) if (Token::simpleMatch(tok2->astOperand1(), "this"))
@ -2296,7 +2294,7 @@ void CheckClass::checkConstError2(const Token *tok1, const Token *tok2, const st
namespace { // avoid one-definition-rule violation namespace { // avoid one-definition-rule violation
struct VarInfo { struct VarInfo {
VarInfo(const Variable *_var, const Token *_tok) VarInfo(const Variable *_var, const Token *_tok)
: var(_var), tok(_tok) { } : var(_var), tok(_tok) {}
const Variable *var; const Variable *var;
const Token *tok; const Token *tok;
@ -2406,9 +2404,9 @@ void CheckClass::selfInitializationError(const Token* tok, const std::string& va
void CheckClass::checkVirtualFunctionCallInConstructor() void CheckClass::checkVirtualFunctionCallInConstructor()
{ {
if (! mSettings->severity.isEnabled(Severity::warning)) if (!mSettings->severity.isEnabled(Severity::warning))
return; return;
std::map<const Function *, std::list<const Token *> > virtualFunctionCallsMap; std::map<const Function *, std::list<const Token *>> virtualFunctionCallsMap;
for (const Scope *scope : mSymbolDatabase->functionScopes) { for (const Scope *scope : mSymbolDatabase->functionScopes) {
if (scope->function == nullptr || !scope->function->hasBody() || if (scope->function == nullptr || !scope->function->hasBody() ||
!(scope->function->isConstructor() || !(scope->function->isConstructor() ||
@ -2432,9 +2430,9 @@ void CheckClass::checkVirtualFunctionCallInConstructor()
} }
const std::list<const Token *> & CheckClass::getVirtualFunctionCalls(const Function & function, const std::list<const Token *> & CheckClass::getVirtualFunctionCalls(const Function & function,
std::map<const Function *, std::list<const Token *> > & virtualFunctionCallsMap) std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap)
{ {
const std::map<const Function *, std::list<const Token *> >::const_iterator found = virtualFunctionCallsMap.find(&function); const std::map<const Function *, std::list<const Token *>>::const_iterator found = virtualFunctionCallsMap.find(&function);
if (found != virtualFunctionCallsMap.end()) if (found != virtualFunctionCallsMap.end())
return found->second; return found->second;
@ -2489,7 +2487,7 @@ const std::list<const Token *> & CheckClass::getVirtualFunctionCalls(const Funct
} }
void CheckClass::getFirstVirtualFunctionCallStack( void CheckClass::getFirstVirtualFunctionCallStack(
std::map<const Function *, std::list<const Token *> > & virtualFunctionCallsMap, std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap,
const Token * callToken, const Token * callToken,
std::list<const Token *> & pureFuncStack) std::list<const Token *> & pureFuncStack)
{ {
@ -2498,7 +2496,7 @@ void CheckClass::getFirstVirtualFunctionCallStack(
pureFuncStack.push_back(callFunction->tokenDef); pureFuncStack.push_back(callFunction->tokenDef);
return; return;
} }
std::map<const Function *, std::list<const Token *> >::const_iterator found = virtualFunctionCallsMap.find(callFunction); std::map<const Function *, std::list<const Token *>>::const_iterator found = virtualFunctionCallsMap.find(callFunction);
if (found == virtualFunctionCallsMap.end() || found->second.empty()) { if (found == virtualFunctionCallsMap.end() || found->second.empty()) {
pureFuncStack.clear(); pureFuncStack.clear();
return; return;
@ -2604,8 +2602,8 @@ void CheckClass::checkDuplInheritedMembersRecursive(const Type* typeCurrent, con
} }
void CheckClass::duplInheritedMembersError(const Token *tok1, const Token* tok2, void CheckClass::duplInheritedMembersError(const Token *tok1, const Token* tok2,
const std::string &derivedName, const std::string &baseName, const std::string &derivedName, const std::string &baseName,
const std::string &variableName, bool derivedIsStruct, bool baseIsStruct) const std::string &variableName, bool derivedIsStruct, bool baseIsStruct)
{ {
ErrorPath errorPath; ErrorPath errorPath;
errorPath.emplace_back(tok2, "Parent variable '" + baseName + "::" + variableName + "'"); errorPath.emplace_back(tok2, "Parent variable '" + baseName + "::" + variableName + "'");
@ -2878,7 +2876,7 @@ Check::FileInfo *CheckClass::getFileInfo(const Tokenizer *tokenizer, const Setti
// the full definition must be compared // the full definition must be compared
bool fullDefinition = std::all_of(classScope->functionList.begin(), bool fullDefinition = std::all_of(classScope->functionList.begin(),
classScope->functionList.end(), classScope->functionList.end(),
[](const Function& f) { [](const Function& f) {
return f.hasBody(); return f.hasBody();
}); });
if (!fullDefinition) if (!fullDefinition)

View File

@ -44,8 +44,7 @@ class Token;
class CPPCHECKLIB CheckClass : public Check { class CPPCHECKLIB CheckClass : public Check {
public: public:
/** @brief This constructor is used when registering the CheckClass */ /** @brief This constructor is used when registering the CheckClass */
CheckClass() : Check(myName()), mSymbolDatabase(nullptr) { CheckClass() : Check(myName()), mSymbolDatabase(nullptr) {}
}
/** @brief This constructor is used when running checks. */ /** @brief This constructor is used when running checks. */
CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger); CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger);
@ -310,7 +309,7 @@ private:
// constructors helper function // constructors helper function
/** @brief Information about a member variable. Used when checking for uninitialized variables */ /** @brief Information about a member variable. Used when checking for uninitialized variables */
struct Usage { struct Usage {
explicit Usage(const Variable *var) : var(var), assign(false), init(false) { } explicit Usage(const Variable *var) : var(var), assign(false), init(false) {}
/** Variable that this usage is for */ /** Variable that this usage is for */
const Variable *var; const Variable *var;
@ -374,7 +373,7 @@ private:
*/ */
const std::list<const Token *> & getVirtualFunctionCalls( const std::list<const Token *> & getVirtualFunctionCalls(
const Function & function, const Function & function,
std::map<const Function *, std::list<const Token *> > & virtualFunctionCallsMap); std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap);
/** /**
* @brief looks for the first virtual function call stack * @brief looks for the first virtual function call stack
@ -383,7 +382,7 @@ private:
* @param[in,out] pureFuncStack list to append the stack * @param[in,out] pureFuncStack list to append the stack
*/ */
void getFirstVirtualFunctionCallStack( void getFirstVirtualFunctionCallStack(
std::map<const Function *, std::list<const Token *> > & virtualFunctionCallsMap, std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap,
const Token *callToken, const Token *callToken,
std::list<const Token *> & pureFuncStack); std::list<const Token *> & pureFuncStack);

View File

@ -596,7 +596,7 @@ void CheckCondition::multiCondition2()
bool nonlocal = false; // nonlocal variable used in condition bool nonlocal = false; // nonlocal variable used in condition
std::set<int> vars; // variables used in condition std::set<int> vars; // variables used in condition
visitAstNodes(condTok, visitAstNodes(condTok,
[&](const Token *cond) { [&](const Token *cond) {
if (Token::Match(cond, "%name% (")) { if (Token::Match(cond, "%name% (")) {
functionCall = true; functionCall = true;
nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library); nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library);
@ -628,7 +628,7 @@ void CheckCondition::multiCondition2()
std::vector<const Variable*> varsInCond; std::vector<const Variable*> varsInCond;
visitAstNodes(condTok, visitAstNodes(condTok,
[&varsInCond](const Token *cond) { [&varsInCond](const Token *cond) {
if (cond->variable()) { if (cond->variable()) {
const Variable *var = cond->variable(); const Variable *var = cond->variable();
if (std::find(varsInCond.begin(), varsInCond.end(), var) == varsInCond.end()) if (std::find(varsInCond.begin(), varsInCond.end(), var) == varsInCond.end())
@ -885,22 +885,22 @@ static std::string invertOperatorForOperandSwap(std::string s)
return s; return s;
} }
template <typename T> template<typename T>
static bool checkIntRelation(const std::string &op, const T value1, const T value2) static bool checkIntRelation(const std::string &op, const T value1, const T value2)
{ {
return (op == "==" && value1 == value2) || return (op == "==" && value1 == value2) ||
(op == "!=" && value1 != value2) || (op == "!=" && value1 != value2) ||
(op == ">" && value1 > value2) || (op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) || (op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) || (op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2); (op == "<=" && value1 <= value2);
} }
static bool checkFloatRelation(const std::string &op, const double value1, const double value2) static bool checkFloatRelation(const std::string &op, const double value1, const double value2)
{ {
return (op == ">" && value1 > value2) || return (op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) || (op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) || (op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2); (op == "<=" && value1 <= value2);
} }
@ -1172,7 +1172,7 @@ void CheckCondition::checkIncorrectLogicOperator()
const double d2 = (isfloat) ? MathLib::toDoubleNumber(value2) : 0; const double d2 = (isfloat) ? MathLib::toDoubleNumber(value2) : 0;
const MathLib::bigint i1 = (isfloat) ? 0 : MathLib::toLongNumber(value1); const MathLib::bigint i1 = (isfloat) ? 0 : MathLib::toLongNumber(value1);
const MathLib::bigint i2 = (isfloat) ? 0 : MathLib::toLongNumber(value2); const MathLib::bigint i2 = (isfloat) ? 0 : MathLib::toLongNumber(value2);
const bool useUnsignedInt = (std::numeric_limits<MathLib::bigint>::max()==i1)||(std::numeric_limits<MathLib::bigint>::max()==i2); const bool useUnsignedInt = (std::numeric_limits<MathLib::bigint>::max()==i1) || (std::numeric_limits<MathLib::bigint>::max()==i2);
const MathLib::biguint u1 = (useUnsignedInt) ? MathLib::toLongNumber(value1) : 0; const MathLib::biguint u1 = (useUnsignedInt) ? MathLib::toLongNumber(value1) : 0;
const MathLib::biguint u2 = (useUnsignedInt) ? MathLib::toLongNumber(value2) : 0; const MathLib::biguint u2 = (useUnsignedInt) ? MathLib::toLongNumber(value2) : 0;
// evaluate if expression is always true/false // evaluate if expression is always true/false

View File

@ -47,13 +47,11 @@ class ValueType;
class CPPCHECKLIB CheckCondition : public Check { class CPPCHECKLIB CheckCondition : public Check {
public: public:
/** This constructor is used when registering the CheckAssignIf */ /** This constructor is used when registering the CheckAssignIf */
CheckCondition() : Check(myName()) { CheckCondition() : Check(myName()) {}
}
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
CheckCondition(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) CheckCondition(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) { : Check(myName(), tokenizer, settings, errorLogger) {}
}
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE { void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) OVERRIDE {
CheckCondition checkCondition(tokenizer, settings, errorLogger); CheckCondition checkCondition(tokenizer, settings, errorLogger);

Some files were not shown because too many files have changed in this diff Show More