diff --git a/cli/cmdlineparser.cpp b/cli/cmdlineparser.cpp index 22837da9f..b5913edd3 100644 --- a/cli/cmdlineparser.cpp +++ b/cli/cmdlineparser.cpp @@ -47,22 +47,16 @@ static void AddFilesToList(const std::string& FileList, std::vector // drawback : creates a dependency std::istream *Files; std::ifstream Infile; - if (FileList.compare("-") == 0) // read from stdin - { + if (FileList.compare("-") == 0) { // read from stdin Files = &std::cin; - } - else - { + } else { Infile.open(FileList.c_str()); Files = &Infile; } - if (Files) - { + if (Files) { std::string FileName; - while (std::getline(*Files, FileName)) // next line - { - if (!FileName.empty()) - { + while (std::getline(*Files, FileName)) { // next line + if (!FileName.empty()) { PathNames.push_back(FileName); } } @@ -85,10 +79,8 @@ void CmdLineParser::PrintMessage(const std::string &message) bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) { - for (int i = 1; i < argc; i++) - { - if (strcmp(argv[i], "--version") == 0) - { + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--version") == 0) { _showVersion = true; _exitAfterPrint = true; return true; @@ -107,8 +99,7 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) _settings->debugFalsePositive = true; // Enable all checks - will be removed in future - else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--all") == 0) - { + else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--all") == 0) { PrintMessage("cppcheck: -a/--all option is deprecated and will be removed in 1.55 release."); PrintMessage("cppcheck: please use --enable=all instead."); } @@ -118,66 +109,56 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) _settings->inconclusive = true; // Checking coding style - will be removed in the future - else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--style") == 0) - { + else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--style") == 0) { PrintMessage("cppcheck: -s/--style option is deprecated and will be removed in 1.55 release."); PrintMessage("cppcheck: please use --enable=style instead."); const std::string errmsg = _settings->addEnabled("style"); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Filter errors - else if (strncmp(argv[i], "--exitcode-suppressions", 23) == 0) - { + else if (strncmp(argv[i], "--exitcode-suppressions", 23) == 0) { std::string filename; // exitcode-suppressions filename.txt // Deprecated - if (strcmp(argv[i], "--exitcode-suppressions") == 0) - { + if (strcmp(argv[i], "--exitcode-suppressions") == 0) { ++i; if (i >= argc || strncmp(argv[i], "-", 1) == 0 || - strncmp(argv[i], "--", 2) == 0) - { + strncmp(argv[i], "--", 2) == 0) { PrintMessage("cppcheck: No filename specified for the --exitcode-suppressions option"); return false; } filename = argv[i]; } // exitcode-suppressions=filename.txt - else - { + else { filename = 24 + argv[i]; } std::ifstream f(filename.c_str()); - if (!f.is_open()) - { + if (!f.is_open()) { PrintMessage("cppcheck: Couldn't open the file \"" + std::string(filename) + "\""); return false; } const std::string errmsg(_settings->nofail.parseFile(f)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Filter errors - else if (strncmp(argv[i], "--suppressions-list=", 20) == 0) - { + else if (strncmp(argv[i], "--suppressions-list=", 20) == 0) { std::string filename = argv[i]; filename = filename.substr(20); std::ifstream f(filename.c_str()); - if (!f.is_open()) - { + if (!f.is_open()) { std::string message("cppcheck: Couldn't open the file \""); message += std::string(filename); message += "\""; @@ -185,8 +166,7 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) return false; } const std::string errmsg(_settings->nomsg.parseFile(f)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } @@ -195,19 +175,16 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) // Filter errors // This is deprecated, see --supressions-list above else if (strcmp(argv[i], "--suppressions") == 0 && - strlen(argv[i]) == 14) - { + strlen(argv[i]) == 14) { ++i; - if (i >= argc) - { + if (i >= argc) { PrintMessage("cppcheck: No file specified for the --suppressions option"); return false; } std::ifstream f(argv[i]); - if (!f.is_open()) - { + if (!f.is_open()) { std::string message("cppcheck: Couldn't open the file \""); message += std::string(argv[i]); message += "\""; @@ -215,20 +192,17 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) return false; } const std::string errmsg(_settings->nomsg.parseFile(f)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } - else if (strncmp(argv[i], "--suppress=", 11) == 0) - { + else if (strncmp(argv[i], "--suppress=", 11) == 0) { std::string suppression = argv[i]; suppression = suppression.substr(11); const std::string errmsg(_settings->nomsg.addSuppressionLine(suppression)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } @@ -251,20 +225,17 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) _settings->_xml = true; // Define the XML file version (and enable XML output) - else if (strncmp(argv[i], "--xml-version=", 14) == 0) - { + else if (strncmp(argv[i], "--xml-version=", 14) == 0) { std::string numberString(argv[i]); numberString = numberString.substr(14); std::istringstream iss(numberString); - if (!(iss >> _settings->_xml_version)) - { + if (!(iss >> _settings->_xml_version)) { PrintMessage("cppcheck: argument to '--xml-version' is not a number"); return false; } - if (_settings->_xml_version < 0 || _settings->_xml_version > 2) - { + if (_settings->_xml_version < 0 || _settings->_xml_version > 2) { // We only have xml versions 1 and 2 PrintMessage("cppcheck: --xml-version can only be 1 or 2."); return false; @@ -282,30 +253,25 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) else if (strncmp(argv[i], "--append=", 9) == 0) _settings->append(9 + argv[i]); - else if (strncmp(argv[i], "--enable=", 9) == 0) - { + else if (strncmp(argv[i], "--enable=", 9) == 0) { const std::string errmsg = _settings->addEnabled(argv[i] + 9); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { PrintMessage(errmsg); return false; } // when "style" is enabled, also enable "performance" and "portability" - else if (strstr(argv[i]+9, "style")) - { + else if (strstr(argv[i]+9, "style")) { _settings->addEnabled("performance"); _settings->addEnabled("portability"); } } // --error-exitcode=1 - else if (strncmp(argv[i], "--error-exitcode=", 17) == 0) - { + else if (strncmp(argv[i], "--error-exitcode=", 17) == 0) { std::string temp = argv[i]; temp = temp.substr(17); std::istringstream iss(temp); - if (!(iss >> _settings->_exitCode)) - { + if (!(iss >> _settings->_exitCode)) { _settings->_exitCode = 0; PrintMessage("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'"); return false; @@ -313,17 +279,14 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // User define - else if (strncmp(argv[i], "-D", 2) == 0) - { + else if (strncmp(argv[i], "-D", 2) == 0) { std::string define; // "-D define" - if (strcmp(argv[i], "-D") == 0) - { + if (strcmp(argv[i], "-D") == 0) { ++i; if (i >= argc || strncmp(argv[i], "-", 1) == 0 || - strncmp(argv[i], "--", 2) == 0) - { + strncmp(argv[i], "--", 2) == 0) { PrintMessage("cppcheck: argument to '-D' is missing"); return false; } @@ -331,8 +294,7 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) define = argv[i]; } // "-Ddefine" - else - { + else { define = 2 + argv[i]; } @@ -342,16 +304,13 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // Include paths - else if (strncmp(argv[i], "-I", 2) == 0) - { + else if (strncmp(argv[i], "-I", 2) == 0) { std::string path; // "-I path/" - if (strcmp(argv[i], "-I") == 0) - { + if (strcmp(argv[i], "-I") == 0) { ++i; - if (i >= argc) - { + if (i >= argc) { PrintMessage("cppcheck: argument to '-I' is missing"); return false; } @@ -359,8 +318,7 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // "-Ipath/" - else - { + else { path = 2 + argv[i]; } path = Path::fromNativeSeparators(path); @@ -374,23 +332,19 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // file list specified - else if (strncmp(argv[i], "--file-list=", 12) == 0) - { + else if (strncmp(argv[i], "--file-list=", 12) == 0) { // open this file and read every input file (1 file name per line) AddFilesToList(12 + argv[i], _pathnames); } // Ignored paths - else if (strncmp(argv[i], "-i", 2) == 0) - { + else if (strncmp(argv[i], "-i", 2) == 0) { std::string path; // "-i path/" - if (strcmp(argv[i], "-i") == 0) - { + if (strcmp(argv[i], "-i") == 0) { ++i; - if (i >= argc) - { + if (i >= argc) { PrintMessage("cppcheck: argument to '-i' is missing"); return false; } @@ -398,19 +352,16 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // "-ipath/" - else - { + else { path = 2 + argv[i]; } - if (!path.empty()) - { + if (!path.empty()) { path = Path::fromNativeSeparators(path); path = Path::simplifyPath(path.c_str()); path = Path::removeQuotationMarks(path); - if (!FileLister::fileExists(path) && FileLister::isDirectory(path)) - { + if (!FileLister::fileExists(path) && FileLister::isDirectory(path)) { // If directory name doesn't end with / or \, add it if (path[path.length()-1] != '/') path += '/'; @@ -420,30 +371,25 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // Report progress - else if (strcmp(argv[i], "--report-progress") == 0) - { + else if (strcmp(argv[i], "--report-progress") == 0) { _settings->reportProgress = true; } // --std - else if (strcmp(argv[i], "--std=posix") == 0) - { + else if (strcmp(argv[i], "--std=posix") == 0) { _settings->posix = true; } // --C99 - else if (strcmp(argv[i], "--std=c99") == 0) - { + else if (strcmp(argv[i], "--std=c99") == 0) { _settings->c99 = true; } // Output formatter - else if (strcmp(argv[i], "--template") == 0) - { + else if (strcmp(argv[i], "--template") == 0) { // "--template path/" ++i; - if (i >= argc) - { + if (i >= argc) { PrintMessage("cppcheck: argument to '--template' is missing"); return false; } @@ -457,16 +403,13 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) // Checking threads else if (strcmp(argv[i], "-j") == 0 || - strncmp(argv[i], "-j", 2) == 0) - { + strncmp(argv[i], "-j", 2) == 0) { std::string numberString; // "-j 3" - if (strcmp(argv[i], "-j") == 0) - { + if (strcmp(argv[i], "-j") == 0) { ++i; - if (i >= argc) - { + if (i >= argc) { PrintMessage("cppcheck: argument to '-j' is missing"); return false; } @@ -475,21 +418,18 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // "-j3" - else if (strncmp(argv[i], "-j", 2) == 0) - { + else if (strncmp(argv[i], "-j", 2) == 0) { numberString = argv[i]; numberString = numberString.substr(2); } std::istringstream iss(numberString); - if (!(iss >> _settings->_jobs)) - { + if (!(iss >> _settings->_jobs)) { PrintMessage("cppcheck: argument to '-j' is not a number"); return false; } - if (_settings->_jobs > 10000) - { + if (_settings->_jobs > 10000) { // This limit is here just to catch typos. If someone has // need for more jobs, this value should be increased. PrintMessage("cppcheck: argument for '-j' is allowed to be 10000 at max"); @@ -498,27 +438,23 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // deprecated: auto deallocated classes.. - else if (strcmp(argv[i], "--auto-dealloc") == 0) - { + else if (strcmp(argv[i], "--auto-dealloc") == 0) { ++i; PrintMessage("cppcheck: --auto-dealloc option is deprecated and will be removed in 1.55 release."); } // print all possible error messages.. - else if (strcmp(argv[i], "--errorlist") == 0) - { + else if (strcmp(argv[i], "--errorlist") == 0) { _showErrorMessages = true; _settings->_xml = true; _exitAfterPrint = true; } // documentation.. - else if (strcmp(argv[i], "--doc") == 0) - { + else if (strcmp(argv[i], "--doc") == 0) { std::ostringstream doc; // Get documentation.. - for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) - { + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { doc << "===" << (*it)->name() << "===\n" << (*it)->classInfo() << "\n\n"; } @@ -533,14 +469,12 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) // --test-2-pass Experimental 2-pass checking of files // This command line flag will be removed - else if (strcmp(argv[i], "--test-2-pass") == 0) - { + else if (strcmp(argv[i], "--test-2-pass") == 0) { _settings->test_2_pass = true; } // show timing information.. - else if (strncmp(argv[i], "--showtime=", 11) == 0) - { + else if (strncmp(argv[i], "--showtime=", 11) == 0) { const std::string showtimeMode = argv[i] + 11; if (showtimeMode == "file") _settings->_showtime = SHOWTIME_FILE; @@ -554,33 +488,27 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) #ifdef HAVE_RULES // Rule given at command line - else if (strncmp(argv[i], "--rule=", 7) == 0) - { + else if (strncmp(argv[i], "--rule=", 7) == 0) { Settings::Rule rule; rule.pattern = 7 + argv[i]; _settings->rules.push_back(rule); } // Rule file - else if (strncmp(argv[i], "--rule-file=", 12) == 0) - { + else if (strncmp(argv[i], "--rule-file=", 12) == 0) { TiXmlDocument doc; - if (doc.LoadFile(12+argv[i])) - { + if (doc.LoadFile(12+argv[i])) { TiXmlElement *node = doc.FirstChildElement(); - for (; node && node->ValueStr() == "rule"; node = node->NextSiblingElement()) - { + for (; node && node->ValueStr() == "rule"; node = node->NextSiblingElement()) { Settings::Rule rule; TiXmlElement *pattern = node->FirstChildElement("pattern"); - if (pattern) - { + if (pattern) { rule.pattern = pattern->GetText(); } TiXmlElement *message = node->FirstChildElement("message"); - if (message) - { + if (message) { TiXmlElement *severity = message->FirstChildElement("severity"); if (severity) rule.severity = severity->GetText(); @@ -602,14 +530,12 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) #endif // Check configuration - else if (strcmp(argv[i], "--check-config") == 0) - { + else if (strcmp(argv[i], "--check-config") == 0) { _settings->checkConfiguration = true; } // Specify platform - else if (strncmp(argv[i], "--platform=", 11) == 0) - { + else if (strncmp(argv[i], "--platform=", 11) == 0) { std::string platform(11+argv[i]); if (platform == "win32A") @@ -622,8 +548,7 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) _settings->platform(Settings::Unix32); else if (platform == "unix64") _settings->platform(Settings::Unix64); - else - { + else { std::string message("cppcheck: error: unrecognized platform\""); message += argv[i]; message += "\""; @@ -633,16 +558,14 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) } // Print help - else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) - { + else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { _pathnames.clear(); _showHelp = true; _exitAfterPrint = true; break; } - else if (strncmp(argv[i], "-", 1) == 0 || strncmp(argv[i], "--", 2) == 0) - { + else if (strncmp(argv[i], "-", 1) == 0 || strncmp(argv[i], "--", 2) == 0) { std::string message("cppcheck: error: unrecognized command line option \""); message += argv[i]; message += "\""; @@ -650,37 +573,32 @@ bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) return false; } - else - { + else { std::string path = Path::fromNativeSeparators(argv[i]); path = Path::removeQuotationMarks(path); _pathnames.push_back(path); } } - if (_settings->isEnabled("unusedFunction") && _settings->_jobs > 1) - { + if (_settings->isEnabled("unusedFunction") && _settings->_jobs > 1) { PrintMessage("cppcheck: unusedFunction check can't be used with -j option, so it was disabled."); } // FIXME: Make the _settings.test_2_pass thread safe - if (_settings->test_2_pass && _settings->_jobs > 1) - { + if (_settings->test_2_pass && _settings->_jobs > 1) { PrintMessage("cppcheck: --test-2-pass doesn't work with -j option yet."); } if (argc <= 1) _showHelp = true; - if (_showHelp) - { + if (_showHelp) { PrintHelp(); return true; } // Print error only if we have "real" command and expect files - if (!_exitAfterPrint && _pathnames.empty()) - { + if (!_exitAfterPrint && _pathnames.empty()) { PrintMessage("cppcheck: No C or C++ source files found."); return false; } diff --git a/cli/cmdlineparser.h b/cli/cmdlineparser.h index bfc047cb9..ef8c11c38 100644 --- a/cli/cmdlineparser.h +++ b/cli/cmdlineparser.h @@ -36,8 +36,7 @@ class Settings; * based on options user has given. Couple of options are handled as * class internal options. */ -class CmdLineParser -{ +class CmdLineParser { public: /** * The constructor. @@ -55,48 +54,42 @@ public: /** * Return if user wanted to see program version. */ - bool GetShowVersion() const - { + bool GetShowVersion() const { return _showVersion; } /** * Return if user wanted to see list of error messages. */ - bool GetShowErrorMessages() const - { + bool GetShowErrorMessages() const { return _showErrorMessages; } /** * Return the path names user gave to command line. */ - std::vector GetPathNames() const - { + std::vector GetPathNames() const { return _pathnames; } /** * Return if help is shown to user. */ - bool GetShowHelp() const - { + bool GetShowHelp() const { return _showHelp; } /** * Return if we should exit after printing version, help etc. */ - bool ExitAfterPrinting() const - { + bool ExitAfterPrinting() const { return _exitAfterPrint; } /** * Return a list of paths user wants to ignore. */ - std::vector GetIgnoredPaths() const - { + std::vector GetIgnoredPaths() const { return _ignoredPaths; } diff --git a/cli/cppcheckexecutor.cpp b/cli/cppcheckexecutor.cpp index 1a4b88fc5..9f73fc031 100644 --- a/cli/cppcheckexecutor.cpp +++ b/cli/cppcheckexecutor.cpp @@ -49,10 +49,8 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c bool success = parser.ParseFromArgs(argc, argv); cppcheck->settings(_settings); // copy the settings - if (success) - { - if (parser.GetShowVersion() && !parser.GetShowErrorMessages()) - { + if (success) { + if (parser.GetShowVersion() && !parser.GetShowErrorMessages()) { const char * extraVersion = cppcheck->extraVersion(); if (strlen(extraVersion) > 0) std::cout << "Cppcheck " << cppcheck->version() << " (" @@ -61,8 +59,7 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c std::cout << "Cppcheck " << cppcheck->version() << std::endl; } - if (parser.GetShowErrorMessages()) - { + if (parser.GetShowErrorMessages()) { errorlist = true; std::cout << ErrorLogger::ErrorMessage::getXMLHeader(_settings._xml_version); cppcheck->getErrorMessages(); @@ -78,13 +75,11 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c std::list::iterator iter; for (iter = _settings._includePaths.begin(); iter != _settings._includePaths.end(); - ) - { + ) { const std::string path(Path::toNativeSeparators(*iter)); if (FileLister::isDirectory(path)) ++iter; - else - { + else { // If the include path is not found, warn user and remove the // non-existing path from the list. std::cout << "cppcheck: warning: Couldn't find path given by -I '" + path + "'" << std::endl; @@ -97,30 +92,25 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c std::vector filenames; std::map filesizes; - if (!pathnames.empty()) - { + if (!pathnames.empty()) { // Execute recursiveAddFiles() to each given file parameter std::vector::const_iterator iter; for (iter = pathnames.begin(); iter != pathnames.end(); ++iter) FileLister::recursiveAddFiles(filenames, filesizes, Path::toNativeSeparators(*iter)); } - if (!filenames.empty()) - { + if (!filenames.empty()) { // Remove header files from the list of ignored files. // Also output a warning for the user. // TODO: Remove all unknown files? (use FileLister::acceptFile()) bool warned = false; std::vector ignored = parser.GetIgnoredPaths(); std::vector::iterator iterIgnored = ignored.begin(); - for (int i = (int)ignored.size() - 1; i >= 0; i--) - { + for (int i = (int)ignored.size() - 1; i >= 0; i--) { const std::string extension = Path::getFilenameExtension(ignored[i]); - if (extension == ".h" || extension == ".hpp") - { + if (extension == ".h" || extension == ".hpp") { ignored.erase(iterIgnored + i); - if (!warned) - { + if (!warned) { std::cout << "cppcheck: filename exclusion does not apply to header (.h and .hpp) files." << std::endl; std::cout << "cppcheck: Please use --suppress for ignoring results from the header files." << std::endl; warned = true; // Warn only once @@ -130,8 +120,7 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c PathMatch matcher(parser.GetIgnoredPaths()); std::vector::iterator iterBegin = filenames.begin(); - for (int i = (int)filenames.size() - 1; i >= 0; i--) - { + for (int i = (int)filenames.size() - 1; i >= 0; i--) { #if defined(_WIN32) // For Windows we want case-insensitive path matching const bool caseSensitive = false; @@ -141,26 +130,20 @@ bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* c if (matcher.Match(filenames[(unsigned int)i], caseSensitive)) filenames.erase(iterBegin + i); } - } - else - { + } else { std::cout << "cppcheck: error: could not find or open any of the paths given." << std::endl; return false; } - if (!filenames.empty()) - { + if (!filenames.empty()) { std::vector::iterator iter; - for (iter = filenames.begin(); iter != filenames.end(); ++iter) - { + for (iter = filenames.begin(); iter != filenames.end(); ++iter) { _filenames.push_back(*iter); _filesizes[*iter] = filesizes[*iter]; } return true; - } - else - { + } else { std::cout << "cppcheck: error: no files to check - all paths ignored." << std::endl; return false; } @@ -171,8 +154,7 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) Preprocessor::missingIncludeFlag = false; CppCheck cppCheck(*this, true); - if (!parseFromArgs(&cppCheck, argc, argv)) - { + if (!parseFromArgs(&cppCheck, argc, argv)) { return EXIT_FAILURE; } @@ -180,28 +162,23 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) time1 = std::time(0); _settings = cppCheck.settings(); - if (_settings._xml) - { + if (_settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLHeader(_settings._xml_version)); } unsigned int returnValue = 0; - if (_settings._jobs == 1) - { + if (_settings._jobs == 1) { // Single process long totalfilesize = 0; - for (std::map::const_iterator i = _filesizes.begin(); i != _filesizes.end(); ++i) - { + for (std::map::const_iterator i = _filesizes.begin(); i != _filesizes.end(); ++i) { totalfilesize += i->second; } long processedsize = 0; - for (unsigned int c = 0; c < _filenames.size(); c++) - { + for (unsigned int c = 0; c < _filenames.size(); c++) { returnValue += cppCheck.check(_filenames[c]); - if (_filesizes.find(_filenames[c]) != _filesizes.end()) - { + if (_filesizes.find(_filenames[c]) != _filesizes.end()) { processedsize += _filesizes[_filenames[c]]; } if (!_settings._errorsOnly) @@ -209,26 +186,20 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) } cppCheck.checkFunctionUsage(); - } - else if (!ThreadExecutor::isEnabled()) - { + } else if (!ThreadExecutor::isEnabled()) { std::cout << "No thread support yet implemented for this platform." << std::endl; - } - else - { + } else { // Multiple processes Settings &settings = cppCheck.settings(); ThreadExecutor executor(_filenames, _filesizes, settings, *this); returnValue = executor.check(); } - if (!cppCheck.settings().checkConfiguration) - { + if (!cppCheck.settings().checkConfiguration) { if (!_settings._errorsOnly) reportUnmatchedSuppressions(cppCheck.settings().nomsg.getUnmatchedGlobalSuppressions()); - if (Preprocessor::missingIncludeFlag) - { + if (Preprocessor::missingIncludeFlag) { const std::list callStack; ErrorLogger::ErrorMessage msg(callStack, Severity::information, @@ -244,8 +215,7 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) } } - if (_settings._xml) - { + if (_settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLFooter(_settings._xml_version)); } @@ -279,8 +249,7 @@ void CppCheckExecutor::reportProgress(const std::string &filename, const char st // Report progress messages every 10 seconds const std::time_t time2 = std::time(NULL); - if (time2 >= (time1 + 10)) - { + if (time2 >= (time1 + 10)) { time1 = time2; // current time in the format "Www Mmm dd hh:mm:ss yyyy" @@ -301,8 +270,7 @@ void CppCheckExecutor::reportProgress(const std::string &filename, const char st void CppCheckExecutor::reportStatus(unsigned int fileindex, unsigned int filecount, long sizedone, long sizetotal) { - if (filecount > 1) - { + if (filecount > 1) { std::ostringstream oss; oss << fileindex << "/" << filecount << " files checked " << @@ -314,16 +282,11 @@ void CppCheckExecutor::reportStatus(unsigned int fileindex, unsigned int filecou void CppCheckExecutor::reportErr(const ErrorLogger::ErrorMessage &msg) { - if (errorlist) - { + if (errorlist) { reportOut(msg.toXML(false, _settings._xml_version)); - } - else if (_settings._xml) - { + } else if (_settings._xml) { reportErr(msg.toXML(_settings._verbose, _settings._xml_version)); - } - else - { + } else { reportErr(msg.toString(_settings._verbose, _settings._outputFormat)); } } diff --git a/cli/cppcheckexecutor.h b/cli/cppcheckexecutor.h index 02945a461..01cb74f62 100644 --- a/cli/cppcheckexecutor.h +++ b/cli/cppcheckexecutor.h @@ -35,8 +35,7 @@ class CppCheck; * just rewrite this class for your needs and possibly use other methods * from CppCheck class instead the ones used here. */ -class CppCheckExecutor : public ErrorLogger -{ +class CppCheckExecutor : public ErrorLogger { public: /** * Constructor diff --git a/cli/filelister.cpp b/cli/filelister.cpp index eb6f35199..3ef3854ba 100644 --- a/cli/filelister.cpp +++ b/cli/filelister.cpp @@ -44,8 +44,7 @@ bool FileLister::acceptFile(const std::string &filename) extension == ".c" || extension == ".c++" || extension == ".tpp" || - extension == ".txx") - { + extension == ".txx") { return true; } @@ -153,11 +152,9 @@ void FileLister::recursiveAddFiles(std::vector &filenames, std::map oss << cleanedPath; - if (MyIsDirectory(cleanedPath.c_str())) - { + if (MyIsDirectory(cleanedPath.c_str())) { char c = cleanedPath[ cleanedPath.size()-1 ]; - switch (c) - { + switch (c) { case '\\': oss << '*'; bdir << cleanedPath; @@ -170,13 +167,10 @@ void FileLister::recursiveAddFiles(std::vector &filenames, std::map if (cleanedPath != ".") bdir << cleanedPath << '\\'; } - } - else - { + } else { std::string::size_type pos; pos = cleanedPath.find_last_of('\\'); - if (std::string::npos != pos) - { + if (std::string::npos != pos) { bdir << cleanedPath.substr(0, pos + 1); } } @@ -186,8 +180,7 @@ void FileLister::recursiveAddFiles(std::vector &filenames, std::map if (INVALID_HANDLE_VALUE == hFind) return; - do - { + do { if (ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0') continue; @@ -196,8 +189,7 @@ void FileLister::recursiveAddFiles(std::vector &filenames, std::map TransformUcs2ToAnsi(ffd.cFileName, ansiFfd, wcslen(ffd.cFileName) + 1); #else // defined(UNICODE) const char * ansiFfd = &ffd.cFileName[0]; - if (strchr(ansiFfd,'?')) - { + if (strchr(ansiFfd,'?')) { ansiFfd = &ffd.cAlternateFileName[0]; } #endif // defined(UNICODE) @@ -205,32 +197,26 @@ void FileLister::recursiveAddFiles(std::vector &filenames, std::map std::ostringstream fname; fname << bdir.str().c_str() << ansiFfd; - if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) - { + if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { // File // If recursive is not used, accept all files given by user - if (Path::sameFileName(path,ansiFfd) || FileLister::acceptFile(ansiFfd)) - { + if (Path::sameFileName(path,ansiFfd) || FileLister::acceptFile(ansiFfd)) { const std::string nativename = Path::fromNativeSeparators(fname.str()); filenames.push_back(nativename); // Limitation: file sizes are assumed to fit in a 'long' filesizes[nativename] = ffd.nFileSizeLow; } - } - else - { + } else { // Directory FileLister::recursiveAddFiles(filenames, filesizes, fname.str()); } #if defined(UNICODE) delete [] ansiFfd; #endif // defined(UNICODE) - } - while (FindNextFile(hFind, &ffd) != FALSE); + } while (FindNextFile(hFind, &ffd) != FALSE); - if (INVALID_HANDLE_VALUE != hFind) - { + if (INVALID_HANDLE_VALUE != hFind) { FindClose(hFind); hFind = INVALID_HANDLE_VALUE; } @@ -274,14 +260,12 @@ void FileLister::recursiveAddFiles2(std::vector &relative, glob_t glob_results; glob(oss.str().c_str(), GLOB_MARK, 0, &glob_results); - for (unsigned int i = 0; i < glob_results.gl_pathc; i++) - { + for (unsigned int i = 0; i < glob_results.gl_pathc; i++) { const std::string filename = glob_results.gl_pathv[i]; if (filename == "." || filename == ".." || filename.length() == 0) continue; - if (filename[filename.length()-1] != '/') - { + if (filename[filename.length()-1] != '/') { // File #ifdef PATH_MAX char fname[PATH_MAX]; @@ -295,21 +279,18 @@ void FileLister::recursiveAddFiles2(std::vector &relative, } // Does absolute path exist? then bail out - if (std::find(absolute.begin(), absolute.end(), std::string(fname)) != absolute.end()) - { + if (std::find(absolute.begin(), absolute.end(), std::string(fname)) != absolute.end()) { #ifndef PATH_MAX free(fname); #endif continue; } - if (Path::sameFileName(path,filename) || FileLister::acceptFile(filename)) - { + if (Path::sameFileName(path,filename) || FileLister::acceptFile(filename)) { relative.push_back(filename); absolute.push_back(fname); struct stat sb; - if (stat(fname, &sb) == 0) - { + if (stat(fname, &sb) == 0) { // Limitation: file sizes are assumed to fit in a 'long' filesizes[filename] = static_cast(sb.st_size); } @@ -318,9 +299,7 @@ void FileLister::recursiveAddFiles2(std::vector &relative, #ifndef PATH_MAX free(fname); #endif - } - else - { + } else { // Directory recursiveAddFiles2(relative, absolute, filesizes, filename); } @@ -341,11 +320,9 @@ bool FileLister::isDirectory(const std::string &path) glob_t glob_results; glob(path.c_str(), GLOB_MARK, 0, &glob_results); - if (glob_results.gl_pathc == 1) - { + if (glob_results.gl_pathc == 1) { const std::string glob_path = glob_results.gl_pathv[0]; - if (!glob_path.empty() && glob_path[glob_path.size() - 1] == '/') - { + if (!glob_path.empty() && glob_path[glob_path.size() - 1] == '/') { ret = true; } } @@ -359,8 +336,7 @@ bool FileLister::fileExists(const std::string &path) struct stat statinfo; int result = stat(path.c_str(), &statinfo); - if (result < 0) // Todo: should check errno == ENOENT? - { + if (result < 0) { // Todo: should check errno == ENOENT? // File not found return false; } diff --git a/cli/filelister.h b/cli/filelister.h index a4055113c..1d0d59b49 100644 --- a/cli/filelister.h +++ b/cli/filelister.h @@ -27,8 +27,7 @@ /// @{ /** @brief Cross-platform FileLister */ -class FileLister -{ +class FileLister { public: /** * @brief Recursively add source files to a vector. diff --git a/cli/pathmatch.cpp b/cli/pathmatch.cpp index 3c3eaf468..870cbfdea 100644 --- a/cli/pathmatch.cpp +++ b/cli/pathmatch.cpp @@ -30,8 +30,7 @@ bool PathMatch::Match(const std::string &path, bool caseSensitive) return false; std::vector::const_iterator iterMask; - for (iterMask = _masks.begin(); iterMask != _masks.end(); ++iterMask) - { + for (iterMask = _masks.begin(); iterMask != _masks.end(); ++iterMask) { std::string mask(*iterMask); if (!caseSensitive) std::transform(mask.begin(), mask.end(), mask.begin(), ::tolower); @@ -41,8 +40,7 @@ bool PathMatch::Match(const std::string &path, bool caseSensitive) std::transform(findpath.begin(), findpath.end(), findpath.begin(), ::tolower); // Filtering directory name - if (mask[mask.length() - 1] == '/') - { + if (mask[mask.length() - 1] == '/') { if (findpath[findpath.length() - 1] != '/') findpath = RemoveFilename(findpath); @@ -59,8 +57,7 @@ bool PathMatch::Match(const std::string &path, bool caseSensitive) return true; } // Filtering filename - else - { + else { if (mask.length() > findpath.length()) continue; // Check if path ends with mask diff --git a/cli/pathmatch.h b/cli/pathmatch.h index 179b1c317..9def070f8 100644 --- a/cli/pathmatch.h +++ b/cli/pathmatch.h @@ -28,8 +28,7 @@ /** * @brief Simple path matching for ignoring paths in CLI. */ -class PathMatch -{ +class PathMatch { public: /** diff --git a/cli/threadexecutor.cpp b/cli/threadexecutor.cpp index 11a23393b..9b980018f 100644 --- a/cli/threadexecutor.cpp +++ b/cli/threadexecutor.cpp @@ -59,64 +59,52 @@ void ThreadExecutor::addFileContent(const std::string &path, const std::string & int ThreadExecutor::handleRead(int rpipe, unsigned int &result) { char type = 0; - if (read(rpipe, &type, 1) <= 0) - { + if (read(rpipe, &type, 1) <= 0) { if (errno == EAGAIN) return 0; return -1; } - if (type != '1' && type != '2' && type != '3') - { + if (type != '1' && type != '2' && type != '3') { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } unsigned int len = 0; - if (read(rpipe, &len, sizeof(len)) <= 0) - { + if (read(rpipe, &len, sizeof(len)) <= 0) { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } char *buf = new char[len]; - if (read(rpipe, buf, len) <= 0) - { + if (read(rpipe, buf, len) <= 0) { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } - if (type == '1') - { + if (type == '1') { _errorLogger.reportOut(buf); - } - else if (type == '2') - { + } else if (type == '2') { ErrorLogger::ErrorMessage msg; msg.deserialize(buf); std::string file; unsigned int line(0); - if (!msg._callStack.empty()) - { + if (!msg._callStack.empty()) { file = msg._callStack.back().getfile(false); line = msg._callStack.back().line; } - if (!_settings.nomsg.isSuppressed(msg._id, file, line)) - { + if (!_settings.nomsg.isSuppressed(msg._id, file, line)) { // Alert only about unique errors std::string errmsg = msg.toString(_settings._verbose); - if (std::find(_errorList.begin(), _errorList.end(), errmsg) == _errorList.end()) - { + if (std::find(_errorList.begin(), _errorList.end(), errmsg) == _errorList.end()) { _errorList.push_back(errmsg); _errorLogger.reportErr(msg); } } - } - else if (type == '3') - { + } else if (type == '3') { std::istringstream iss(buf); unsigned int fileResult = 0; iss >> fileResult; @@ -135,8 +123,7 @@ unsigned int ThreadExecutor::check() unsigned int result = 0; long totalfilesize = 0; - for (std::map::const_iterator i = _filesizes.begin(); i != _filesizes.end(); ++i) - { + for (std::map::const_iterator i = _filesizes.begin(); i != _filesizes.end(); ++i) { totalfilesize += i->second; } @@ -145,40 +132,32 @@ unsigned int ThreadExecutor::check() std::map pipeFile; long processedsize = 0; unsigned int i = 0; - while (true) - { + while (true) { // Start a new child - if (i < _filenames.size() && rpipes.size() < _settings._jobs) - { + if (i < _filenames.size() && rpipes.size() < _settings._jobs) { int pipes[2]; - if (pipe(pipes) == -1) - { + if (pipe(pipes) == -1) { perror("pipe"); exit(1); } int flags = 0; - if ((flags = fcntl(pipes[0], F_GETFL, 0)) < 0) - { + if ((flags = fcntl(pipes[0], F_GETFL, 0)) < 0) { perror("fcntl"); exit(1); } - if (fcntl(pipes[0], F_SETFL, flags | O_NONBLOCK) < 0) - { + if (fcntl(pipes[0], F_SETFL, flags | O_NONBLOCK) < 0) { perror("fcntl"); exit(1); } pid_t pid = fork(); - if (pid < 0) - { + if (pid < 0) { // Error std::cerr << "Failed to create child process" << std::endl; exit(EXIT_FAILURE); - } - else if (pid == 0) - { + } else if (pid == 0) { close(pipes[0]); _wpipe = pipes[1]; @@ -186,13 +165,10 @@ unsigned int ThreadExecutor::check() fileChecker.settings(_settings); unsigned int resultOfCheck = 0; - if (_fileContents.size() > 0 && _fileContents.find(_filenames[i]) != _fileContents.end()) - { + if (_fileContents.size() > 0 && _fileContents.find(_filenames[i]) != _fileContents.end()) { // File content was given as a string resultOfCheck = fileChecker.check(_filenames[i], _fileContents[ _filenames[i] ]); - } - else - { + } else { // Read file from a file resultOfCheck = fileChecker.check(_filenames[i]); } @@ -209,9 +185,7 @@ unsigned int ThreadExecutor::check() pipeFile[pipes[0]] = _filenames[i]; ++i; - } - else if (!rpipes.empty()) - { + } else if (!rpipes.empty()) { fd_set rfds; FD_ZERO(&rfds); for (std::list::const_iterator rp = rpipes.begin(); rp != rpipes.end(); ++rp) @@ -219,25 +193,19 @@ unsigned int ThreadExecutor::check() int r = select(*std::max_element(rpipes.begin(), rpipes.end()) + 1, &rfds, NULL, NULL, NULL); - if (r > 0) - { + if (r > 0) { std::list::iterator rp = rpipes.begin(); - while (rp != rpipes.end()) - { - if (FD_ISSET(*rp, &rfds)) - { + while (rp != rpipes.end()) { + if (FD_ISSET(*rp, &rfds)) { int readRes = handleRead(*rp, result); - if (readRes == -1) - { + if (readRes == -1) { long size = 0; std::map::iterator p = pipeFile.find(*rp); - if (p != pipeFile.end()) - { + if (p != pipeFile.end()) { std::string name = p->second; pipeFile.erase(p); std::map::const_iterator fs = _filesizes.find(name); - if (fs != _filesizes.end()) - { + if (fs != _filesizes.end()) { size = fs->second; } } @@ -249,29 +217,24 @@ unsigned int ThreadExecutor::check() close(*rp); rp = rpipes.erase(rp); - } - else + } else ++rp; - } - else + } else ++rp; } } int stat = 0; pid_t child = waitpid(0, &stat, WNOHANG); - if (child > 0) - { + if (child > 0) { std::string childname; std::map::iterator c = childFile.find(child); - if (c != childFile.end()) - { + if (c != childFile.end()) { childname = c->second; childFile.erase(c); } - if (WIFSIGNALED(stat)) - { + if (WIFSIGNALED(stat)) { std::ostringstream oss; oss << "Internal error: Child process crashed with signal " << WTERMSIG(stat); @@ -287,9 +250,7 @@ unsigned int ThreadExecutor::check() _errorLogger.reportErr(errmsg); } } - } - else - { + } else { // All done break; } @@ -306,8 +267,7 @@ void ThreadExecutor::writeToPipe(char type, const std::string &data) out[0] = type; std::memcpy(&(out[1]), &len, sizeof(len)); std::memcpy(&(out[1+sizeof(len)]), data.c_str(), len); - if (write(_wpipe, out, len + 1 + sizeof(len)) <= 0) - { + if (write(_wpipe, out, len + 1 + sizeof(len)) <= 0) { delete [] out; out = 0; std::cerr << "#### ThreadExecutor::writeToPipe, Failed to write to pipe" << std::endl; diff --git a/cli/threadexecutor.h b/cli/threadexecutor.h index 8a29c6068..b4540e4c9 100644 --- a/cli/threadexecutor.h +++ b/cli/threadexecutor.h @@ -36,8 +36,7 @@ * This class will take a list of filenames and settings and check then * all files using threads. */ -class ThreadExecutor : public ErrorLogger -{ +class ThreadExecutor : public ErrorLogger { public: ThreadExecutor(const std::vector &filenames, const std::map &filesizes, Settings &settings, ErrorLogger &_errorLogger); virtual ~ThreadExecutor(); @@ -84,8 +83,7 @@ public: /** * @return true if support for threads exist. */ - static bool isEnabled() - { + static bool isEnabled() { return true; } #else @@ -93,8 +91,7 @@ public: /** * @return true if support for threads exist. */ - static bool isEnabled() - { + static bool isEnabled() { return false; } #endif diff --git a/gui/aboutdialog.cpp b/gui/aboutdialog.cpp index 41b45ae1c..20aaf1728 100644 --- a/gui/aboutdialog.cpp +++ b/gui/aboutdialog.cpp @@ -27,8 +27,7 @@ AboutDialog::AboutDialog(const QString &version, const QString &extraVersion, QW mUI.setupUi(this); QString fmtVersion(version); - if (!extraVersion.isEmpty()) - { + if (!extraVersion.isEmpty()) { fmtVersion += " (" + extraVersion + ")"; } mUI.mVersion->setText(mUI.mVersion->text().arg(fmtVersion)); diff --git a/gui/aboutdialog.h b/gui/aboutdialog.h index f8bc58c92..f3a222578 100644 --- a/gui/aboutdialog.h +++ b/gui/aboutdialog.h @@ -32,8 +32,7 @@ class QWidget; * @brief About dialog * */ -class AboutDialog : public QDialog -{ +class AboutDialog : public QDialog { Q_OBJECT public: AboutDialog(const QString &version, const QString &extraVersion, diff --git a/gui/application.h b/gui/application.h index 5e6d7b56a..f3f724614 100644 --- a/gui/application.h +++ b/gui/application.h @@ -40,8 +40,7 @@ * Executable: kate * Parameters: -l(line) (file) */ -class Application -{ +class Application { public: Application() { } Application(const QString &name, const QString &path, const QString ¶ms); @@ -50,8 +49,7 @@ public: * @brief Get application name. * @return Application name. */ - QString getName() const - { + QString getName() const { return mName; } @@ -59,8 +57,7 @@ public: * @brief Get application path. * @return Application path. */ - QString getPath() const - { + QString getPath() const { return mPath; } @@ -68,8 +65,7 @@ public: * @brief Get application command line parameters. * @return Application command line parameters. */ - QString getParameters() const - { + QString getParameters() const { return mParameters; } @@ -77,8 +73,7 @@ public: * @brief Set application name. * @param name Application name. */ - void setName(const QString &name) - { + void setName(const QString &name) { mName = name; } @@ -86,8 +81,7 @@ public: * @brief Set application path. * @param path Application path. */ - void setPath(const QString &path) - { + void setPath(const QString &path) { mPath = path; } @@ -95,8 +89,7 @@ public: * @brief Set application command line parameters. * @param parameters Application command line parameters. */ - void setParameters(const QString ¶meters) - { + void setParameters(const QString ¶meters) { mParameters = parameters; } diff --git a/gui/applicationdialog.cpp b/gui/applicationdialog.cpp index 9f7fb685c..5cf9c4ef7 100644 --- a/gui/applicationdialog.cpp +++ b/gui/applicationdialog.cpp @@ -62,8 +62,7 @@ void ApplicationDialog::Browse() QString(), filter); - if (!selectedFile.isEmpty()) - { + if (!selectedFile.isEmpty()) { QString path(QDir::toNativeSeparators(selectedFile)); mUI.mPath->setText(path); } @@ -81,8 +80,7 @@ Application ApplicationDialog::GetApplication() const void ApplicationDialog::Ok() { if (mUI.mName->text().isEmpty() || mUI.mPath->text().isEmpty() || - mUI.mParameters->text().isEmpty()) - { + mUI.mParameters->text().isEmpty()) { QMessageBox msg(QMessageBox::Warning, tr("Cppcheck"), tr("You must specify a name, a path and parameters for the application!"), @@ -91,9 +89,7 @@ void ApplicationDialog::Ok() msg.exec(); - } - else - { + } else { // Convert possible native (Windows) path to internal presentation format mUI.mPath->setText(QDir::fromNativeSeparators(mUI.mPath->text())); accept(); diff --git a/gui/applicationdialog.h b/gui/applicationdialog.h index 885b1af7e..100d7ab90 100644 --- a/gui/applicationdialog.h +++ b/gui/applicationdialog.h @@ -36,8 +36,7 @@ class QWidget; * to modify/add an application to open errors with. * */ -class ApplicationDialog : public QDialog -{ +class ApplicationDialog : public QDialog { Q_OBJECT public: diff --git a/gui/applicationlist.cpp b/gui/applicationlist.cpp index 9b79d381b..d84fa45bc 100644 --- a/gui/applicationlist.cpp +++ b/gui/applicationlist.cpp @@ -50,20 +50,16 @@ bool ApplicationList::LoadSettings() // Params will be empty first time starting with the new setting. // Return false and inform user about problem with application settings. bool succeeded = true; - if (!names.empty() && !paths.empty() && params.empty()) - { + if (!names.empty() && !paths.empty() && params.empty()) { for (int i = 0; i < paths.length(); i++) params << ""; succeeded = false; } - if (names.empty() && paths.empty() && params.empty()) - { - do - { + if (names.empty() && paths.empty() && params.empty()) { + do { // use as default for gnome environments - if (QFileInfo("/usr/bin/gedit").isExecutable()) - { + if (QFileInfo("/usr/bin/gedit").isExecutable()) { Application app; app.setName("gedit"); app.setPath("/usr/bin/gedit"); @@ -73,8 +69,7 @@ bool ApplicationList::LoadSettings() break; } // use as default for kde environments - if (QFileInfo("/usr/bin/kate").isExecutable()) - { + if (QFileInfo("/usr/bin/kate").isExecutable()) { Application app; app.setName("kate"); app.setPath("/usr/bin/kate"); @@ -83,19 +78,15 @@ bool ApplicationList::LoadSettings() defapp = 0; break; } - if (FindDefaultWindowsEditor()) - { + if (FindDefaultWindowsEditor()) { defapp = 0; break; } - } - while (0); + } while (0); } - if (names.size() > 0 && (names.size() == paths.size())) - { - for (int i = 0; i < names.size(); i++) - { + if (names.size() > 0 && (names.size() == paths.size())) { + for (int i = 0; i < names.size(); i++) { const Application app(names[i], paths[i], params[i]); AddApplication(app); } @@ -117,8 +108,7 @@ void ApplicationList::SaveSettings() QStringList paths; QStringList params; - for (int i = 0; i < GetApplicationCount(); i++) - { + for (int i = 0; i < GetApplicationCount(); i++) { Application app = GetApplication(i); names << app.getName(); paths << app.getPath(); @@ -139,8 +129,7 @@ int ApplicationList::GetApplicationCount() const Application ApplicationList::GetApplication(const int index) const { - if (index >= 0 && index < mApplications.size()) - { + if (index >= 0 && index < mApplications.size()) { return mApplications[index]; } @@ -149,16 +138,14 @@ Application ApplicationList::GetApplication(const int index) const void ApplicationList::SetApplication(int index, const Application &app) { - if (index >= 0 && index < mApplications.size()) - { + if (index >= 0 && index < mApplications.size()) { mApplications.replace(index, app); } } void ApplicationList::AddApplication(const Application &app) { - if (app.getName().isEmpty() || app.getPath().isEmpty()) - { + if (app.getName().isEmpty() || app.getPath().isEmpty()) { return; } mApplications << app; @@ -171,22 +158,19 @@ void ApplicationList::RemoveApplication(const int index) void ApplicationList::SetDefault(const int index) { - if (index < mApplications.size() && index >= 0) - { + if (index < mApplications.size() && index >= 0) { mDefaultApplicationIndex = index; } } void ApplicationList::Copy(const ApplicationList *list) { - if (!list) - { + if (!list) { return; } Clear(); - for (int i = 0; i < list->GetApplicationCount(); i++) - { + for (int i = 0; i < list->GetApplicationCount(); i++) { const Application app = list->GetApplication(i); AddApplication(app); } @@ -203,8 +187,7 @@ bool ApplicationList::FindDefaultWindowsEditor() { const QString appPath(getenv("ProgramFiles")); const QString notepadppPath = appPath + "\\Notepad++\\notepad++.exe"; - if (QFileInfo(notepadppPath).isExecutable()) - { + if (QFileInfo(notepadppPath).isExecutable()) { Application app; app.setName("Notepad++"); app.setPath("\"" + notepadppPath + "\""); @@ -215,8 +198,7 @@ bool ApplicationList::FindDefaultWindowsEditor() const QString windowsPath(getenv("windir")); const QString notepadPath = windowsPath + "\\system32\\notepad.exe"; - if (QFileInfo(notepadPath).isExecutable()) - { + if (QFileInfo(notepadPath).isExecutable()) { Application app; app.setName("Notepad"); app.setPath(notepadPath); diff --git a/gui/applicationlist.h b/gui/applicationlist.h index 05936734f..ffcae6f63 100644 --- a/gui/applicationlist.h +++ b/gui/applicationlist.h @@ -30,8 +30,7 @@ /** * @brief List of applications user has specified to open errors with. */ -class ApplicationList : public QObject -{ +class ApplicationList : public QObject { Q_OBJECT public: @@ -70,8 +69,7 @@ public: * @brief Return the default application. * @return Index of the default application. */ - int GetDefaultApplication() const - { + int GetDefaultApplication() const { return mDefaultApplicationIndex; } diff --git a/gui/checkstatistics.cpp b/gui/checkstatistics.cpp index 4f431ae7f..0348421bb 100644 --- a/gui/checkstatistics.cpp +++ b/gui/checkstatistics.cpp @@ -28,8 +28,7 @@ CheckStatistics::CheckStatistics(QObject *parent) void CheckStatistics::AddItem(ShowTypes::ShowType type) { - switch (type) - { + switch (type) { case ShowTypes::ShowStyle: mStyle++; break; @@ -68,8 +67,7 @@ void CheckStatistics::Clear() unsigned CheckStatistics::GetCount(ShowTypes::ShowType type) const { unsigned count = 0; - switch (type) - { + switch (type) { case ShowTypes::ShowStyle: count = mStyle; break; diff --git a/gui/checkstatistics.h b/gui/checkstatistics.h index 0c44d6626..7ccde3636 100644 --- a/gui/checkstatistics.h +++ b/gui/checkstatistics.h @@ -29,8 +29,7 @@ /** * A class for check statistics. */ -class CheckStatistics : public QObject -{ +class CheckStatistics : public QObject { public: CheckStatistics(QObject *parent = NULL); diff --git a/gui/checkthread.cpp b/gui/checkthread.cpp index b06627396..9bde678e0 100644 --- a/gui/checkthread.cpp +++ b/gui/checkthread.cpp @@ -47,8 +47,7 @@ void CheckThread::run() QString file; file = mResult.GetNextFile(); - while (!file.isEmpty() && mState == Running) - { + while (!file.isEmpty() && mState == Running) { qDebug() << "Checking file" << file; mCppcheck.check(file.toStdString()); emit FileChecked(file); diff --git a/gui/checkthread.h b/gui/checkthread.h index 3c7ab77d7..12be8bbe4 100644 --- a/gui/checkthread.h +++ b/gui/checkthread.h @@ -32,8 +32,7 @@ * @brief Thread to run cppcheck * */ -class CheckThread : public QThread -{ +class CheckThread : public QThread { Q_OBJECT public: CheckThread(ThreadResult &result); @@ -73,8 +72,7 @@ protected: * has been completed. Thread must be stopped cleanly, just terminating thread * likely causes unpredictable side-effects. */ - enum State - { + enum State { Running, /**< The thread is checking. */ Stopping, /**< The thread will stop after current work. */ Stopped, /**< The thread has been stopped. */ diff --git a/gui/csvreport.cpp b/gui/csvreport.cpp index 1147d01f3..ac397d3c9 100644 --- a/gui/csvreport.cpp +++ b/gui/csvreport.cpp @@ -37,8 +37,7 @@ CsvReport::~CsvReport() bool CsvReport::Create() { bool success = false; - if (Report::Create()) - { + if (Report::Create()) { mTxtWriter.setDevice(Report::GetFile()); success = true; } diff --git a/gui/csvreport.h b/gui/csvreport.h index 5994bba7e..4b39e7b38 100644 --- a/gui/csvreport.h +++ b/gui/csvreport.h @@ -36,8 +36,7 @@ * easy to import to many other programs. * @todo This class should be inherited from TxtReport? */ -class CsvReport : public Report -{ +class CsvReport : public Report { public: CsvReport(const QString &filename, QObject * parent = 0); virtual ~CsvReport(); diff --git a/gui/erroritem.cpp b/gui/erroritem.cpp index 99f9ebb29..e5c8bf535 100644 --- a/gui/erroritem.cpp +++ b/gui/erroritem.cpp @@ -56,8 +56,7 @@ QString ErrorItem::ToString() const str += GuiSeverity::toString(severity) +"\n"; str += summary + "\n"; str += message + "\n"; - for (int i = 0; i < files.size(); i++) - { + for (int i = 0; i < files.size(); i++) { str += " " + files[i] + ": " + QString::number(lines[i]) + "\n"; } return str; diff --git a/gui/erroritem.h b/gui/erroritem.h index 8bfe6cf1d..496122d08 100644 --- a/gui/erroritem.h +++ b/gui/erroritem.h @@ -35,13 +35,10 @@ class ErrorLine; * GUI needs its own versions of conversions since GUI uses Qt's QString * instead of the std::string used by lib/cli. */ -class GuiSeverity : Severity -{ +class GuiSeverity : Severity { public: - static QString toString(SeverityType severity) - { - switch (severity) - { + static QString toString(SeverityType severity) { + switch (severity) { case none: return ""; case error: @@ -62,8 +59,7 @@ public: return "???"; } - static SeverityType fromString(const QString &severity) - { + static SeverityType fromString(const QString &severity) { if (severity.isEmpty()) return none; if (severity == "none") @@ -94,8 +90,7 @@ public: * Full path is stored instead of relative path for flexibility. It is easy * to get the relative path from full path when needed. */ -class ErrorItem -{ +class ErrorItem { public: ErrorItem(); ErrorItem(const ErrorItem &item); @@ -123,8 +118,7 @@ Q_DECLARE_METATYPE(ErrorItem); /** * @brief A class containing error data for one shown error line. */ -class ErrorLine -{ +class ErrorLine { public: QString file; unsigned int line; diff --git a/gui/filelist.cpp b/gui/filelist.cpp index 9f3ef8985..30d68b9fc 100644 --- a/gui/filelist.cpp +++ b/gui/filelist.cpp @@ -32,8 +32,7 @@ QStringList FileList::GetDefaultFilters() bool FileList::FilterMatches(const QFileInfo &inf) { - if (inf.isFile()) - { + if (inf.isFile()) { const QStringList filters = FileList::GetDefaultFilters(); QString ext("*."); ext += inf.suffix(); @@ -57,14 +56,11 @@ void FileList::AddDirectory(const QString &directory, bool recursive) const QStringList filters = FileList::GetDefaultFilters(); const QStringList origNameFilters = dir.nameFilters(); dir.setNameFilters(filters); - if (!recursive) - { + if (!recursive) { dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); QFileInfoList items = dir.entryInfoList(); mFileList += items; - } - else - { + } else { dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); QFileInfoList items = dir.entryInfoList(); mFileList += items; @@ -73,8 +69,7 @@ void FileList::AddDirectory(const QString &directory, bool recursive) dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList list = dir.entryInfoList(); QFileInfo item; - foreach(item, list) - { + foreach(item, list) { const QString path = item.canonicalFilePath(); AddDirectory(path, recursive); } @@ -84,8 +79,7 @@ void FileList::AddDirectory(const QString &directory, bool recursive) void FileList::AddPathList(const QStringList &paths) { QString path; - foreach(path, paths) - { + foreach(path, paths) { QFileInfo inf(path); if (inf.isFile()) AddFile(path); @@ -96,18 +90,14 @@ void FileList::AddPathList(const QStringList &paths) QStringList FileList::GetFileList() const { - if (mExcludedPaths.empty()) - { + if (mExcludedPaths.empty()) { QStringList names; - foreach(QFileInfo item, mFileList) - { + foreach(QFileInfo item, mFileList) { QString name = QDir::fromNativeSeparators(item.canonicalFilePath()); names << name; } return names; - } - else - { + } else { return ApplyExcludeList(); } } @@ -120,8 +110,7 @@ void FileList::AddExcludeList(const QStringList &paths) QStringList FileList::ApplyExcludeList() const { QStringList paths; - foreach(QFileInfo item, mFileList) - { + foreach(QFileInfo item, mFileList) { QString name = QDir::fromNativeSeparators(item.canonicalFilePath()); if (!Match(name)) paths << name; @@ -131,16 +120,12 @@ QStringList FileList::ApplyExcludeList() const bool FileList::Match(const QString &path) const { - for (int i = 0; i < mExcludedPaths.size(); i++) - { - if (mExcludedPaths[i].endsWith('/')) - { + for (int i = 0; i < mExcludedPaths.size(); i++) { + if (mExcludedPaths[i].endsWith('/')) { const QString pathexclude("/" + mExcludedPaths[i]); if (path.indexOf(pathexclude) != -1) return true; - } - else - { + } else { if (path.endsWith(mExcludedPaths[i])) return true; } diff --git a/gui/filelist.h b/gui/filelist.h index 2fd00915f..ec7a774f5 100644 --- a/gui/filelist.h +++ b/gui/filelist.h @@ -35,8 +35,7 @@ * there is ignore filters then only paths not matching those filters are * returned. */ -class FileList -{ +class FileList { public: /** diff --git a/gui/fileviewdialog.cpp b/gui/fileviewdialog.cpp index 066930704..aa7f22d32 100644 --- a/gui/fileviewdialog.cpp +++ b/gui/fileviewdialog.cpp @@ -38,8 +38,7 @@ FileViewDialog::FileViewDialog(const QString &file, void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit) { QFile file(filename); - if (!file.exists()) - { + if (!file.exists()) { QString msg(tr("Could not find the file: %1")); msg = msg.arg(filename); @@ -53,8 +52,7 @@ void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit) } file.open(QIODevice::ReadOnly | QIODevice::Text); - if (!file.isReadable()) - { + if (!file.isReadable()) { QString msg(tr("Could not read the file: %1")); msg = msg.arg(filename); diff --git a/gui/fileviewdialog.h b/gui/fileviewdialog.h index 4fe67b754..3854318b2 100644 --- a/gui/fileviewdialog.h +++ b/gui/fileviewdialog.h @@ -36,8 +36,7 @@ class QTextEdit; * the authors list. * */ -class FileViewDialog : public QDialog -{ +class FileViewDialog : public QDialog { Q_OBJECT public: FileViewDialog(const QString &file, diff --git a/gui/logview.cpp b/gui/logview.cpp index 17a1630fe..1b4b4b8a5 100644 --- a/gui/logview.cpp +++ b/gui/logview.cpp @@ -65,11 +65,9 @@ void LogView::SaveButtonClicked() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log"), "", tr("Text files (*.txt *.log);;All files (*.*)")); - if (!fileName.isEmpty()) - { + if (!fileName.isEmpty()) { QFile file(fileName); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) - { + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(this, tr("Cppcheck"), tr("Could not open file for writing: \"%1\"").arg(fileName)); return; diff --git a/gui/logview.h b/gui/logview.h index 72770b882..9627e1661 100644 --- a/gui/logview.h +++ b/gui/logview.h @@ -29,8 +29,7 @@ * @brief A tool window that shows checking log. * */ -class LogView : public QWidget -{ +class LogView : public QWidget { Q_OBJECT public: LogView(QWidget *parent = 0); diff --git a/gui/main.cpp b/gui/main.cpp index 47c59b027..537a48f65 100644 --- a/gui/main.cpp +++ b/gui/main.cpp @@ -58,8 +58,7 @@ int main(int argc, char *argv[]) // Rest of the arguments are handled in MainWindow::HandleCLIParams() bool CheckArgs(const QStringList &args) { - if (args.contains("-h") || args.contains("--help")) - { + if (args.contains("-h") || args.contains("--help")) { ShowUsage(); return false; } diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp index 4d318020a..134e06c7c 100644 --- a/gui/mainwindow.cpp +++ b/gui/mainwindow.cpp @@ -134,13 +134,11 @@ MainWindow::MainWindow() : QStringList args = QCoreApplication::arguments(); //Remove the application itself args.removeFirst(); - if (!args.isEmpty()) - { + if (!args.isEmpty()) { HandleCLIParams(args); } - for (int i = 0; i < MaxRecentProjects; ++i) - { + for (int i = 0; i < MaxRecentProjects; ++i) { mRecentProjectActs[i] = new QAction(this); mRecentProjectActs[i]->setVisible(false); connect(mRecentProjectActs[i], SIGNAL(triggered()), @@ -151,8 +149,7 @@ MainWindow::MainWindow() : UpdateMRUMenuItems(); QActionGroup* platformGroup = new QActionGroup(this); - for (int i = 0; i < mPlatforms.getCount(); i++) - { + for (int i = 0; i < mPlatforms.getCount(); i++) { Platform plat = mPlatforms.mPlatforms[i]; QAction *act = new QAction(this); plat.mActMainWindow = act; @@ -185,28 +182,23 @@ MainWindow::~MainWindow() void MainWindow::HandleCLIParams(const QStringList ¶ms) { - if (params.contains("-p")) - { + if (params.contains("-p")) { QString projFile; const int ind = params.indexOf("-p"); if ((ind + 1) < params.length()) projFile = params[ind + 1]; LoadProjectFile(projFile); - } - else + } else DoCheckFiles(params); } void MainWindow::LoadSettings() { // Window/dialog sizes - if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) - { + if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) { showMaximized(); - } - else - { + } else { resize(mSettings->value(SETTINGS_WINDOW_WIDTH, 800).toInt(), mSettings->value(SETTINGS_WINDOW_HEIGHT, 600).toInt()); } @@ -235,8 +227,7 @@ void MainWindow::LoadSettings() SetLanguage(mSettings->value(SETTINGS_LANGUAGE, mTranslation->SuggestLanguage()).toString()); bool succeeded = mApplications->LoadSettings(); - if (!succeeded) - { + if (!succeeded) { const QString msg = tr("There was a problem with loading the editor application settings.\n\n" "This is probably because the settings were changed between the Cppcheck versions. " "Please check (and fix) the editor application settings, otherwise the editor " @@ -283,8 +274,7 @@ void MainWindow::SaveSettings() void MainWindow::DoCheckFiles(const QStringList &files) { - if (files.isEmpty()) - { + if (files.isEmpty()) { return; } ClearResults(); @@ -298,8 +288,7 @@ void MainWindow::DoCheckFiles(const QStringList &files) mUI.mResults->Clear(); mThread->ClearFiles(); - if (fileNames.isEmpty()) - { + if (fileNames.isEmpty()) { QMessageBox msg(QMessageBox::Warning, tr("Cppcheck"), tr("No suitable files found to check!"), @@ -329,8 +318,7 @@ void MainWindow::DoCheckFiles(const QStringList &files) QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode) { - if (mProject) - { + if (mProject) { QMessageBox msgBox(this); msgBox.setWindowTitle(tr("Cppcheck")); const QString msg(tr("You must close the project file before selecting new files or directories!")); @@ -345,27 +333,22 @@ QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode) // NOTE: we use QFileDialog::getOpenFileNames() and // QFileDialog::getExistingDirectory() because they show native Windows // selection dialog which is a lot more usable than QT:s own dialog. - if (mode == QFileDialog::ExistingFiles) - { + if (mode == QFileDialog::ExistingFiles) { selected = QFileDialog::getOpenFileNames(this, tr("Select files to check"), mSettings->value(SETTINGS_CHECK_PATH, "").toString()); if (selected.isEmpty()) mCurrentDirectory.clear(); - else - { + else { QFileInfo inf(selected[0]); mCurrentDirectory = inf.absolutePath(); } FormatAndSetTitle(); - } - else if (mode == QFileDialog::DirectoryOnly) - { + } else if (mode == QFileDialog::DirectoryOnly) { QString dir = QFileDialog::getExistingDirectory(this, tr("Select directory to check"), mSettings->value(SETTINGS_CHECK_PATH, "").toString()); - if (!dir.isEmpty()) - { + if (!dir.isEmpty()) { qDebug() << "Setting current directory to: " << dir; mCurrentDirectory = dir; selected.append(dir); @@ -394,10 +377,8 @@ void MainWindow::CheckDirectory() checkDir.setFilter(QDir::Files | QDir::Readable); checkDir.setNameFilters(filters); QStringList projFiles = checkDir.entryList(); - if (!projFiles.empty()) - { - if (projFiles.size() == 1) - { + if (!projFiles.empty()) { + if (projFiles.size() == 1) { // If one project file found, suggest loading it QMessageBox msgBox(this); msgBox.setWindowTitle(tr("Cppcheck")); @@ -409,21 +390,16 @@ void MainWindow::CheckDirectory() msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int dlgResult = msgBox.exec(); - if (dlgResult == QMessageBox::Yes) - { + if (dlgResult == QMessageBox::Yes) { QString path = checkDir.canonicalPath(); if (!path.endsWith("/")) path += "/"; path += projFiles[0]; LoadProjectFile(path); - } - else - { + } else { DoCheckFiles(dir); } - } - else - { + } else { // If multiple project files found inform that there are project // files also available. QMessageBox msgBox(this); @@ -437,14 +413,11 @@ void MainWindow::CheckDirectory() msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int dlgResult = msgBox.exec(); - if (dlgResult == QMessageBox::Yes) - { + if (dlgResult == QMessageBox::Yes) { DoCheckFiles(dir); } } - } - else - { + } else { DoCheckFiles(dir); } } @@ -452,8 +425,7 @@ void MainWindow::CheckDirectory() void MainWindow::AddIncludeDirs(const QStringList &includeDirs, Settings &result) { QString dir; - foreach(dir, includeDirs) - { + foreach(dir, includeDirs) { QString incdir; if (!QDir::isAbsolutePath(dir)) incdir = mCurrentDirectory + "/"; @@ -472,16 +444,14 @@ Settings MainWindow::GetCppcheckSettings() Settings result; // If project file loaded, read settings from it - if (mProject) - { + if (mProject) { ProjectFile *pfile = mProject->GetProjectFile(); QStringList dirs = pfile->GetIncludeDirs(); AddIncludeDirs(dirs, result); QStringList defines = pfile->GetDefines(); QString define; - foreach(define, defines) - { + foreach(define, defines) { if (!result.userDefines.empty()) result.userDefines += ";"; result.userDefines += define.toStdString(); @@ -492,8 +462,7 @@ Settings MainWindow::GetCppcheckSettings() // Global include directories must be added AFTER the per project include // directories so per project include directories can override global ones. const QString globalIncludes = mSettings->value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString(); - if (!globalIncludes.isEmpty()) - { + if (!globalIncludes.isEmpty()) { QStringList includes = globalIncludes.split(";"); AddIncludeDirs(includes, result); } @@ -514,8 +483,7 @@ Settings MainWindow::GetCppcheckSettings() result.inconclusive = mSettings->value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool(); result.platformType = (Settings::PlatformType) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt(); - if (result._jobs <= 0) - { + if (result._jobs <= 0) { result._jobs = 1; } @@ -524,8 +492,7 @@ Settings MainWindow::GetCppcheckSettings() void MainWindow::CheckDone() { - if (mExiting) - { + if (mExiting) { close(); return; } @@ -537,8 +504,7 @@ void MainWindow::CheckDone() EnableProjectActions(true); EnableProjectOpenActions(true); - if (mUI.mResults->HasResults()) - { + if (mUI.mResults->HasResults()) { mUI.mActionClearResults->setEnabled(true); mUI.mActionSave->setEnabled(true); } @@ -559,8 +525,7 @@ void MainWindow::CheckLockDownUI() void MainWindow::ProgramSettings() { SettingsDialog dialog(mApplications, mTranslation, this); - if (dialog.exec() == QDialog::Accepted) - { + if (dialog.exec() == QDialog::Accepted) { dialog.SaveSettingValues(); mUI.mResults->UpdateSettings(dialog.ShowFullPath(), dialog.SaveFullPath(), @@ -603,8 +568,7 @@ void MainWindow::OpenXML() filter, &selectedFilter); - if (!selectedFile.isEmpty()) - { + if (!selectedFile.isEmpty()) { mUI.mResults->ReadErrorsXml(selectedFile); } } @@ -663,13 +627,10 @@ void MainWindow::UncheckAll() void MainWindow::closeEvent(QCloseEvent *event) { // Check that we aren't checking files - if (!mThread->IsChecking()) - { + if (!mThread->IsChecking()) { SaveSettings(); event->accept(); - } - else - { + } else { const QString text(tr("Checking is running.\n\n" \ "Do you want to stop the checking and exit Cppcheck?.")); @@ -681,8 +642,7 @@ void MainWindow::closeEvent(QCloseEvent *event) msg.setDefaultButton(QMessageBox::No); int rv = msg.exec(); - if (rv == QMessageBox::Yes) - { + if (rv == QMessageBox::Yes) { // This isn't really very clean way to close threads but since the app is // exiting it doesn't matter. mThread->Stop(); @@ -739,35 +699,25 @@ void MainWindow::Save() filter, &selectedFilter); - if (!selectedFile.isEmpty()) - { + if (!selectedFile.isEmpty()) { Report::Type type = Report::TXT; - if (selectedFilter == tr("XML files version 1 (*.xml)")) - { + if (selectedFilter == tr("XML files version 1 (*.xml)")) { type = Report::XML; if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive)) selectedFile += ".xml"; - } - else if (selectedFilter == tr("XML files version 2 (*.xml)")) - { + } else if (selectedFilter == tr("XML files version 2 (*.xml)")) { type = Report::XMLV2; if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive)) selectedFile += ".xml"; - } - else if (selectedFilter == tr("Text files (*.txt)")) - { + } else if (selectedFilter == tr("Text files (*.txt)")) { type = Report::TXT; if (!selectedFile.endsWith(".txt", Qt::CaseInsensitive)) selectedFile += ".txt"; - } - else if (selectedFilter == tr("CSV files (*.csv)")) - { + } else if (selectedFilter == tr("CSV files (*.csv)")) { type = Report::CSV; if (!selectedFile.endsWith(".csv", Qt::CaseInsensitive)) selectedFile += ".csv"; - } - else - { + } else { if (selectedFile.endsWith(".xml", Qt::CaseInsensitive)) type = Report::XML; else if (selectedFile.endsWith(".txt", Qt::CaseInsensitive)) @@ -817,8 +767,7 @@ void MainWindow::SetLanguage(const QString &code) return; QString error; - if (!mTranslation->SetLanguage(code, error)) - { + if (!mTranslation->SetLanguage(code, error)) { const QString msg(tr("Failed to change the user interface language:" "\n\n%1\n\n" "The user interface language has been reset to English. Open " @@ -830,9 +779,7 @@ void MainWindow::SetLanguage(const QString &code) QMessageBox::Ok, this); msgBox.exec(); - } - else - { + } else { //Translate everything that is visible here mUI.retranslateUi(this); mUI.mResults->Translate(); @@ -870,8 +817,7 @@ void MainWindow::OpenProjectFile() QString(), filter); - if (!filepath.isEmpty()) - { + if (!filepath.isEmpty()) { LoadProjectFile(filepath); } } @@ -911,16 +857,13 @@ void MainWindow::CheckProject(Project *project) // file's location, see above). This is to keep the compatibility with // old "silent" project file loading when we checked the director where the // project file was located. - if (paths.isEmpty()) - { + if (paths.isEmpty()) { paths << mCurrentDirectory; } // Convert relative paths to absolute paths - for (int i = 0; i < paths.size(); i++) - { - if (!QDir::isAbsolutePath(paths[i])) - { + for (int i = 0; i < paths.size(); i++) { + if (!QDir::isAbsolutePath(paths[i])) { QString path = mCurrentDirectory + "/"; path += paths[i]; paths[i] = QDir::cleanPath(path); @@ -937,8 +880,7 @@ void MainWindow::NewProjectFile() QString(), filter); - if (!filepath.isEmpty()) - { + if (!filepath.isEmpty()) { EnableProjectActions(true); QFileInfo inf(filepath); const QString filename = inf.fileName(); @@ -964,8 +906,7 @@ void MainWindow::CloseProjectFile() void MainWindow::EditProjectFile() { - if (!mProject) - { + if (!mProject) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), QString(tr("No project file loaded")), @@ -992,8 +933,7 @@ void MainWindow::ShowStatistics() StatsDialog statsDialog(this); // Show a dialog with the previous scan statistics and project information - if (mProject) - { + if (mProject) { statsDialog.setProject(*mProject); } statsDialog.setPathSelected(mCurrentDirectory); @@ -1006,16 +946,14 @@ void MainWindow::ShowStatistics() void MainWindow::Log(const QString &logline) { - if (mLogView) - { + if (mLogView) { mLogView->AppendLine(logline); } } void MainWindow::DebugError(const ErrorItem &item) { - if (mLogView) - { + if (mLogView) { mLogView->AppendLine(item.ToString()); } } @@ -1040,16 +978,12 @@ void MainWindow::EnableProjectOpenActions(bool enable) void MainWindow::OpenRecentProject() { QAction *action = qobject_cast(sender()); - if (action) - { + if (action) { const QString project = action->data().toString(); QFileInfo inf(project); - if (inf.exists()) - { + if (inf.exists()) { LoadProjectFile(project); - } - else - { + } else { const QString text(tr("The project file\n\n%1\n\n could not be found!\n\n" "Do you want to remove the file from the recently " "used projects -list?").arg(project)); @@ -1062,8 +996,7 @@ void MainWindow::OpenRecentProject() msg.setDefaultButton(QMessageBox::No); int rv = msg.exec(); - if (rv == QMessageBox::Yes) - { + if (rv == QMessageBox::Yes) { RemoveProjectMRU(project); } @@ -1073,16 +1006,14 @@ void MainWindow::OpenRecentProject() void MainWindow::UpdateMRUMenuItems() { - for (int i = 0; i < MaxRecentProjects + 1; i++) - { + for (int i = 0; i < MaxRecentProjects + 1; i++) { if (mRecentProjectActs[i] != NULL) mUI.mMenuFile->removeAction(mRecentProjectActs[i]); } QStringList projects = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList(); const int numRecentProjects = qMin(projects.size(), (int)MaxRecentProjects); - for (int i = 0; i < numRecentProjects; i++) - { + for (int i = 0; i < numRecentProjects; i++) { const QString filename = QFileInfo(projects[i]).fileName(); const QString text = QString("&%1 %2").arg(i + 1).arg(filename); mRecentProjectActs[i]->setText(text); @@ -1119,8 +1050,7 @@ void MainWindow::RemoveProjectMRU(const QString &project) void MainWindow::SelectPlatform() { QAction *action = qobject_cast(sender()); - if (action) - { + if (action) { const Settings::PlatformType platform = (Settings::PlatformType) action->data().toInt(); mSettings->setValue(SETTINGS_CHECKED_PLATFORM, platform); } diff --git a/gui/mainwindow.h b/gui/mainwindow.h index ddd0550f7..6b733bb6e 100644 --- a/gui/mainwindow.h +++ b/gui/mainwindow.h @@ -49,8 +49,7 @@ class QAction; * @brief Main window for cppcheck-gui * */ -class MainWindow : public QMainWindow -{ +class MainWindow : public QMainWindow { Q_OBJECT public: diff --git a/gui/platforms.cpp b/gui/platforms.cpp index 8d095622d..12cf8ee28 100644 --- a/gui/platforms.cpp +++ b/gui/platforms.cpp @@ -50,10 +50,8 @@ int Platforms::getCount() const Platform& Platforms::get(Settings::PlatformType platform) { QList::iterator iter = mPlatforms.begin(); - while (iter != mPlatforms.end()) - { - if ((*iter).mType == platform) - { + while (iter != mPlatforms.end()) { + if ((*iter).mType == platform) { return *iter; } ++iter; diff --git a/gui/platforms.h b/gui/platforms.h index 62de8b2bd..02caa21f0 100644 --- a/gui/platforms.h +++ b/gui/platforms.h @@ -31,8 +31,7 @@ /** * @brief Checked platform GUI-data. */ -struct Platform -{ +struct Platform { QString mTitle; /**< Text visible in the GUI. */ Settings::PlatformType mType; /**< Type in the core. */ QAction *mActMainWindow; /**< Pointer to main window action item. */ @@ -41,8 +40,7 @@ struct Platform /** * @brief List of checked platforms. */ -class Platforms : public QObject -{ +class Platforms : public QObject { Q_OBJECT public: diff --git a/gui/project.cpp b/gui/project.cpp index 4a58406fb..7914a24f5 100644 --- a/gui/project.cpp +++ b/gui/project.cpp @@ -65,10 +65,8 @@ bool Project::IsOpen() const bool Project::Open() { mPFile = new ProjectFile(mFilename, this); - if (QFile::exists(mFilename)) - { - if (!mPFile->Read()) - { + if (QFile::exists(mFilename)) { + if (!mPFile->Read()) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), tr("Could not read the project file."), @@ -99,8 +97,7 @@ void Project::Edit() dlg.SetExcludedPaths(ignorepaths); int rv = dlg.exec(); - if (rv == QDialog::Accepted) - { + if (rv == QDialog::Accepted) { QString root = dlg.GetRootPath(); mPFile->SetRootPath(root); QStringList includes = dlg.GetIncludePaths(); @@ -113,8 +110,7 @@ void Project::Edit() mPFile->SetExcludedPaths(excludedpaths); bool writeSuccess = mPFile->Write(); - if (!writeSuccess) - { + if (!writeSuccess) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), tr("Could not write the project file."), diff --git a/gui/project.h b/gui/project.h index 2d235e314..d8c11cc80 100644 --- a/gui/project.h +++ b/gui/project.h @@ -32,8 +32,7 @@ class ProjectFile; * @brief A class that contains project data and manages projects. * Currently only project file creation and editing is implemented. */ -class Project : public QObject -{ +class Project : public QObject { Q_OBJECT public: @@ -79,8 +78,7 @@ public: * @brief Return current project file. * @return project file. */ - ProjectFile * GetProjectFile() const - { + ProjectFile * GetProjectFile() const { return mPFile; } diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp index c1d84e4b5..f9b0bc540 100644 --- a/gui/projectfile.cpp +++ b/gui/projectfile.cpp @@ -68,13 +68,10 @@ bool ProjectFile::Read(const QString &filename) QXmlStreamReader xmlReader(&file); bool insideProject = false; bool projectTagFound = false; - while (!xmlReader.atEnd()) - { - switch (xmlReader.readNext()) - { + while (!xmlReader.atEnd()) { + switch (xmlReader.readNext()) { case QXmlStreamReader::StartElement: - if (xmlReader.name() == ProjectElementName) - { + if (xmlReader.name() == ProjectElementName) { insideProject = true; projectTagFound = true; } @@ -134,8 +131,7 @@ bool ProjectFile::Read(const QString &filename) QStringList ProjectFile::GetIncludeDirs() const { QStringList dirs; - foreach(QString path, mIncludeDirs) - { + foreach(QString path, mIncludeDirs) { dirs << QDir::fromNativeSeparators(path); } return dirs; @@ -149,8 +145,7 @@ QStringList ProjectFile::GetDefines() const QStringList ProjectFile::GetCheckPaths() const { QStringList paths; - foreach(QString path, mPaths) - { + foreach(QString path, mPaths) { paths << QDir::fromNativeSeparators(path); } return paths; @@ -159,8 +154,7 @@ QStringList ProjectFile::GetCheckPaths() const QStringList ProjectFile::GetExcludedPaths() const { QStringList paths; - foreach(QString path, mExcludedPaths) - { + foreach(QString path, mExcludedPaths) { paths << QDir::fromNativeSeparators(path); } return paths; @@ -178,16 +172,13 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) { QXmlStreamReader::TokenType type; bool allRead = false; - do - { + do { type = reader.readNext(); - switch (type) - { + switch (type) { case QXmlStreamReader::StartElement: // Read dir-elements - if (reader.name().toString() == DirElementName) - { + if (reader.name().toString() == DirElementName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", DirNameAttrib).toString(); if (!name.isEmpty()) @@ -212,23 +203,19 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) case QXmlStreamReader::ProcessingInstruction: break; } - } - while (!allRead); + } while (!allRead); } void ProjectFile::ReadDefines(QXmlStreamReader &reader) { QXmlStreamReader::TokenType type; bool allRead = false; - do - { + do { type = reader.readNext(); - switch (type) - { + switch (type) { case QXmlStreamReader::StartElement: // Read define-elements - if (reader.name().toString() == DefineName) - { + if (reader.name().toString() == DefineName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", DefineNameAttrib).toString(); if (!name.isEmpty()) @@ -253,24 +240,20 @@ void ProjectFile::ReadDefines(QXmlStreamReader &reader) case QXmlStreamReader::ProcessingInstruction: break; } - } - while (!allRead); + } while (!allRead); } void ProjectFile::ReadCheckPaths(QXmlStreamReader &reader) { QXmlStreamReader::TokenType type; bool allRead = false; - do - { + do { type = reader.readNext(); - switch (type) - { + switch (type) { case QXmlStreamReader::StartElement: // Read dir-elements - if (reader.name().toString() == PathName) - { + if (reader.name().toString() == PathName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", PathNameAttrib).toString(); if (!name.isEmpty()) @@ -295,31 +278,26 @@ void ProjectFile::ReadCheckPaths(QXmlStreamReader &reader) case QXmlStreamReader::ProcessingInstruction: break; } - } - while (!allRead); + } while (!allRead); } void ProjectFile::ReadExcludes(QXmlStreamReader &reader) { QXmlStreamReader::TokenType type; bool allRead = false; - do - { + do { type = reader.readNext(); - switch (type) - { + switch (type) { case QXmlStreamReader::StartElement: // Read exclude-elements - if (reader.name().toString() == ExcludePathName) - { + if (reader.name().toString() == ExcludePathName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", ExcludePathNameAttrib).toString(); if (!name.isEmpty()) mExcludedPaths << name; } // Read ignore-elements - deprecated but support reading them - else if (reader.name().toString() == IgnorePathName) - { + else if (reader.name().toString() == IgnorePathName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", IgnorePathNameAttrib).toString(); if (!name.isEmpty()) @@ -346,8 +324,7 @@ void ProjectFile::ReadExcludes(QXmlStreamReader &reader) case QXmlStreamReader::ProcessingInstruction: break; } - } - while (!allRead); + } while (!allRead); } void ProjectFile::SetIncludes(const QStringList &includes) @@ -385,18 +362,15 @@ bool ProjectFile::Write(const QString &filename) xmlWriter.writeStartElement(ProjectElementName); xmlWriter.writeAttribute(ProjectVersionAttrib, ProjectFileVersion); - if (!mRootPath.isEmpty()) - { + if (!mRootPath.isEmpty()) { xmlWriter.writeStartElement(RootPathName); xmlWriter.writeAttribute(RootPathNameAttrib, mRootPath); xmlWriter.writeEndElement(); } - if (!mIncludeDirs.isEmpty()) - { + if (!mIncludeDirs.isEmpty()) { xmlWriter.writeStartElement(IncludDirElementName); - foreach(QString incdir, mIncludeDirs) - { + foreach(QString incdir, mIncludeDirs) { xmlWriter.writeStartElement(DirElementName); xmlWriter.writeAttribute(DirNameAttrib, incdir); xmlWriter.writeEndElement(); @@ -404,11 +378,9 @@ bool ProjectFile::Write(const QString &filename) xmlWriter.writeEndElement(); } - if (!mDefines.isEmpty()) - { + if (!mDefines.isEmpty()) { xmlWriter.writeStartElement(DefinesElementName); - foreach(QString define, mDefines) - { + foreach(QString define, mDefines) { xmlWriter.writeStartElement(DefineName); xmlWriter.writeAttribute(DefineNameAttrib, define); xmlWriter.writeEndElement(); @@ -416,11 +388,9 @@ bool ProjectFile::Write(const QString &filename) xmlWriter.writeEndElement(); } - if (!mPaths.isEmpty()) - { + if (!mPaths.isEmpty()) { xmlWriter.writeStartElement(PathsElementName); - foreach(QString path, mPaths) - { + foreach(QString path, mPaths) { xmlWriter.writeStartElement(PathName); xmlWriter.writeAttribute(PathNameAttrib, path); xmlWriter.writeEndElement(); @@ -428,11 +398,9 @@ bool ProjectFile::Write(const QString &filename) xmlWriter.writeEndElement(); } - if (!mExcludedPaths.isEmpty()) - { + if (!mExcludedPaths.isEmpty()) { xmlWriter.writeStartElement(ExcludeElementName); - foreach(QString path, mExcludedPaths) - { + foreach(QString path, mExcludedPaths) { xmlWriter.writeStartElement(ExcludePathName); xmlWriter.writeAttribute(ExcludePathNameAttrib, path); xmlWriter.writeEndElement(); diff --git a/gui/projectfile.h b/gui/projectfile.h index b6d264044..2e4226bf2 100644 --- a/gui/projectfile.h +++ b/gui/projectfile.h @@ -33,8 +33,7 @@ * The project files contain project-specific settings for checking. For * example a list of include paths. */ -class ProjectFile : public QObject -{ +class ProjectFile : public QObject { Q_OBJECT public: @@ -51,8 +50,7 @@ public: * @brief Get project root path. * @return project root path. */ - QString GetRootPath() const - { + QString GetRootPath() const { return mRootPath; } @@ -84,8 +82,7 @@ public: * @brief Get filename for the project file. * @return file name. */ - QString GetFilename() - { + QString GetFilename() { return mFilename; } @@ -93,8 +90,7 @@ public: * @brief Set project root path. * @param rootpath new project root path. */ - void SetRootPath(const QString &rootpath) - { + void SetRootPath(const QString &rootpath) { mRootPath = rootpath; } @@ -132,8 +128,7 @@ public: * @brief Set filename for the project file. * @param filename Filename to use. */ - void SetFilename(const QString &filename) - { + void SetFilename(const QString &filename) { mFilename = filename; } diff --git a/gui/projectfiledialog.cpp b/gui/projectfiledialog.cpp index 06a18bee6..9f6f5292a 100644 --- a/gui/projectfiledialog.cpp +++ b/gui/projectfiledialog.cpp @@ -118,8 +118,7 @@ QStringList ProjectFileDialog::GetIncludePaths() const { const int count = mUI.mListIncludeDirs->count(); QStringList includePaths; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { QListWidgetItem *item = mUI.mListIncludeDirs->item(i); includePaths << QDir::fromNativeSeparators(item->text()); } @@ -130,8 +129,7 @@ QStringList ProjectFileDialog::GetDefines() const { QString define = mUI.mEditDefines->text(); QStringList defines; - if (!define.isEmpty()) - { + if (!define.isEmpty()) { define = define.trimmed(); if (define.indexOf(';') != -1) defines = define.split(";"); @@ -145,8 +143,7 @@ QStringList ProjectFileDialog::GetPaths() const { const int count = mUI.mListPaths->count(); QStringList paths; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { QListWidgetItem *item = mUI.mListPaths->item(i); paths << QDir::fromNativeSeparators(item->text()); } @@ -157,8 +154,7 @@ QStringList ProjectFileDialog::GetExcludedPaths() const { const int count = mUI.mListExcludedPaths->count(); QStringList paths; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { QListWidgetItem *item = mUI.mListExcludedPaths->item(i); paths << QDir::fromNativeSeparators(item->text()); } @@ -173,8 +169,7 @@ void ProjectFileDialog::SetRootPath(const QString &root) void ProjectFileDialog::SetIncludepaths(const QStringList &includes) { - foreach(QString dir, includes) - { + foreach(QString dir, includes) { AddIncludeDir(dir); } } @@ -183,8 +178,7 @@ void ProjectFileDialog::SetDefines(const QStringList &defines) { QString definestr; QString define; - foreach(define, defines) - { + foreach(define, defines) { definestr += define; definestr += ";"; } @@ -196,16 +190,14 @@ void ProjectFileDialog::SetDefines(const QStringList &defines) void ProjectFileDialog::SetPaths(const QStringList &paths) { - foreach(QString path, paths) - { + foreach(QString path, paths) { AddPath(path); } } void ProjectFileDialog::SetExcludedPaths(const QStringList &paths) { - foreach(QString path, paths) - { + foreach(QString path, paths) { AddExcludePath(path); } } @@ -218,8 +210,7 @@ void ProjectFileDialog::AddIncludeDir() tr("Select include directory"), rootpath); - if (!selectedDir.isEmpty()) - { + if (!selectedDir.isEmpty()) { AddIncludeDir(selectedDir); } } @@ -232,8 +223,7 @@ void ProjectFileDialog::AddPath() tr("Select a directory to check"), rootpath); - if (!selectedDir.isEmpty()) - { + if (!selectedDir.isEmpty()) { AddPath(selectedDir); } } @@ -273,8 +263,7 @@ void ProjectFileDialog::AddExcludePath() tr("Select directory to ignore"), rootpath); - if (!selectedDir.isEmpty()) - { + if (!selectedDir.isEmpty()) { if (!selectedDir.endsWith('/')) selectedDir += '/'; AddExcludePath(selectedDir); diff --git a/gui/projectfiledialog.h b/gui/projectfiledialog.h index 51cfbab17..e9aade83f 100644 --- a/gui/projectfiledialog.h +++ b/gui/projectfiledialog.h @@ -36,8 +36,7 @@ class QLineEdit; /** * @brief A dialog for editing project file data. */ -class ProjectFileDialog : public QDialog -{ +class ProjectFileDialog : public QDialog { Q_OBJECT public: ProjectFileDialog(const QString &path, QWidget *parent = 0); diff --git a/gui/report.cpp b/gui/report.cpp index 3ea7445f6..1db50fefd 100644 --- a/gui/report.cpp +++ b/gui/report.cpp @@ -36,8 +36,7 @@ Report::~Report() bool Report::Create() { bool succeed = false; - if (!mFile.isOpen()) - { + if (!mFile.isOpen()) { mFile.setFileName(mFilename); succeed = mFile.open(QIODevice::WriteOnly | QIODevice::Text); } @@ -47,8 +46,7 @@ bool Report::Create() bool Report::Open() { bool succeed = false; - if (!mFile.isOpen()) - { + if (!mFile.isOpen()) { mFile.setFileName(mFilename); succeed = mFile.open(QIODevice::ReadOnly | QIODevice::Text); } diff --git a/gui/report.h b/gui/report.h index ace33c4b6..abce3415d 100644 --- a/gui/report.h +++ b/gui/report.h @@ -31,12 +31,10 @@ /** * @brief A base class for reports. */ -class Report : public QObject -{ +class Report : public QObject { public: - enum Type - { + enum Type { TXT, XML, XMLV2, diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp index 517900127..2a2d7f526 100644 --- a/gui/resultstree.cpp +++ b/gui/resultstree.cpp @@ -96,15 +96,13 @@ QStandardItem *ResultsTree::CreateLineNumberItem(const QString &linenumber) void ResultsTree::AddErrorItem(const ErrorItem &item) { - if (item.files.isEmpty()) - { + if (item.files.isEmpty()) { return; } QString realfile = StripPath(item.files[0], false); - if (realfile.isEmpty()) - { + if (realfile.isEmpty()) { realfile = tr("Undefined file"); } @@ -112,20 +110,17 @@ void ResultsTree::AddErrorItem(const ErrorItem &item) //bool hide = !mShowTypes[SeverityToShowType(item.severity)]; //If specified, filter on summary, message, filename, and id - if (!hide && !mFilter.isEmpty()) - { + if (!hide && !mFilter.isEmpty()) { if (!item.summary.contains(mFilter, Qt::CaseInsensitive) && !item.message.contains(mFilter, Qt::CaseInsensitive) && !item.file.contains(mFilter, Qt::CaseInsensitive) && - !item.errorId.contains(mFilter, Qt::CaseInsensitive)) - { + !item.errorId.contains(mFilter, Qt::CaseInsensitive)) { hide = true; } } //if there is at least one error that is not hidden, we have a visible error - if (!hide) - { + if (!hide) { mVisibleErrors = true; } @@ -160,8 +155,7 @@ void ResultsTree::AddErrorItem(const ErrorItem &item) stditem->setData(QVariant(data)); //Add backtrace files as children - for (int i = 1; i < item.files.size(); i++) - { + for (int i = 1; i < item.files.size(); i++) { line.file = StripPath(item.files[i], false); line.line = item.lines[i]; QStandardItem *child_item; @@ -184,8 +178,7 @@ void ResultsTree::AddErrorItem(const ErrorItem &item) //TODO just hide/show current error and it's file //since this does a lot of unnecessary work - if (!hide) - { + if (!hide) { ShowFileItem(realfile); } } @@ -196,8 +189,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, const QString &icon) { - if (!parent) - { + if (!parent) { return 0; } @@ -211,8 +203,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, //TODO message has parameter names so we'll need changes to the core //cppcheck so we can get proper translations QString summary; - if (item.inconclusive) - { + if (item.inconclusive) { summary = tr("[Inconclusive]"); summary += " "; } @@ -220,22 +211,18 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, list << CreateNormalItem(summary); // Check for duplicate rows and don't add them if found - for (int i = 0; i < parent->rowCount(); i++) - { + for (int i = 0; i < parent->rowCount(); i++) { // The first column is the file name and is always the same so // we skip it in other platforms than Windows, where filename case // is ignored. So in Windows we can get filenames "header.h" and // "Header.h" and must compare them as identical filenames. // the third column is the line number so check it first - if (parent->child(i, 2)->text() == list[2]->text()) - { + if (parent->child(i, 2)->text() == list[2]->text()) { // the second column is the severity so check it next - if (parent->child(i, 1)->text() == list[1]->text()) - { + if (parent->child(i, 1)->text() == list[1]->text()) { // the fourth column is the summary so check it last - if (parent->child(i, 3)->text() == list[3]->text()) - { + if (parent->child(i, 3)->text() == list[3]->text()) { #if defined(_WIN32) const QString first = parent->child(i, 0)->text().toLower(); const QString second = list[0]->text().toLower(); @@ -254,8 +241,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, setRowHidden(parent->rowCount() - 1, parent->index(), hide); - if (!icon.isEmpty()) - { + if (!icon.isEmpty()) { list[0]->setIcon(QIcon(icon)); } @@ -266,8 +252,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, QString ResultsTree::SeverityToTranslatedString(Severity::SeverityType severity) { - switch (severity) - { + switch (severity) { case Severity::style: return tr("style"); break; @@ -307,8 +292,7 @@ QString ResultsTree::SeverityToTranslatedString(Severity::SeverityType severity) QStandardItem *ResultsTree::FindFileItem(const QString &name) { QList list = mModel.findItems(name); - if (list.size() > 0) - { + if (list.size() > 0) { return list[0]; } return 0; @@ -321,8 +305,7 @@ void ResultsTree::Clear() void ResultsTree::LoadSettings() { - for (int i = 0; i < mModel.columnCount(); i++) - { + for (int i = 0; i < mModel.columnCount(); i++) { //mFileTree.columnWidth(i); QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i); setColumnWidth(i, mSettings->value(temp, 800 / mModel.columnCount()).toInt()); @@ -335,8 +318,7 @@ void ResultsTree::LoadSettings() void ResultsTree::SaveSettings() { - for (int i = 0; i < mModel.columnCount(); i++) - { + for (int i = 0; i < mModel.columnCount(); i++) { QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i); mSettings->setValue(temp, columnWidth(i)); } @@ -344,8 +326,7 @@ void ResultsTree::SaveSettings() void ResultsTree::ShowResults(ShowTypes::ShowType type, bool show) { - if (type != ShowTypes::ShowNone && mShowSeverities.isShown(type) != show) - { + if (type != ShowTypes::ShowNone && mShowSeverities.isShown(type) != show) { mShowSeverities.show(type, show); RefreshTree(); } @@ -361,8 +342,7 @@ void ResultsTree::ShowHiddenResults() { //Clear the "hide" flag for each item int filecount = mModel.rowCount(); - for (int i = 0; i < filecount; i++) - { + for (int i = 0; i < filecount; i++) { QStandardItem *file = mModel.item(i, 0); if (!file) continue; @@ -372,11 +352,9 @@ void ResultsTree::ShowHiddenResults() file->setData(QVariant(data)); int errorcount = file->rowCount(); - for (int j = 0; j < errorcount; j++) - { + for (int j = 0; j < errorcount; j++) { QStandardItem *child = file->child(j, 0); - if (child) - { + if (child) { data = child->data().toMap(); data["hide"] = false; child->setData(QVariant(data)); @@ -394,12 +372,10 @@ void ResultsTree::RefreshTree() //Get the amount of files in the tree int filecount = mModel.rowCount(); - for (int i = 0; i < filecount; i++) - { + for (int i = 0; i < filecount; i++) { //Get file i QStandardItem *file = mModel.item(i, 0); - if (!file) - { + if (!file) { continue; } @@ -409,12 +385,10 @@ void ResultsTree::RefreshTree() //By default it shouldn't be visible bool show = false; - for (int j = 0; j < errorcount; j++) - { + for (int j = 0; j < errorcount; j++) { //Get the error itself QStandardItem *child = file->child(j, 0); - if (!child) - { + if (!child) { continue; } @@ -427,19 +401,16 @@ void ResultsTree::RefreshTree() bool hide = (data["hide"].toBool() || !mShowSeverities.isShown(ShowTypes::VariantToShowType(data["severity"]))); //If specified, filter on summary, message, filename, and id - if (!hide && !mFilter.isEmpty()) - { + if (!hide && !mFilter.isEmpty()) { if (!data["summary"].toString().contains(mFilter, Qt::CaseInsensitive) && !data["message"].toString().contains(mFilter, Qt::CaseInsensitive) && !data["file"].toString().contains(mFilter, Qt::CaseInsensitive) && - !data["id"].toString().contains(mFilter, Qt::CaseInsensitive)) - { + !data["id"].toString().contains(mFilter, Qt::CaseInsensitive)) { hide = true; } } - if (!hide) - { + if (!hide) { mVisibleErrors = true; } @@ -447,15 +418,13 @@ void ResultsTree::RefreshTree() setRowHidden(j, file->index(), hide); //If it was shown then the file itself has to be shown as well - if (!hide) - { + if (!hide) { show = true; } } //Hide the file if its "hide" attribute is set - if (file->data().toMap()["hide"].toBool()) - { + if (file->data().toMap()["hide"].toBool()) { show = false; } @@ -471,8 +440,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide) // native separators to find it. QStandardItem *item = FindFileItem(QDir::toNativeSeparators(name)); - if (item) - { + if (item) { return item; } @@ -495,8 +463,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide) void ResultsTree::ShowFileItem(const QString &name) { QStandardItem *item = FindFileItem(name); - if (item) - { + if (item) { setRowHidden(0, mModel.indexFromItem(item), false); } } @@ -504,8 +471,7 @@ void ResultsTree::ShowFileItem(const QString &name) void ResultsTree::contextMenuEvent(QContextMenuEvent * e) { QModelIndex index = indexAt(e->pos()); - if (index.isValid()) - { + if (index.isValid()) { bool multipleSelection = false; mSelectionModel = selectionModel(); if (mSelectionModel->selectedRows().count() > 1) @@ -523,11 +489,9 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) //member variables QSignalMapper *signalMapper = new QSignalMapper(this); - if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) - { + if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) { //Go through all applications and add them to the context menu - for (int i = 0; i < mApplications->GetApplicationCount(); i++) - { + for (int i = 0; i < mApplications->GetApplicationCount(); i++) { //Create an action for the application const Application app = mApplications->GetApplication(i); QAction *start = new QAction(app.getName(), &menu); @@ -552,10 +516,8 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) } // Add menuitems to copy full path/filename to clipboard - if (mContextItem) - { - if (mApplications->GetApplicationCount() > 0) - { + if (mContextItem) { + if (mApplications->GetApplicationCount() > 0) { menu.addSeparator(); } @@ -565,8 +527,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) QAction *copymessage = new QAction(tr("Copy message"), &menu); QAction *hide = new QAction(tr("Hide"), &menu); - if (multipleSelection) - { + if (multipleSelection) { copyfilename->setDisabled(true); copypath->setDisabled(true); copymessage->setDisabled(true); @@ -586,11 +547,9 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) //Start the menu menu.exec(e->globalPos()); - if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) - { + if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) { //Disconnect all signals - for (int i = 0; i < actions.size(); i++) - { + for (int i = 0; i < actions.size(); i++) { disconnect(actions[i], SIGNAL(triggered()), signalMapper, SLOT(map())); } @@ -607,8 +566,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) void ResultsTree::StartApplication(QStandardItem *target, int application) { //If there are no applications specified, tell the user about it - if (mApplications->GetApplicationCount() == 0) - { + if (mApplications->GetApplicationCount() == 0) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), tr("No editor application configured.\n\n" @@ -622,8 +580,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) if (application == -1) application = mApplications->GetDefaultApplication(); - if (application == -1) - { + if (application == -1) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), tr("No default editor application selected.\n\n" @@ -635,8 +592,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) } - if (target && application >= 0 && application < mApplications->GetApplicationCount() && target->parent()) - { + if (target && application >= 0 && application < mApplications->GetApplicationCount() && target->parent()) { // Make sure we are working with the first column if (target->column() != 0) target = target->parent()->child(target->row(), 0); @@ -649,25 +605,18 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) qDebug() << "Opening file: " << file; QFileInfo info(file); - if (!info.exists()) - { - if (info.isAbsolute()) - { + if (!info.exists()) { + if (info.isAbsolute()) { QMessageBox msgbox(this); msgbox.setWindowTitle("Cppcheck"); msgbox.setText(tr("Could not find the file!")); msgbox.setIcon(QMessageBox::Critical); msgbox.exec(); - } - else - { + } else { QDir checkdir(mCheckPath); - if (checkdir.isAbsolute() && checkdir.exists()) - { + if (checkdir.isAbsolute() && checkdir.exists()) { file = mCheckPath + "/" + file; - } - else - { + } else { QString dir = AskFileDir(file); dir += '/'; file = dir + file; @@ -675,8 +624,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) } } - if (file.indexOf(" ") > -1) - { + if (file.indexOf(" ") > -1) { file.insert(0, "\""); file.append("\""); } @@ -695,10 +643,8 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) // In Windows we must surround paths including spaces with quotation marks. #ifdef Q_WS_WIN - if (program.indexOf(" ") > -1) - { - if (!program.startsWith('"') && !program.endsWith('"')) - { + if (program.indexOf(" ") > -1) { + if (!program.startsWith('"') && !program.endsWith('"')) { program.insert(0, "\""); program.append("\""); } @@ -708,8 +654,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) const QString cmdLine = QString("%1 %2").arg(program).arg(params); bool success = QProcess::startDetached(cmdLine); - if (!success) - { + if (!success) { QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(program); QMessageBox msgbox(this); @@ -750,8 +695,7 @@ void ResultsTree::CopyFullPath() void ResultsTree::CopyMessage() { - if (mContextItem) - { + if (mContextItem) { // Make sure we are working with the first column if (mContextItem->column() != 0) mContextItem = mContextItem->parent()->child(mContextItem->row(), 0); @@ -759,8 +703,7 @@ void ResultsTree::CopyMessage() QVariantMap data = mContextItem->data().toMap(); QString message; - if (data["inconclusive"].toBool()) - { + if (data["inconclusive"].toBool()) { message = tr("[Inconclusive]"); message += " "; } @@ -778,8 +721,7 @@ void ResultsTree::HideResult() QModelIndexList selectedRows = mSelectionModel->selectedRows(); QModelIndex index; - foreach(index, selectedRows) - { + foreach(index, selectedRows) { QStandardItem *item = mModel.itemFromIndex(index); //Set the "hide" flag for this item QVariantMap data = item->data().toMap(); @@ -803,8 +745,7 @@ void ResultsTree::QuickStartApplication(const QModelIndex &index) void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) { - if (target) - { + if (target) { // Make sure we are working with the first column if (target->column() != 0) target = target->parent()->child(target->row(), 0); @@ -815,8 +756,7 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) //Replace (file) with filename QString file = data["file"].toString(); pathStr = QDir::toNativeSeparators(file); - if (!fullPath) - { + if (!fullPath) { QFileInfo fi(pathStr); pathStr = fi.fileName(); } @@ -828,8 +768,7 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) QString ResultsTree::SeverityToIcon(Severity::SeverityType severity) const { - switch (severity) - { + switch (severity) { case Severity::error: return ":images/dialog-error.png"; case Severity::style: @@ -852,8 +791,7 @@ void ResultsTree::SaveResults(Report *report) { report->WriteHeader(); - for (int i = 0; i < mModel.rowCount(); i++) - { + for (int i = 0; i < mModel.rowCount(); i++) { QStandardItem *item = mModel.item(i, 0); if (!isRowHidden(i, item->index())) SaveErrors(report, item); @@ -864,22 +802,18 @@ void ResultsTree::SaveResults(Report *report) void ResultsTree::SaveErrors(Report *report, QStandardItem *item) { - if (!item) - { + if (!item) { return; } - for (int i = 0; i < item->rowCount(); i++) - { + for (int i = 0; i < item->rowCount(); i++) { QStandardItem *error = item->child(i, 0); - if (!error) - { + if (!error) { continue; } - if (isRowHidden(i, item->index()) && !mSaveAllErrors) - { + if (isRowHidden(i, item->index()) && !mSaveAllErrors) { continue; } @@ -900,8 +834,7 @@ void ResultsTree::SaveErrors(Report *report, QStandardItem *item) item.files << file; item.lines << line; - for (int j = 0; j < error->rowCount(); j++) - { + for (int j = 0; j < error->rowCount(); j++) { QStandardItem *child_error = error->child(j, 0); //Get error's user data QVariant child_userdata = child_error->data(); @@ -923,8 +856,7 @@ void ResultsTree::UpdateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors) { - if (mShowFullPath != showFullPath) - { + if (mShowFullPath != showFullPath) { mShowFullPath = showFullPath; RefreshFilePaths(); } @@ -940,8 +872,7 @@ void ResultsTree::SetCheckDirectory(const QString &dir) QString ResultsTree::StripPath(const QString &path, bool saving) { - if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) - { + if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) { return QString(path); } @@ -951,8 +882,7 @@ QString ResultsTree::StripPath(const QString &path, bool saving) void ResultsTree::RefreshFilePaths(QStandardItem *item) { - if (!item) - { + if (!item) { return; } @@ -960,13 +890,11 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) bool updated = false; //Loop through all errors within this file - for (int i = 0; i < item->rowCount(); i++) - { + for (int i = 0; i < item->rowCount(); i++) { //Get error i QStandardItem *error = item->child(i, 0); - if (!error) - { + if (!error) { continue; } @@ -982,15 +910,12 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) error->setText(StripPath(file, false)); //If this error has backtraces make sure the files list has enough filenames - if (error->hasChildren()) - { + if (error->hasChildren()) { //Loop through all files within the error - for (int j = 0; j < error->rowCount(); j++) - { + for (int j = 0; j < error->rowCount(); j++) { //Get file QStandardItem *child = error->child(j, 0); - if (!child) - { + if (!child) { continue; } //Get childs's user data @@ -1006,8 +931,7 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) } //if the main file hasn't been updated yet, update it now - if (!updated) - { + if (!updated) { updated = true; item->setText(error->text()); } @@ -1020,8 +944,7 @@ void ResultsTree::RefreshFilePaths() qDebug("Refreshing file paths"); //Go through all file items (these are parent items that contain the errors) - for (int i = 0; i < mModel.rowCount(); i++) - { + for (int i = 0; i < mModel.rowCount(); i++) { RefreshFilePaths(mModel.item(i, 0)); } } diff --git a/gui/resultstree.h b/gui/resultstree.h index ceae73a72..c8a239b54 100644 --- a/gui/resultstree.h +++ b/gui/resultstree.h @@ -46,8 +46,7 @@ class QItemSelectionModel; * @brief Cppcheck's results are shown in this tree * */ -class ResultsTree : public QTreeView -{ +class ResultsTree : public QTreeView { Q_OBJECT public: ResultsTree(QWidget * parent = 0); diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp index bd4a692e3..b23ae55c5 100644 --- a/gui/resultsview.cpp +++ b/gui/resultsview.cpp @@ -121,8 +121,7 @@ void ResultsView::FilterResults(const QString& filter) void ResultsView::Save(const QString &filename, Report::Type type) { - if (!mErrorsFound) - { + if (!mErrorsFound) { QMessageBox msgBox; msgBox.setText(tr("No errors found, nothing to save.")); msgBox.setIcon(QMessageBox::Critical); @@ -131,8 +130,7 @@ void ResultsView::Save(const QString &filename, Report::Type type) Report *report = NULL; - switch (type) - { + switch (type) { case Report::CSV: report = new CsvReport(filename, this); break; @@ -147,12 +145,10 @@ void ResultsView::Save(const QString &filename, Report::Type type) break; } - if (report) - { + if (report) { if (report->Create()) mUI.mTree->SaveResults(report); - else - { + else { QMessageBox msgBox; msgBox.setText(tr("Failed to save the report.")); msgBox.setIcon(QMessageBox::Critical); @@ -160,9 +156,7 @@ void ResultsView::Save(const QString &filename, Report::Type type) } delete report; report = NULL; - } - else - { + } else { QMessageBox msgBox; msgBox.setText(tr("Failed to save the report.")); msgBox.setIcon(QMessageBox::Critical); @@ -198,11 +192,9 @@ void ResultsView::CheckingFinished() mUI.mProgress->setFormat("%p%"); //Should we inform user of non visible/not found errors? - if (mShowNoErrorsMessage) - { + if (mShowNoErrorsMessage) { //Tell user that we found no errors - if (!mErrorsFound) - { + if (!mErrorsFound) { QMessageBox msg(QMessageBox::Information, tr("Cppcheck"), tr("No errors found."), @@ -211,8 +203,7 @@ void ResultsView::CheckingFinished() msg.exec(); } //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"\ "To toggle what kind of errors are shown, open view menu."); QMessageBox msg(QMessageBox::Information, @@ -257,8 +248,7 @@ void ResultsView::DisableProgressbar() void ResultsView::ReadErrorsXml(const QString &filename) { const int version = XmlReport::determineVersion(filename); - if (version == 0) - { + if (version == 0) { QMessageBox msgBox; msgBox.setText(tr("Failed to read the report.")); msgBox.setIcon(QMessageBox::Critical); @@ -273,12 +263,10 @@ void ResultsView::ReadErrorsXml(const QString &filename) report = new XmlReportV2(filename, this); QList errors; - if (report) - { + if (report) { if (report->Open()) errors = report->Read(); - else - { + else { QMessageBox msgBox; msgBox.setText(tr("Failed to read the report.")); msgBox.setIcon(QMessageBox::Critical); @@ -286,9 +274,7 @@ void ResultsView::ReadErrorsXml(const QString &filename) } delete report; report = NULL; - } - else - { + } else { QMessageBox msgBox; msgBox.setText(tr("Failed to read the report.")); msgBox.setIcon(QMessageBox::Critical); @@ -296,8 +282,7 @@ void ResultsView::ReadErrorsXml(const QString &filename) } ErrorItem item; - foreach(item, errors) - { + foreach(item, errors) { mUI.mTree->AddErrorItem(item); } mUI.mTree->SetCheckDirectory(""); @@ -308,8 +293,7 @@ void ResultsView::UpdateDetails(const QModelIndex &index) QStandardItemModel *model = qobject_cast(mUI.mTree->model()); QStandardItem *item = model->itemFromIndex(index); - if (!item) - { + if (!item) { mUI.mDetails->setText(""); return; } @@ -321,8 +305,7 @@ void ResultsView::UpdateDetails(const QModelIndex &index) QVariantMap data = item->data().toMap(); // If there is no severity data then it is a parent item without summary and message - if (!data.contains("severity")) - { + if (!data.contains("severity")) { mUI.mDetails->setText(""); return; } diff --git a/gui/resultsview.h b/gui/resultsview.h index 72ad81c40..480ccc4bf 100644 --- a/gui/resultsview.h +++ b/gui/resultsview.h @@ -41,8 +41,7 @@ class CheckStatistics; * @brief Widget to show cppcheck progressbar and result * */ -class ResultsView : public QWidget -{ +class ResultsView : public QWidget { Q_OBJECT public: @@ -147,8 +146,7 @@ public: * @brief Return checking statistics. * @return Pointer to checking statistics. */ - CheckStatistics *GetStatistics() const - { + CheckStatistics *GetStatistics() const { return mStatistics; } @@ -156,8 +154,7 @@ public: * @brief Return Showtypes. * @return Pointer to Showtypes. */ - ShowTypes * GetShowTypes() const - { + ShowTypes * GetShowTypes() const { return &mUI.mTree->mShowSeverities; } diff --git a/gui/settingsdialog.cpp b/gui/settingsdialog.cpp index 259af4f76..8f8c4d15b 100644 --- a/gui/settingsdialog.cpp +++ b/gui/settingsdialog.cpp @@ -108,8 +108,7 @@ void SettingsDialog::InitIncludepathsList() QSettings settings; const QString allPaths = settings.value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString(); const QStringList paths = allPaths.split(";", QString::SkipEmptyParts); - foreach(QString path, paths) - { + foreach(QString path, paths) { AddIncludePath(path); } } @@ -118,8 +117,7 @@ void SettingsDialog::InitTranslationsList() { const QString current = mTranslator->GetCurrentLanguage(); QList translations = mTranslator->GetTranslations(); - foreach(TranslationInfo translation, translations) - { + foreach(TranslationInfo translation, translations) { QListWidgetItem *item = new QListWidgetItem; item->setText(translation.mName); item->setData(LangCodeRole, QVariant(translation.mCode)); @@ -131,8 +129,7 @@ void SettingsDialog::InitTranslationsList() Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) const { - if (yes) - { + if (yes) { return Qt::Checked; } return Qt::Unchecked; @@ -140,8 +137,7 @@ Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) const bool SettingsDialog::CheckStateToBool(Qt::CheckState state) const { - if (state == Qt::Checked) - { + if (state == Qt::Checked) { return true; } return false; @@ -165,8 +161,7 @@ void SettingsDialog::SaveSettings() void SettingsDialog::SaveSettingValues() { int jobs = mUI.mJobs->text().toInt(); - if (jobs <= 0) - { + if (jobs <= 0) { jobs = 1; } @@ -187,8 +182,7 @@ void SettingsDialog::SaveSettingValues() const int count = mUI.mListIncludePaths->count(); QString includePaths; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { QListWidgetItem *item = mUI.mListIncludePaths->item(i); includePaths += item->text(); includePaths += ";"; @@ -207,8 +201,7 @@ void SettingsDialog::AddApplication() Application app; ApplicationDialog dialog(tr("Add a new application"), app, this); - if (dialog.exec() == QDialog::Accepted) - { + if (dialog.exec() == QDialog::Accepted) { const Application app = dialog.GetApplication(); mTempApplications->AddApplication(app); mUI.mListWidget->addItem(app.getName()); @@ -218,8 +211,7 @@ void SettingsDialog::AddApplication() void SettingsDialog::RemoveApplication() { QList selected = mUI.mListWidget->selectedItems(); - foreach(QListWidgetItem *item, selected) - { + foreach(QListWidgetItem *item, selected) { const int removeIndex = mUI.mListWidget->row(item); const int currentDefault = mTempApplications->GetDefaultApplication(); mTempApplications->RemoveApplication(removeIndex); @@ -238,14 +230,12 @@ void SettingsDialog::EditApplication() { QList selected = mUI.mListWidget->selectedItems(); QListWidgetItem *item = 0; - foreach(item, selected) - { + foreach(item, selected) { int row = mUI.mListWidget->row(item); const Application app = mTempApplications->GetApplication(row); ApplicationDialog dialog(tr("Modify an application"), app, this); - if (dialog.exec() == QDialog::Accepted) - { + if (dialog.exec() == QDialog::Accepted) { const Application app2 = dialog.GetApplication(); mTempApplications->SetApplication(row, app2); item->setText(app2.getName()); @@ -256,8 +246,7 @@ void SettingsDialog::EditApplication() void SettingsDialog::DefaultApplication() { QList selected = mUI.mListWidget->selectedItems(); - if (selected.size() > 0) - { + if (selected.size() > 0) { int index = mUI.mListWidget->row(selected[0]); mTempApplications->SetDefault(index); mUI.mListWidget->clear(); @@ -268,12 +257,10 @@ void SettingsDialog::DefaultApplication() void SettingsDialog::PopulateApplicationList() { const int defapp = mTempApplications->GetDefaultApplication(); - for (int i = 0; i < mTempApplications->GetApplicationCount(); i++) - { + for (int i = 0; i < mTempApplications->GetApplicationCount(); i++) { Application app = mTempApplications->GetApplication(i); QString name = app.getName(); - if (i == defapp) - { + if (i == defapp) { name += " "; name += tr("[Default]"); } @@ -284,8 +271,7 @@ void SettingsDialog::PopulateApplicationList() // first item. if (defapp == -1) mUI.mListWidget->setCurrentRow(0); - else - { + else { if (mTempApplications->GetApplicationCount() > defapp) mUI.mListWidget->setCurrentRow(defapp); else @@ -325,8 +311,7 @@ void SettingsDialog::AddIncludePath() tr("Select include directory"), QString()); - if (!selectedDir.isEmpty()) - { + if (!selectedDir.isEmpty()) { AddIncludePath(selectedDir); } } diff --git a/gui/settingsdialog.h b/gui/settingsdialog.h index ec2a1347a..6c09fd0ba 100644 --- a/gui/settingsdialog.h +++ b/gui/settingsdialog.h @@ -36,8 +36,7 @@ class TranslationHandler; * @brief Settings dialog * */ -class SettingsDialog : public QDialog -{ +class SettingsDialog : public QDialog { Q_OBJECT public: SettingsDialog(ApplicationList *list, diff --git a/gui/showtypes.cpp b/gui/showtypes.cpp index b1a6e6883..9b8856b05 100644 --- a/gui/showtypes.cpp +++ b/gui/showtypes.cpp @@ -33,8 +33,7 @@ ShowTypes::~ShowTypes() ShowTypes::ShowType ShowTypes::SeverityToShowType(Severity::SeverityType severity) { - switch (severity) - { + switch (severity) { case Severity::none: return ShowTypes::ShowNone; case Severity::error: @@ -58,8 +57,7 @@ ShowTypes::ShowType ShowTypes::SeverityToShowType(Severity::SeverityType severit Severity::SeverityType ShowTypes::ShowTypeToSeverity(ShowTypes::ShowType type) { - switch (type) - { + switch (type) { case ShowTypes::ShowStyle: return Severity::style; break; @@ -95,8 +93,7 @@ Severity::SeverityType ShowTypes::ShowTypeToSeverity(ShowTypes::ShowType type) ShowTypes::ShowType ShowTypes::VariantToShowType(const QVariant &data) { const int value = data.toInt(); - if (value < ShowTypes::ShowStyle || value > ShowTypes::ShowErrors) - { + if (value < ShowTypes::ShowStyle || value > ShowTypes::ShowErrors) { return ShowTypes::ShowNone; } return (ShowTypes::ShowType)value; diff --git a/gui/showtypes.h b/gui/showtypes.h index 197fd3100..d04f2c2f3 100644 --- a/gui/showtypes.h +++ b/gui/showtypes.h @@ -34,15 +34,13 @@ * Notice that the "visibility" settings are automatically loaded when the * class is constructed and saved when the class is destroyed. */ -class ShowTypes -{ +class ShowTypes { public: /** * @brief Show types we have (i.e. severities in the GUI). */ - enum ShowType - { + enum ShowType { ShowStyle = 0, ShowWarnings, ShowPerformance, diff --git a/gui/statsdialog.cpp b/gui/statsdialog.cpp index 903aed807..5a2660ecf 100644 --- a/gui/statsdialog.cpp +++ b/gui/statsdialog.cpp @@ -38,15 +38,12 @@ StatsDialog::StatsDialog(QWidget *parent) void StatsDialog::setProject(const Project& project) { ProjectFile *projectFile = project.GetProjectFile(); - if (projectFile) - { + if (projectFile) { mUI.mProject->setText(projectFile->GetRootPath()); mUI.mPaths->setText(projectFile->GetCheckPaths().join(";")); mUI.mIncludePaths->setText(projectFile->GetIncludeDirs().join(";")); mUI.mDefines->setText(projectFile->GetDefines().join(";")); - } - else - { + } else { mUI.mProject->setText(""); mUI.mPaths->setText(""); mUI.mIncludePaths->setText(""); @@ -96,8 +93,7 @@ void StatsDialog::setScanDuration(double seconds) void StatsDialog::copyToClipboard() { QClipboard *clipboard = QApplication::clipboard(); - if (clipboard) - { + if (clipboard) { const QString projSettings(tr("Project Settings")); const QString project(tr("Project")); const QString paths(tr("Paths")); diff --git a/gui/statsdialog.h b/gui/statsdialog.h index 341a9d6f1..26f0b5cd5 100644 --- a/gui/statsdialog.h +++ b/gui/statsdialog.h @@ -32,8 +32,7 @@ class CheckStatistics; * @brief A dialog that shows project and scan statistics. * */ -class StatsDialog : public QDialog -{ +class StatsDialog : public QDialog { Q_OBJECT public: StatsDialog(QWidget *parent = 0); diff --git a/gui/test/benchmark/simple/benchmarksimple.cpp b/gui/test/benchmark/simple/benchmarksimple.cpp index 86e23a6ff..24877e2b3 100644 --- a/gui/test/benchmark/simple/benchmarksimple.cpp +++ b/gui/test/benchmark/simple/benchmarksimple.cpp @@ -39,8 +39,7 @@ void BenchmarkSimple::tokenize() // tokenize.. Tokenizer tokenizer(&settings, this); std::istringstream istr(data.constData()); - QBENCHMARK - { + QBENCHMARK { tokenizer.tokenize(istr, "test.cpp"); } } @@ -57,8 +56,7 @@ void BenchmarkSimple::simplify() Tokenizer tokenizer(&settings, this); std::istringstream istr(data.constData()); tokenizer.tokenize(istr, "test.cpp"); - QBENCHMARK - { + QBENCHMARK { tokenizer.simplifyTokenList(); } } @@ -74,8 +72,7 @@ void BenchmarkSimple::tokenizeAndSimplify() // tokenize.. Tokenizer tokenizer(&settings, this); std::istringstream istr(data.constData()); - QBENCHMARK - { + QBENCHMARK { tokenizer.tokenize(istr, "test.cpp"); tokenizer.simplifyTokenList(); } diff --git a/gui/test/benchmark/simple/benchmarksimple.h b/gui/test/benchmark/simple/benchmarksimple.h index 1bb0ea08f..bb880592f 100644 --- a/gui/test/benchmark/simple/benchmarksimple.h +++ b/gui/test/benchmark/simple/benchmarksimple.h @@ -20,8 +20,7 @@ #include #include "errorlogger.h" -class BenchmarkSimple: public QObject, public ErrorLogger -{ +class BenchmarkSimple: public QObject, public ErrorLogger { Q_OBJECT private slots: @@ -32,10 +31,8 @@ private slots: private: // Empty implementations of ErrorLogger methods. // We don't care about the output in the benchmark tests. - void reportOut(const std::string & outmsg) - { + void reportOut(const std::string & outmsg) { } - void reportErr(const ErrorLogger::ErrorMessage &msg) - { + void reportErr(const ErrorLogger::ErrorMessage &msg) { } }; diff --git a/gui/test/data/benchmark/simple.cpp b/gui/test/data/benchmark/simple.cpp index 719b1f0d5..8b2ea012a 100644 --- a/gui/test/data/benchmark/simple.cpp +++ b/gui/test/data/benchmark/simple.cpp @@ -30,9 +30,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckOther instance; +namespace { + CheckOther instance; } //--------------------------------------------------------------------------- @@ -42,12 +41,9 @@ void CheckOther::checkIncrementBoolean() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "%var% ++")) - { - if (tok->varId()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "%var% ++")) { + if (tok->varId()) { const Token *declTok = Token::findmatch(_tokenizer->tokens(), "bool %varid%", tok->varId()); if (declTok) incrementBooleanError(tok); @@ -74,10 +70,8 @@ void CheckOther::clarifyCalculation() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (tok->strAt(1) == "?") - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (tok->strAt(1) == "?") { // condition const Token *cond = tok; if (cond->isName() || cond->isNumber()) @@ -102,12 +96,9 @@ void CheckOther::clarifyCalculation() continue; // first multiplication operand - if (cond->str() == ")") - { + if (cond->str() == ")") { clarifyCalculationError(cond, op); - } - else if (cond->isName() || cond->isNumber()) - { + } else if (cond->isName() || cond->isNumber()) { if (Token::Match(cond->previous(),("return|=|+|-|,|(|"+op).c_str())) clarifyCalculationError(cond, op); } @@ -140,18 +131,14 @@ void CheckOther::clarifyCondition() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "( %var% =")) - { - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "( %var% =")) { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "[") tok2 = tok2->link(); else if (Token::Match(tok2, "&&|%oror%|?|)")) break; - else if (Token::Match(tok2, "<|<=|==|!=|>|>= %num% )")) - { + else if (Token::Match(tok2, "<|<=|==|!=|>|>= %num% )")) { clarifyConditionError(tok); break; } @@ -176,8 +163,7 @@ void CheckOther::warningOldStylePointerCast() (_tokenizer->tokens() && _tokenizer->fileLine(_tokenizer->tokens()).find(".cpp") == std::string::npos)) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Old style pointer casting.. if (!Token::Match(tok, "( const| %type% * ) %var%") && !Token::Match(tok, "( const| %type% * ) (| new")) @@ -205,8 +191,7 @@ void CheckOther::warningOldStylePointerCast() void CheckOther::checkFflushOnInputStream() { const Token *tok = _tokenizer->tokens(); - while (tok && ((tok = Token::findmatch(tok, "fflush ( stdin )")) != NULL)) - { + while (tok && ((tok = Token::findmatch(tok, "fflush ( stdin )")) != NULL)) { fflushOnInputStreamError(tok, tok->strAt(2)); tok = tok->tokAt(4); } @@ -214,14 +199,12 @@ void CheckOther::checkFflushOnInputStream() void CheckOther::checkSizeofForNumericParameter() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "sizeof ( %num% )") || Token::Match(tok, "sizeof ( - %num% )") || Token::Match(tok, "sizeof %num%") || Token::Match(tok, "sizeof - %num%") - ) - { + ) { sizeofForNumericParameterError(tok); } } @@ -229,50 +212,37 @@ void CheckOther::checkSizeofForNumericParameter() void CheckOther::checkSizeofForArrayParameter() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var%")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var%")) { int tokIdx = 1; - if (tok->tokAt(tokIdx)->str() == "(") - { + if (tok->tokAt(tokIdx)->str() == "(") { ++tokIdx; } - if (tok->tokAt(tokIdx)->varId() > 0) - { + if (tok->tokAt(tokIdx)->varId() > 0) { const Token *declTok = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->tokAt(tokIdx)->varId()); - if (declTok) - { - if (Token::simpleMatch(declTok->next(), "[")) - { + if (declTok) { + if (Token::simpleMatch(declTok->next(), "[")) { declTok = declTok->next()->link(); // multidimensional array - while (Token::simpleMatch(declTok->next(), "[")) - { + while (Token::simpleMatch(declTok->next(), "[")) { declTok = declTok->next()->link(); } - if (!(Token::Match(declTok->next(), "= %str%")) && !(Token::simpleMatch(declTok->next(), "= {")) && !(Token::simpleMatch(declTok->next(), ";"))) - { - if (Token::simpleMatch(declTok->next(), ",")) - { + if (!(Token::Match(declTok->next(), "= %str%")) && !(Token::simpleMatch(declTok->next(), "= {")) && !(Token::simpleMatch(declTok->next(), ";"))) { + if (Token::simpleMatch(declTok->next(), ",")) { declTok = declTok->next(); - while (!Token::simpleMatch(declTok, ";")) - { - if (Token::simpleMatch(declTok, ")")) - { + while (!Token::simpleMatch(declTok, ";")) { + if (Token::simpleMatch(declTok, ")")) { sizeofForArrayParameterError(tok); break; } - if (Token::Match(declTok, "(|[|{")) - { + if (Token::Match(declTok, "(|[|{")) { declTok = declTok->link(); } declTok = declTok->next(); } } } - if (Token::simpleMatch(declTok->next(), ")")) - { + if (Token::simpleMatch(declTok->next(), ")")) { sizeofForArrayParameterError(tok); } } @@ -302,36 +272,28 @@ void CheckOther::checkRedundantAssignmentInSwitch() // Find the beginning of a switch. E.g.: // switch (var) { ... const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern); - while (tok) - { + while (tok) { // Check the contents of the switch statement std::map varsAssigned; int indentLevel = 0; - for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { // Inside a conditional or loop. Don't mark variable accesses as being redundant. E.g.: // case 3: b = 1; // case 4: if (a) { b = 2; } // Doesn't make the b=1 redundant because it's conditional - if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) - { + if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) { const Token* endOfConditional = tok2->link(); - for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) - { + for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) { if (tok3->varId() != 0) varsAssigned.erase(tok3->varId()); else if (Token::Match(tok3, functionPattern) || Token::Match(tok3, breakPattern)) varsAssigned.clear(); } tok2 = endOfConditional; - } - else + } else ++ indentLevel; - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { -- indentLevel; // End of the switch block @@ -342,8 +304,7 @@ void CheckOther::checkRedundantAssignmentInSwitch() // Variable assignment. Report an error if it's assigned to twice before a break. E.g.: // case 3: b = 1; // <== redundant // case 4: b = 2; - if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;") && tok2->varId() != 0) - { + if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;") && tok2->varId() != 0) { std::map::iterator i = varsAssigned.find(tok2->varId()); if (i == varsAssigned.end()) varsAssigned[tok2->varId()] = tok2; @@ -379,8 +340,7 @@ void CheckOther::checkSwitchCaseFallThrough() // Find the beginning of a switch. E.g.: // switch (var) { ... const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern); - while (tok) - { + while (tok) { // Check the contents of the switch statement std::stack > ifnest; @@ -388,13 +348,10 @@ void CheckOther::checkSwitchCaseFallThrough() std::stack scopenest; bool justbreak = true; bool firstcase = true; - for (const Token *tok2 = tok->tokAt(1)->link()->tokAt(2); tok2; tok2 = tok2->next()) - { - if (Token::simpleMatch(tok2, "if (")) - { + for (const Token *tok2 = tok->tokAt(1)->link()->tokAt(2); tok2; tok2 = tok2->next()) { + if (Token::simpleMatch(tok2, "if (")) { tok2 = tok2->tokAt(1)->link()->next(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched if in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -402,15 +359,11 @@ void CheckOther::checkSwitchCaseFallThrough() } ifnest.push(std::make_pair(tok2->link(), false)); justbreak = false; - } - else if (Token::simpleMatch(tok2, "while (")) - { + } else if (Token::simpleMatch(tok2, "while (")) { tok2 = tok2->tokAt(1)->link()->next(); // skip over "do { } while ( ) ;" case - if (tok2->str() == "{") - { - if (tok2->link() == NULL) - { + if (tok2->str() == "{") { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched while in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -419,12 +372,9 @@ void CheckOther::checkSwitchCaseFallThrough() loopnest.push(tok2->link()); } justbreak = false; - } - else if (Token::simpleMatch(tok2, "do {")) - { + } else if (Token::simpleMatch(tok2, "do {")) { tok2 = tok2->tokAt(1); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched do in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -432,12 +382,9 @@ void CheckOther::checkSwitchCaseFallThrough() } loopnest.push(tok2->link()); justbreak = false; - } - else if (Token::simpleMatch(tok2, "for (")) - { + } else if (Token::simpleMatch(tok2, "for (")) { tok2 = tok2->tokAt(1)->link()->next(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched for in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -445,44 +392,29 @@ void CheckOther::checkSwitchCaseFallThrough() } loopnest.push(tok2->link()); justbreak = false; - } - else if (Token::Match(tok2, switchPattern)) - { + } else if (Token::Match(tok2, switchPattern)) { // skip over nested switch, we'll come to that soon tok2 = tok2->tokAt(1)->link()->next()->link(); - } - else if (Token::Match(tok2, breakPattern)) - { - if (loopnest.empty()) - { + } else if (Token::Match(tok2, breakPattern)) { + if (loopnest.empty()) { justbreak = true; } tok2 = Token::findmatch(tok2, ";"); - } - else if (Token::Match(tok2, "case|default")) - { - if (!justbreak && !firstcase) - { + } else if (Token::Match(tok2, "case|default")) { + if (!justbreak && !firstcase) { switchCaseFallThrough(tok2); } tok2 = Token::findmatch(tok2, ":"); justbreak = true; firstcase = false; - } - else if (tok2->str() == "{") - { + } else if (tok2->str() == "{") { scopenest.push(tok2->link()); - } - else if (tok2->str() == "}") - { - if (!ifnest.empty() && tok2 == ifnest.top().first) - { - if (tok2->next()->str() == "else") - { + } else if (tok2->str() == "}") { + if (!ifnest.empty() && tok2 == ifnest.top().first) { + if (tok2->next()->str() == "else") { tok2 = tok2->tokAt(2); ifnest.pop(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched if in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -490,25 +422,16 @@ void CheckOther::checkSwitchCaseFallThrough() } ifnest.push(std::make_pair(tok2->link(), justbreak)); justbreak = false; - } - else - { + } else { justbreak &= ifnest.top().second; ifnest.pop(); } - } - else if (!loopnest.empty() && tok2 == loopnest.top()) - { + } else if (!loopnest.empty() && tok2 == loopnest.top()) { loopnest.pop(); - } - else if (!scopenest.empty() && tok2 == scopenest.top()) - { + } else if (!scopenest.empty() && tok2 == scopenest.top()) { scopenest.pop(); - } - else - { - if (!ifnest.empty() || !loopnest.empty() || !scopenest.empty()) - { + } else { + if (!ifnest.empty() || !loopnest.empty() || !scopenest.empty()) { std::ostringstream errmsg; errmsg << "unexpected end of switch: "; errmsg << "ifnest=" << ifnest.size(); @@ -525,9 +448,7 @@ void CheckOther::checkSwitchCaseFallThrough() // end of switch block break; } - } - else if (tok2->str() != ";") - { + } else if (tok2->str() != ";") { justbreak = false; } @@ -551,20 +472,17 @@ void CheckOther::checkSelfAssignment() // POD variables.. std::set pod; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->isStandardType() && Token::Match(tok->tokAt(2), "[,);]") && tok->next()->varId()) pod.insert(tok->next()->varId()); } const char selfAssignmentPattern[] = "%var% = %var% ;|=|)"; const Token *tok = Token::findmatch(_tokenizer->tokens(), selfAssignmentPattern); - while (tok) - { + while (tok) { if (Token::Match(tok->previous(), "[;{}]") && tok->varId() && tok->varId() == tok->tokAt(2)->varId() && - pod.find(tok->varId()) != pod.end()) - { + pod.find(tok->varId()) != pod.end()) { selfAssignmentError(tok, tok->str()); } @@ -585,15 +503,11 @@ void CheckOther::checkAssignmentInAssert() const Token *tok = Token::findmatch(_tokenizer->tokens(), assertPattern); const Token *endTok = tok ? tok->next()->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { const Token* varTok = Token::findmatch(tok->tokAt(2), "%var% --|++|+=|-=|*=|/=|&=|^=|=", endTok); - if (varTok) - { + if (varTok) { assignmentInAssertError(tok, varTok->str()); - } - else if (NULL != (varTok = Token::findmatch(tok->tokAt(2), "--|++ %var%", endTok))) - { + } else if (NULL != (varTok = Token::findmatch(tok->tokAt(2), "--|++ %var%", endTok))) { assignmentInAssertError(tok, varTok->strAt(1)); } @@ -617,23 +531,19 @@ void CheckOther::checkIncorrectLogicOperator() const Token *tok = Token::findmatch(_tokenizer->tokens(), conditionPattern); const Token *endTok = tok ? tok->next()->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { // Find a pair of OR'd terms, with or without parenthesis // e.g. if (x != 3 || x != 4) const Token *logicTok = NULL, *term1Tok = NULL, *term2Tok = NULL; const Token *op1Tok = NULL, *op2Tok = NULL, *op3Tok = NULL, *nextTok = NULL; - if (NULL != (logicTok = Token::findmatch(tok, "( %any% !=|==|<|>|>=|<= %any% ) &&|%oror% ( %any% !=|==|<|>|>=|<= %any% ) %any%", endTok))) - { + if (NULL != (logicTok = Token::findmatch(tok, "( %any% !=|==|<|>|>=|<= %any% ) &&|%oror% ( %any% !=|==|<|>|>=|<= %any% ) %any%", endTok))) { term1Tok = logicTok->next(); term2Tok = logicTok->tokAt(7); op1Tok = logicTok->tokAt(2); op2Tok = logicTok->tokAt(5); op3Tok = logicTok->tokAt(8); nextTok = logicTok->tokAt(11); - } - else if (NULL != (logicTok = Token::findmatch(tok, "%any% !=|==|<|>|>=|<= %any% &&|%oror% %any% !=|==|<|>|>=|<= %any% %any%", endTok))) - { + } else if (NULL != (logicTok = Token::findmatch(tok, "%any% !=|==|<|>|>=|<= %any% &&|%oror% %any% !=|==|<|>|>=|<= %any% %any%", endTok))) { term1Tok = logicTok; term2Tok = logicTok->tokAt(4); op1Tok = logicTok->tokAt(1); @@ -642,49 +552,39 @@ void CheckOther::checkIncorrectLogicOperator() nextTok = logicTok->tokAt(7); } - if (logicTok) - { + if (logicTok) { // Find the common variable and the two different-valued constants unsigned int variableTested = 0; std::string firstConstant, secondConstant; bool varFirst1, varFirst2; unsigned int varId; - if (Token::Match(term1Tok, "%var% %any% %num%")) - { + if (Token::Match(term1Tok, "%var% %any% %num%")) { varId = term1Tok->varId(); - if (!varId) - { + if (!varId) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } varFirst1 = true; firstConstant = term1Tok->tokAt(2)->str(); - } - else if (Token::Match(term1Tok, "%num% %any% %var%")) - { + } else if (Token::Match(term1Tok, "%num% %any% %var%")) { varId = term1Tok->tokAt(2)->varId(); - if (!varId) - { + if (!varId) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } varFirst1 = false; firstConstant = term1Tok->str(); - } - else - { + } else { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } - if (Token::Match(term2Tok, "%var% %any% %num%")) - { + if (Token::Match(term2Tok, "%var% %any% %num%")) { const unsigned int varId2 = term2Tok->varId(); - if (!varId2 || varId != varId2) - { + if (!varId2 || varId != varId2) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -692,12 +592,9 @@ void CheckOther::checkIncorrectLogicOperator() varFirst2 = true; secondConstant = term2Tok->tokAt(2)->str(); variableTested = varId; - } - else if (Token::Match(term2Tok, "%num% %any% %var%")) - { + } else if (Token::Match(term2Tok, "%num% %any% %var%")) { const unsigned int varId2 = term1Tok->tokAt(2)->varId(); - if (!varId2 || varId != varId2) - { + if (!varId2 || varId != varId2) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -705,16 +602,13 @@ void CheckOther::checkIncorrectLogicOperator() varFirst2 = false; secondConstant = term2Tok->str(); variableTested = varId; - } - else - { + } else { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } - if (variableTested == 0 || firstConstant.empty() || secondConstant.empty()) - { + if (variableTested == 0 || firstConstant.empty() || secondConstant.empty()) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -722,8 +616,7 @@ void CheckOther::checkIncorrectLogicOperator() enum Position { First, Second, NA }; enum Relation { Equal, NotEqual, Less, LessEqual, More, MoreEqual }; - struct Condition - { + struct Condition { const char *before; Position position1; const char *op1TokStr; @@ -733,8 +626,7 @@ void CheckOther::checkIncorrectLogicOperator() const char *after; Relation relation; bool state; - } conditions[] = - { + } conditions[] = { { "!!&&", NA, "!=", "||", NA, "!=", "!!&&", NotEqual, true }, // (x != 1) || (x != 3) <- always true { "(", NA, "==", "&&", NA, "==", ")", NotEqual, false }, // (x == 1) && (x == 3) <- always false { "(", First, "<", "&&", First, ">", ")", LessEqual, false }, // (x < 1) && (x > 3) <- always false @@ -755,8 +647,7 @@ void CheckOther::checkIncorrectLogicOperator() { "(", Second, ">|>=", "||", Second, "<|<=", ")", More, true }, // (10 > x) || (3 < x) <- always true }; - for (unsigned int i = 0; i < (sizeof(conditions) / sizeof(conditions[0])); i++) - { + for (unsigned int i = 0; i < (sizeof(conditions) / sizeof(conditions[0])); i++) { if (!((conditions[i].position1 == NA) || (((conditions[i].position1 == First) && varFirst1) || ((conditions[i].position1 == Second) && !varFirst1)))) continue; @@ -805,13 +696,11 @@ void CheckOther::checkCatchExceptionByValue() const Token *tok = Token::findmatch(_tokenizer->tokens(), catchPattern); const Token *endTok = tok ? tok->tokAt(2)->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { // Find a pass-by-value declaration in the catch(), excluding basic types // e.g. catch (std::exception err) const Token *tokType = Token::findmatch(tok, "%type% %var% )", endTok); - if (tokType && !tokType->isStandardType()) - { + if (tokType && !tokType->isStandardType()) { catchExceptionByValueError(tokType); } @@ -827,29 +716,23 @@ void CheckOther::checkCatchExceptionByValue() void CheckOther::invalidFunctionUsage() { // strtol and strtoul.. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (!Token::Match(tok, "strtol|strtoul (")) continue; // Locate the third parameter of the function call.. int param = 1; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); else if (tok2->str() == ")") break; - else if (tok2->str() == ",") - { + else if (tok2->str() == ",") { ++param; - if (param == 3) - { - if (Token::Match(tok2, ", %num% )")) - { + if (param == 3) { + if (Token::Match(tok2, ", %num% )")) { const MathLib::bigint radix = MathLib::toLongNumber(tok2->next()->str()); - if (!(radix == 0 || (radix >= 2 && radix <= 36))) - { + if (!(radix == 0 || (radix >= 2 && radix <= 36))) { dangerousUsageStrtolError(tok2); } } @@ -860,8 +743,7 @@ void CheckOther::invalidFunctionUsage() } // sprintf|snprintf overlapping data - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Get variable id of target buffer.. unsigned int varid = 0; @@ -883,18 +765,14 @@ void CheckOther::invalidFunctionUsage() // is any source buffer overlapping the target buffer? int parlevel = 0; - while ((tok2 = tok2->next()) != NULL) - { + while ((tok2 = tok2->next()) != NULL) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { --parlevel; if (parlevel < 0) break; - } - else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) - { + } else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) { sprintfOverlappingDataError(tok2->next(), tok2->next()->str()); break; } @@ -907,8 +785,7 @@ void CheckOther::invalidScanf() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { const Token *formatToken = 0; if (Token::Match(tok, "scanf|vscanf ( %str% ,")) formatToken = tok->tokAt(2); @@ -921,21 +798,18 @@ void CheckOther::invalidScanf() // scan the string backwards, so we dont need to keep states const std::string &formatstr(formatToken->str()); - for (unsigned int i = 1; i < formatstr.length(); i++) - { + for (unsigned int i = 1; i < formatstr.length(); i++) { if (formatstr[i] == '%') format = !format; else if (!format) continue; - else if (std::isdigit(formatstr[i])) - { + else if (std::isdigit(formatstr[i])) { format = false; } - else if (std::isalpha(formatstr[i])) - { + else if (std::isalpha(formatstr[i])) { invalidScanfError(tok); format = false; } @@ -951,21 +825,15 @@ void CheckOther::checkComparisonOfBoolWithInt() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "( ! %var% ==|!= %num% )")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "( ! %var% ==|!= %num% )")) { const Token *numTok = tok->tokAt(4); - if (numTok && numTok->str() != "0") - { + if (numTok && numTok->str() != "0") { comparisonOfBoolWithIntError(numTok, tok->strAt(2)); } - } - else if (Token::Match(tok, "( %num% ==|!= ! %var% )")) - { + } else if (Token::Match(tok, "( %num% ==|!= ! %var% )")) { const Token *numTok = tok->tokAt(1); - if (numTok && numTok->str() != "0") - { + if (numTok && numTok->str() != "0") { comparisonOfBoolWithIntError(numTok, tok->strAt(4)); } } @@ -993,8 +861,7 @@ void CheckOther::checkDuplicateBreak() // Find consecutive break or continue statements. e.g.: // break; break; const Token *tok = Token::findmatch(_tokenizer->tokens(), breakPattern); - while (tok) - { + while (tok) { duplicateBreakError(tok); tok = Token::findmatch(tok->next(), breakPattern); } @@ -1065,35 +932,27 @@ void CheckOther::checkUnsignedDivision() // Check for "ivar / uvar" and "uvar / ivar" std::map varsign; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) { if (tok->tokAt(1)->isUnsigned()) varsign[tok->tokAt(2)->varId()] = 'u'; else varsign[tok->tokAt(2)->varId()] = 's'; } - else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) - { - if (tok->strAt(3)[0] == '-') - { + else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) { + if (tok->strAt(3)[0] == '-') { char sign1 = varsign[tok->tokAt(1)->varId()]; - if (sign1 == 'u') - { + if (sign1 == 'u') { udivError(tok->next()); } } } - else if (Token::Match(tok, "(|[|=|%op% %num% / %var%")) - { - if (tok->strAt(1)[0] == '-') - { + else if (Token::Match(tok, "(|[|=|%op% %num% / %var%")) { + if (tok->strAt(1)[0] == '-') { char sign2 = varsign[tok->tokAt(3)->varId()]; - if (sign2 == 'u') - { + if (sign2 == 'u') { udivError(tok->next()); } } @@ -1107,8 +966,7 @@ void CheckOther::checkUnsignedDivision() void CheckOther::checkMemsetZeroBytes() { const Token *tok = _tokenizer->tokens(); - while (tok && ((tok = Token::findmatch(tok, "memset ( %var% , %num% , 0 )")) != NULL)) - { + while (tok && ((tok = Token::findmatch(tok, "memset ( %var% , %num% , 0 )")) != NULL)) { memsetZeroBytesError(tok, tok->strAt(2)); tok = tok->tokAt(8); } @@ -1124,15 +982,13 @@ void CheckOther::checkMemsetZeroBytes() /** * @brief This class is used to capture the control flow within a function. */ -class ScopeInfo -{ +class ScopeInfo { public: ScopeInfo() : _token(NULL), _parent(NULL) { } ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { } ~ScopeInfo(); - ScopeInfo *parent() - { + ScopeInfo *parent() { return _parent; } ScopeInfo *addChild(const Token *token); @@ -1146,8 +1002,7 @@ private: ScopeInfo::~ScopeInfo() { - while (!_children.empty()) - { + while (!_children.empty()) { delete *_children.begin(); _children.pop_front(); } @@ -1166,10 +1021,8 @@ void ScopeInfo::remove(ScopeInfo *scope) { std::list::iterator it; - for (it = _children.begin(); it != _children.end(); ++it) - { - if (*it == scope) - { + for (it = _children.begin(); it != _children.end(); ++it) { + if (*it == scope) { delete *it; _children.erase(it); break; @@ -1180,14 +1033,12 @@ void ScopeInfo::remove(ScopeInfo *scope) /** * @brief This class is used create a list of variables within a function. */ -class Variables -{ +class Variables { public: enum VariableType { standard, array, pointer, reference, pointerArray, referenceArray, pointerPointer }; /** Store information about variable usage */ - class VariableUsage - { + class VariableUsage { public: VariableUsage(const Token *name = 0, VariableType type = standard, @@ -1202,20 +1053,17 @@ public: _read(read), _write(write), _modified(modified), - _allocateMemory(allocateMemory) - { + _allocateMemory(allocateMemory) { } /** variable is used.. set both read+write */ - void use() - { + void use() { _read = true; _write = true; } /** is variable unused? */ - bool unused() const - { + bool unused() const { return (_read == false && _write == false); } @@ -1232,12 +1080,10 @@ public: typedef std::map VariableMap; - void clear() - { + void clear() { _varUsage.clear(); } - VariableMap &varUsage() - { + VariableMap &varUsage() { return _varUsage; } void addVar(const Token *name, VariableType type, ScopeInfo *scope, bool write_); @@ -1252,8 +1098,7 @@ public: void modified(unsigned int varid); VariableUsage *find(unsigned int varid); void alias(unsigned int varid1, unsigned int varid2, bool replace); - void erase(unsigned int varid) - { + void erase(unsigned int varid) { _varUsage.erase(varid); } void eraseAliases(unsigned int varid); @@ -1277,8 +1122,7 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) VariableUsage *var2 = find(varid2); // alias to self - if (varid1 == varid2) - { + if (varid1 == varid2) { if (var1) var1->use(); return; @@ -1286,11 +1130,9 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) std::set::iterator i; - if (replace) - { + if (replace) { // remove var1 from all aliases - for (i = var1->_aliases.begin(); i != var1->_aliases.end(); ++i) - { + for (i = var1->_aliases.begin(); i != var1->_aliases.end(); ++i) { VariableUsage *temp = find(*i); if (temp) @@ -1302,8 +1144,7 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) } // var1 gets all var2s aliases - for (i = var2->_aliases.begin(); i != var2->_aliases.end(); ++i) - { + for (i = var2->_aliases.begin(); i != var2->_aliases.end(); ++i) { if (*i != varid1) var1->_aliases.insert(*i); } @@ -1320,13 +1161,11 @@ void Variables::clearAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { // remove usage from all aliases std::set::iterator i; - for (i = usage->_aliases.begin(); i != usage->_aliases.end(); ++i) - { + for (i = usage->_aliases.begin(); i != usage->_aliases.end(); ++i) { VariableUsage *temp = find(*i); if (temp) @@ -1342,8 +1181,7 @@ void Variables::eraseAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) @@ -1386,12 +1224,10 @@ void Variables::readAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1404,14 +1240,12 @@ void Variables::readAll(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_read = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1432,12 +1266,10 @@ void Variables::writeAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1450,14 +1282,12 @@ void Variables::writeAll(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_write = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1470,14 +1300,12 @@ void Variables::use(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->use(); std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1490,14 +1318,12 @@ void Variables::modified(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_modified = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -1508,8 +1334,7 @@ void Variables::modified(unsigned int varid) Variables::VariableUsage *Variables::find(unsigned int varid) { - if (varid) - { + if (varid) { VariableMap::iterator i = _varUsage.find(varid); if (i != _varUsage.end()) return &i->second; @@ -1522,8 +1347,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference int next = 0; // a = a + b; - if (Token::Match(tok, "%var% = %var% !!;") && tok->str() == tok->strAt(2)) - { + if (Token::Match(tok, "%var% = %var% !!;") && tok->str() == tok->strAt(2)) { return 2; } @@ -1531,8 +1355,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference const unsigned int varid1 = tok->varId(); Variables::VariableUsage *var1 = variables.find(varid1); - if (var1) - { + if (var1) { Variables::VariableUsage *var2 = 0; int start = 1; @@ -1545,8 +1368,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (Token::Match(tok->tokAt(start), "&| %var%") || Token::Match(tok->tokAt(start), "( const| struct|union| %type% *| ) &| %var%") || Token::Match(tok->tokAt(start), "( const| struct|union| %type% *| ) ( &| %var%") || - Token::Match(tok->tokAt(start), "%any% < const| struct|union| %type% *| > ( &| %var%")) - { + Token::Match(tok->tokAt(start), "%any% < const| struct|union| %type% *| > ( &| %var%")) { unsigned char offset = 0; unsigned int varid2; bool addressOf = false; @@ -1555,8 +1377,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference variables.use(tok->tokAt(start)->varId()); // use = read + write // check for C style cast - if (tok->tokAt(start)->str() == "(") - { + if (tok->tokAt(start)->str() == "(") { if (tok->tokAt(start + 1)->str() == "const") offset++; @@ -1566,29 +1387,22 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (tok->tokAt(start + 2 + offset)->str() == "*") offset++; - if (tok->tokAt(start + 3 + offset)->str() == "&") - { + if (tok->tokAt(start + 3 + offset)->str() == "&") { addressOf = true; next = start + 4 + offset; - } - else if (tok->tokAt(start + 3 + offset)->str() == "(") - { - if (tok->tokAt(start + 4 + offset)->str() == "&") - { + } else if (tok->tokAt(start + 3 + offset)->str() == "(") { + if (tok->tokAt(start + 4 + offset)->str() == "&") { addressOf = true; next = start + 5 + offset; - } - else + } else next = start + 4 + offset; - } - else + } else next = start + 3 + offset; } // check for C++ style cast else if (tok->tokAt(start)->str().find("cast") != std::string::npos && - tok->tokAt(start + 1)->str() == "<") - { + tok->tokAt(start + 1)->str() == "<") { if (tok->tokAt(start + 2)->str() == "const") offset++; @@ -1598,30 +1412,24 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (tok->tokAt(start + 3 + offset)->str() == "*") offset++; - if (tok->tokAt(start + 5 + offset)->str() == "&") - { + if (tok->tokAt(start + 5 + offset)->str() == "&") { addressOf = true; next = start + 6 + offset; - } - else + } else next = start + 5 + offset; } // check for var ? ... - else if (Token::Match(tok->tokAt(start), "%var% ?")) - { + else if (Token::Match(tok->tokAt(start), "%var% ?")) { next = start; } // no cast - else - { - if (tok->tokAt(start)->str() == "&") - { + else { + if (tok->tokAt(start)->str() == "&") { addressOf = true; next = start + 1; - } - else if (tok->tokAt(start)->str() == "new") + } else if (tok->tokAt(start)->str() == "new") return 0; else next = start; @@ -1631,18 +1439,14 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference varid2 = tok->tokAt(next)->varId(); var2 = variables.find(varid2); - if (var2) // local variable (alias or read it) - { - if (var1->_type == Variables::pointer) - { + if (var2) { // local variable (alias or read it) + if (var1->_type == Variables::pointer) { if (dereference) variables.read(varid2); - else - { + else { if (addressOf || var2->_type == Variables::array || - var2->_type == Variables::pointer) - { + var2->_type == Variables::pointer) { bool replace = true; // check if variable declared in same scope @@ -1650,23 +1454,20 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference replace = true; // not in same scope as declaration - else - { + else { std::set::iterator assignment; // check for an assignment in this scope assignment = var1->_assignments.find(scope); // no other assignment in this scope - if (assignment == var1->_assignments.end()) - { + if (assignment == var1->_assignments.end()) { // nothing to replace if (var1->_assignments.empty()) replace = false; // this variable has previous assignments - else - { + else { /** * @todo determine if existing aliases should be replaced or merged */ @@ -1676,8 +1477,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference } // assignment in this scope - else - { + else { // replace when only one other assignment if (var1->_assignments.size() == 1) replace = true; @@ -1689,53 +1489,41 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference } variables.alias(varid1, varid2, replace); - } - else if (tok->tokAt(next + 1)->str() == "?") - { + } else if (tok->tokAt(next + 1)->str() == "?") { if (var2->_type == Variables::reference) variables.readAliases(varid2); else variables.read(varid2); } } - } - else if (var1->_type == Variables::reference) - { + } else if (var1->_type == Variables::reference) { variables.alias(varid1, varid2, true); - } - else - { + } else { if (var2->_type == Variables::pointer && tok->tokAt(next + 1)->str() == "[") variables.readAliases(varid2); variables.read(varid2); } - } - else // not a local variable (or an unsupported local variable) - { - if (var1->_type == Variables::pointer && !dereference) - { + } else { // not a local variable (or an unsupported local variable) + if (var1->_type == Variables::pointer && !dereference) { // check if variable declaration is in this scope if (var1->_scope == scope) variables.clearAliases(varid1); - else - { + else { std::set::iterator assignment; // check for an assignment in this scope assignment = var1->_assignments.find(scope); // no other assignment in this scope - if (assignment == var1->_assignments.end()) - { + if (assignment == var1->_assignments.end()) { /** * @todo determine if existing aliases should be discarded */ } // this assignment replaces the last assignment in this scope - else - { + else { // aliased variables in a larger scope are not supported // remove all aliases variables.clearAliases(varid1); @@ -1750,17 +1538,14 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference // check for alias to struct member // char c[10]; a.b = c; - else if (Token::Match(tok->tokAt(-2), "%var% .")) - { - if (Token::Match(tok->tokAt(2), "%var%")) - { + else if (Token::Match(tok->tokAt(-2), "%var% .")) { + if (Token::Match(tok->tokAt(2), "%var%")) { unsigned int varid2 = tok->tokAt(2)->varId(); Variables::VariableUsage *var2 = variables.find(varid2); // struct member aliased to local variable if (var2 && (var2->_type == Variables::array || - var2->_type == Variables::pointer)) - { + var2->_type == Variables::pointer)) { // erase aliased variable and all variables that alias it // to prevent false positives variables.eraseAll(varid2); @@ -1819,8 +1604,7 @@ void CheckOther::functionVariableUsage() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -1836,10 +1620,8 @@ void CheckOther::functionVariableUsage() ScopeInfo *info = &scopes; unsigned int indentlevel = 0; - for (const Token *tok = tok1; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (const Token *tok = tok1; tok; tok = tok->next()) { + if (tok->str() == "{") { // replace the head node when found if (indentlevel == 0) scopes = ScopeInfo(tok, NULL); @@ -1847,19 +1629,15 @@ void CheckOther::functionVariableUsage() else info = info->addChild(tok); ++indentlevel; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --indentlevel; info = info->parent(); if (indentlevel == 0) break; - } - else if (Token::Match(tok, "struct|union|class {") || - Token::Match(tok, "struct|union|class %type% {|:")) - { + } else if (Token::Match(tok, "struct|union|class {") || + Token::Match(tok, "struct|union|class %type% {|:")) { while (tok->str() != "{") tok = tok->next(); tok = tok->link(); @@ -1867,8 +1645,7 @@ void CheckOther::functionVariableUsage() break; } - if (Token::Match(tok, "[;{}] asm ( ) ;")) - { + if (Token::Match(tok, "[;{}] asm ( ) ;")) { variables.clear(); break; } @@ -1876,16 +1653,14 @@ void CheckOther::functionVariableUsage() // standard type declaration with possible initialization // int i; int j = 0; static int k; if (Token::Match(tok, "[;{}] static| %type% %var% ;|=") && - !Token::Match(tok->next(), "return|throw")) - { + !Token::Match(tok->next(), "return|throw")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; if (isStatic) tok = tok->next(); - if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) - { + if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) { variables.addVar(tok->next(), Variables::standard, info, tok->tokAt(2)->str() == "=" || isStatic); } @@ -1894,8 +1669,7 @@ void CheckOther::functionVariableUsage() // standard const type declaration // const int i = x; - else if (Token::Match(tok, "[;{}] const %type% %var% =")) - { + else if (Token::Match(tok, "[;{}] const %type% %var% =")) { tok = tok->next()->next(); if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) @@ -1906,8 +1680,7 @@ void CheckOther::functionVariableUsage() // std::string declaration with possible initialization // std::string s; std::string s = "string"; - else if (Token::Match(tok, "[;{}] static| std :: string %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| std :: string %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -1922,8 +1695,7 @@ void CheckOther::functionVariableUsage() // standard struct type declaration with possible initialization // struct S s; struct S s = { 0 }; static struct S s; else if (Token::Match(tok, "[;{}] static| struct %type% %var% ;|=") && - (isRecordTypeWithoutSideEffects(tok->strAt(1) == "static" ? tok->tokAt(4) : tok->tokAt(3)))) - { + (isRecordTypeWithoutSideEffects(tok->strAt(1) == "static" ? tok->tokAt(4) : tok->tokAt(3)))) { tok = tok->next(); bool isStatic = tok->str() == "static"; @@ -1940,8 +1712,7 @@ void CheckOther::functionVariableUsage() // standard type declaration and initialization using constructor // int i(0); static int j(0); else if (Token::Match(tok, "[;{}] static| %type% %var% ( %any% ) ;") && - nextIsStandardType(tok)) - { + nextIsStandardType(tok)) { tok = tok->next(); if (tok->str() == "static") @@ -1958,8 +1729,7 @@ void CheckOther::functionVariableUsage() // standard type declaration of array of with possible initialization // int i[10]; int j[2] = { 0, 1 }; static int k[2] = { 2, 3 }; else if (Token::Match(tok, "[;{}] static| const| %type% *| %var% [ %any% ] ;|=") && - nextIsStandardType(tok)) - { + nextIsStandardType(tok)) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -1969,8 +1739,7 @@ void CheckOther::functionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return" && tok->str() != "throw") - { + if (tok->str() != "return" && tok->str() != "throw") { bool isPointer = bool(tok->strAt(1) == "*"); const Token * const nametok = tok->tokAt(isPointer ? 2 : 1); @@ -1982,25 +1751,21 @@ void CheckOther::functionVariableUsage() variables.read(nametok->tokAt(2)->varId()); // look at initializers - if (Token::simpleMatch(nametok->tokAt(4), "= {")) - { + if (Token::simpleMatch(nametok->tokAt(4), "= {")) { tok = nametok->tokAt(6); - while (tok->str() != "}") - { + while (tok->str() != "}") { if (Token::Match(tok, "%var%")) variables.read(tok->varId()); tok = tok->next(); } - } - else + } else tok = nametok->tokAt(3); } } // pointer or reference declaration with possible initialization // int * i; int * j = 0; static int * k = 0; - else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -2013,8 +1778,7 @@ void CheckOther::functionVariableUsage() if (tok->strAt(1) == "::") tok = tok->tokAt(2); - if (tok->str() != "return" && tok->str() != "throw") - { + if (tok->str() != "return" && tok->str() != "throw") { Variables::VariableType type; if (tok->next()->str() == "*") @@ -2038,8 +1802,7 @@ void CheckOther::functionVariableUsage() // pointer to pointer declaration with possible initialization // int ** i; int ** j = 0; static int ** k = 0; - else if (Token::Match(tok, "[;{}] static| const| %type% * * %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% * * %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -2049,8 +1812,7 @@ void CheckOther::functionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return") - { + if (tok->str() != "return") { bool written = tok->tokAt(4)->str() == "="; variables.addVar(tok->tokAt(3), Variables::pointerPointer, info, written || isStatic); @@ -2067,8 +1829,7 @@ void CheckOther::functionVariableUsage() // pointer or reference of struct or union declaration with possible initialization // struct s * i; struct s * j = 0; static struct s * k = 0; - else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% ;|=")) { Variables::VariableType type; tok = tok->next(); @@ -2101,8 +1862,7 @@ void CheckOther::functionVariableUsage() // pointer or reference declaration with initialization using constructor // int * i(j); int * k(i); static int * l(i); else if (Token::Match(tok, "[;{}] static| const| %type% &|* %var% ( %any% ) ;") && - nextIsStandardTypeOrVoid(tok)) - { + nextIsStandardTypeOrVoid(tok)) { Variables::VariableType type; tok = tok->next(); @@ -2127,20 +1887,16 @@ void CheckOther::functionVariableUsage() variables.addVar(tok->tokAt(2), type, info, true); // check if a local variable is used to initialize this variable - if (varid > 0) - { + if (varid > 0) { Variables::VariableUsage *var = variables.find(varid); - if (type == Variables::pointer) - { + if (type == Variables::pointer) { variables.use(tok->tokAt(4)->varId()); if (var && (var->_type == Variables::array || var->_type == Variables::pointer)) var->_aliases.insert(tok->varId()); - } - else - { + } else { variables.readAll(tok->tokAt(4)->varId()); if (var) var->_aliases.insert(tok->varId()); @@ -2151,8 +1907,7 @@ void CheckOther::functionVariableUsage() // array of pointer or reference declaration with possible initialization // int * p[10]; int * q[10] = { 0 }; static int * * r[10] = { 0 }; - else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% [ %any% ] ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% [ %any% ] ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -2162,8 +1917,7 @@ void CheckOther::functionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return") - { + if (tok->str() != "return") { variables.addVar(tok->tokAt(2), tok->next()->str() == "*" ? Variables::pointerArray : Variables::referenceArray, info, tok->tokAt(6)->str() == "=" || isStatic); @@ -2178,8 +1932,7 @@ void CheckOther::functionVariableUsage() // array of pointer or reference of struct or union declaration with possible initialization // struct S * p[10]; struct T * q[10] = { 0 }; static struct S * r[10] = { 0 }; - else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% [ %any% ] ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% [ %any% ] ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -2203,28 +1956,21 @@ void CheckOther::functionVariableUsage() // Freeing memory (not considered "using" the pointer if it was also allocated in this function) else if (Token::Match(tok, "free|g_free|kfree|vfree ( %var% )") || Token::Match(tok, "delete %var% ;") || - Token::Match(tok, "delete [ ] %var% ;")) - { + Token::Match(tok, "delete [ ] %var% ;")) { unsigned int varid = 0; - if (tok->str() != "delete") - { + if (tok->str() != "delete") { varid = tok->tokAt(2)->varId(); tok = tok->tokAt(3); - } - else if (tok->strAt(1) == "[") - { + } else if (tok->strAt(1) == "[") { varid = tok->tokAt(3)->varId(); tok = tok->tokAt(4); - } - else - { + } else { varid = tok->next()->varId(); tok = tok->tokAt(2); } Variables::VariableUsage *var = variables.find(varid); - if (var && !var->_allocateMemory) - { + if (var && !var->_allocateMemory) { variables.readAll(varid); } } @@ -2234,14 +1980,12 @@ void CheckOther::functionVariableUsage() // assignment else if (Token::Match(tok, "*| (| ++|--| %var% ++|--| )| =") || - Token::Match(tok, "*| ( const| %type% *| ) %var% =")) - { + Token::Match(tok, "*| ( const| %type% *| ) %var% =")) { bool dereference = false; bool pre = false; bool post = false; - if (tok->str() == "*") - { + if (tok->str() == "*") { dereference = true; tok = tok->next(); } @@ -2252,8 +1996,7 @@ void CheckOther::functionVariableUsage() else if (tok->str() == "(") tok = tok->next(); - if (Token::Match(tok, "++|--")) - { + if (Token::Match(tok, "++|--")) { pre = true; tok = tok->next(); } @@ -2269,33 +2012,26 @@ void CheckOther::functionVariableUsage() if (pre || post) variables.use(varid1); - if (dereference) - { + if (dereference) { Variables::VariableUsage *var = variables.find(varid1); if (var && var->_type == Variables::array) variables.write(varid1); variables.writeAliases(varid1); variables.read(varid1); - } - else - { + } else { Variables::VariableUsage *var = variables.find(varid1); - if (var && var->_type == Variables::reference) - { + if (var && var->_type == Variables::reference) { variables.writeAliases(varid1); variables.read(varid1); } // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable else if (var && var->_type == Variables::pointer && - Token::Match(start, "%var% = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) - { + Token::Match(start, "%var% = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) { bool allocate = true; - if (start->strAt(2) == "new") - { + if (start->strAt(2) == "new") { // is it a user defined type? - if (!start->tokAt(3)->isStandardType()) - { + if (!start->tokAt(3)->isStandardType()) { if (!isRecordTypeWithoutSideEffects(start)) allocate = false; } @@ -2305,25 +2041,18 @@ void CheckOther::functionVariableUsage() variables.allocateMemory(varid1); else variables.write(varid1); - } - else if (varid1 && Token::Match(tok, "%varid% .", varid1)) - { + } else if (varid1 && Token::Match(tok, "%varid% .", varid1)) { variables.use(varid1); - } - else - { + } else { variables.write(varid1); } Variables::VariableUsage *var2 = variables.find(tok->varId()); - if (var2) - { - if (var2->_type == Variables::reference) - { + if (var2) { + if (var2->_type == Variables::reference) { variables.writeAliases(tok->varId()); variables.read(tok->varId()); - } - else if (tok->varId() != varid1 && Token::Match(tok, "%var% .")) + } else if (tok->varId() != varid1 && Token::Match(tok, "%var% .")) variables.read(tok->varId()); else if (tok->varId() != varid1 && var2->_type == Variables::standard && @@ -2338,8 +2067,7 @@ void CheckOther::functionVariableUsage() equal = tok->tokAt(4); // checked for chained assignments - if (tok != start && equal->str() == "=") - { + if (tok != start && equal->str() == "=") { Variables::VariableUsage *var = variables.find(tok->varId()); if (var && var->_type != Variables::reference) @@ -2350,25 +2078,19 @@ void CheckOther::functionVariableUsage() } // assignment - else if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->next()->link(), "] =")) - { + else if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->next()->link(), "] =")) { unsigned int varid = tok->varId(); const Variables::VariableUsage *var = variables.find(varid); - if (var) - { + if (var) { // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable if (var->_type == Variables::pointer && - Token::Match(tok->next()->link(), "] = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) - { + Token::Match(tok->next()->link(), "] = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) { variables.allocateMemory(varid); - } - else if (var->_type == Variables::pointer || var->_type == Variables::reference) - { + } else if (var->_type == Variables::pointer || var->_type == Variables::reference) { variables.read(varid); variables.writeAliases(varid); - } - else + } else variables.writeAll(varid); } } @@ -2388,8 +2110,7 @@ void CheckOther::functionVariableUsage() variables.use(tok->next()->link()->next()->varId()); // use = read + write // function - else if (Token::Match(tok, "%var% (")) - { + else if (Token::Match(tok, "%var% (")) { variables.read(tok->varId()); if (Token::Match(tok->tokAt(2), "%var% =")) variables.read(tok->tokAt(2)->varId()); @@ -2411,28 +2132,23 @@ void CheckOther::functionVariableUsage() else if (Token::Match(tok, "; %var% ;")) variables.readAll(tok->next()->varId()); - if (Token::Match(tok, "++|-- %var%")) - { + if (Token::Match(tok, "++|-- %var%")) { if (tok->strAt(-1) != ";") variables.use(tok->next()->varId()); else variables.modified(tok->next()->varId()); } - else if (Token::Match(tok, "%var% ++|--")) - { + else if (Token::Match(tok, "%var% ++|--")) { if (tok->strAt(-1) != ";") variables.use(tok->varId()); else variables.modified(tok->varId()); } - else if (tok->isAssignmentOp()) - { - for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) - { - if (tok2->varId()) - { + else if (tok->isAssignmentOp()) { + for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { + if (tok2->varId()) { variables.read(tok2->varId()); if (tok2->next()->isAssignmentOp()) variables.write(tok2->varId()); @@ -2443,8 +2159,7 @@ void CheckOther::functionVariableUsage() // Check usage of all variables in the current scope.. Variables::VariableMap::const_iterator it; - for (it = variables.varUsage().begin(); it != variables.varUsage().end(); ++it) - { + for (it = variables.varUsage().begin(); it != variables.varUsage().end(); ++it) { const Variables::VariableUsage &usage = it->second; const std::string &varname = usage._name->str(); @@ -2520,28 +2235,22 @@ void CheckOther::checkVariableScope() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // Walk through all tokens.. int indentlevel = 0; - for (const Token *tok = scope->classStart; tok; tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok; tok = tok->next()) { // Skip function local class and struct declarations.. - if ((tok->str() == "class") || (tok->str() == "struct") || (tok->str() == "union")) - { - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + if ((tok->str() == "class") || (tok->str() == "struct") || (tok->str() == "union")) { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { tok = tok2->link(); break; } - if (Token::Match(tok2, "[,);]")) - { + if (Token::Match(tok2, "[,);]")) { break; } } @@ -2549,19 +2258,15 @@ void CheckOther::checkVariableScope() break; } - else if (tok->str() == "{") - { + else if (tok->str() == "{") { ++indentlevel; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --indentlevel; if (indentlevel == 0) break;; } - if (indentlevel > 0 && Token::Match(tok, "[{};]")) - { + if (indentlevel > 0 && Token::Match(tok, "[{};]")) { // First token of statement.. const Token *tok1 = tok->next(); if (! tok1) @@ -2575,20 +2280,16 @@ void CheckOther::checkVariableScope() continue; // Variable declaration? - if (Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) - { + if (Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) { // Tokenizer modify "int i = 0;" to "int i; i = 0;", // so to handle this situation we just skip // initialization (see ticket #272). const unsigned int firstVarId = tok1->next()->varId(); const unsigned int secondVarId = tok1->tokAt(3)->varId(); - if (firstVarId > 0 && firstVarId == secondVarId) - { + if (firstVarId > 0 && firstVarId == secondVarId) { lookupVar(tok1->tokAt(6), tok1->strAt(1)); } - } - else if (tok1->isStandardType() && Token::Match(tok1, "%type% %var% [;=]")) - { + } else if (tok1->isStandardType() && Token::Match(tok1, "%type% %var% [;=]")) { lookupVar(tok1, tok1->strAt(1)); } } @@ -2612,30 +2313,23 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) int indentlevel = 0; int parlevel = 0; bool for_or_while = false; // is sub-scope a "for/while/etc". anything that is not "if" - while (tok) - { - if (tok->str() == "{") - { - if (tok->strAt(-1) == "=") - { - if (Token::findmatch(tok, varname.c_str(), tok->link())) - { + while (tok) { + if (tok->str() == "{") { + if (tok->strAt(-1) == "=") { + if (Token::findmatch(tok, varname.c_str(), tok->link())) { return; } tok = tok->link(); - } - else + } else ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel == 0) break; --indentlevel; - if (indentlevel == 0) - { + if (indentlevel == 0) { if (for_or_while && used2) return; used2 |= used1; @@ -2643,24 +2337,20 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) } } - else if (tok->str() == "(") - { + else if (tok->str() == "(") { ++parlevel; } - else if (tok->str() == ")") - { + else if (tok->str() == ")") { --parlevel; } // Bail out if references are used - else if (Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) - { + else if (Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) { return; } - else if (tok->str() == varname) - { + else if (tok->str() == varname) { if (indentlevel == 0) return; used1 = true; @@ -2670,14 +2360,12 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) return; } - else if (indentlevel == 0) - { + else if (indentlevel == 0) { // %unknown% ( %any% ) { // If %unknown% is anything except if, we assume // that it is a for or while loop or a macro hiding either one if (Token::simpleMatch(tok->next(), "(") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + Token::simpleMatch(tok->next()->link(), ") {")) { if (tok->str() != "if") for_or_while = true; } @@ -2686,8 +2374,7 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) for_or_while = true; // possible unexpanded macro hiding for/while.. - else if (tok->str() != "else" && Token::Match(tok->previous(), "[;{}] %type% {")) - { + else if (tok->str() != "else" && Token::Match(tok->previous(), "[;{}] %type% {")) { for_or_while = true; } @@ -2718,53 +2405,43 @@ void CheckOther::checkConstantFunctionParameter() const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // TODO: False negatives. This pattern only checks for string. // Investigate if there are other classes in the std // namespace and add them to the pattern. There are // streams for example (however it seems strange with // const stream parameter). - if (Token::Match(tok, "[,(] const std :: string %var% [,)]")) - { + if (Token::Match(tok, "[,(] const std :: string %var% [,)]")) { passedByValueError(tok, tok->strAt(5)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(8)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(14)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if (Token::Match(tok, "[,(] const %type% %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const %type% %var% [,)]")) { // Check if type is a struct or class. - if (symbolDatabase->isClassOrStruct(tok->strAt(2))) - { + if (symbolDatabase->isClassOrStruct(tok->strAt(2))) { passedByValueError(tok, tok->strAt(3)); } } @@ -2783,13 +2460,11 @@ void CheckOther::checkStructMemberUsage() return; std::string structname; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->fileIndex() != 0) continue; - if (Token::Match(tok, "struct|union %type% {")) - { + if (Token::Match(tok, "struct|union %type% {")) { structname.clear(); if (Token::simpleMatch(tok->previous(), "extern")) continue; @@ -2799,10 +2474,8 @@ void CheckOther::checkStructMemberUsage() structname = tok->strAt(1); // Bail out if struct/union contain any functions - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "(") - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == "(") { structname.clear(); break; } @@ -2830,8 +2503,7 @@ void CheckOther::checkStructMemberUsage() if (tok->str() == "}") structname.clear(); - if (!structname.empty() && Token::Match(tok, "[{;]")) - { + if (!structname.empty() && Token::Match(tok, "[{;]")) { // Declaring struct variable.. std::string varname; @@ -2853,17 +2525,14 @@ void CheckOther::checkStructMemberUsage() // Check if the struct variable is used anywhere in the file const std::string usagePattern(". " + varname); bool used = false; - for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) - { - if (Token::simpleMatch(tok2, usagePattern.c_str())) - { + for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) { + if (Token::simpleMatch(tok2, usagePattern.c_str())) { used = true; break; } } - if (! used) - { + if (! used) { unusedStructMemberError(tok->next(), structname, varname); } } @@ -2883,12 +2552,10 @@ void CheckOther::checkCharVariable() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring the variable.. if (Token::Match(tok, "[{};(,] const| char *| %var% [;=,)]") || - Token::Match(tok, "[{};(,] const| char %var% [")) - { + Token::Match(tok, "[{};(,] const| char %var% [")) { // goto 'char' token tok = tok->next(); if (tok->str() == "const") @@ -2906,37 +2573,31 @@ void CheckOther::checkCharVariable() // Check usage of char variable.. int indentlevel = 0; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { --indentlevel; if (indentlevel <= 0) break; } - if (!isPointer) - { + if (!isPointer) { std::string temp = "%var% [ " + tok->str() + " ]"; - if ((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) - { + if ((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) { charArrayIndexError(tok2->next()); break; } } - if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) - { + if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) { // is the char variable used in the calculation? if (tok2->tokAt(3)->varId() != tok->varId() && tok2->tokAt(5)->varId() != tok->varId()) continue; // it's ok with a bitwise and where the other operand is 0xff or less.. - if (tok2->strAt(4) == "&") - { + if (tok2->strAt(4) == "&") { if (tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) continue; if (tok2->tokAt(5)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(5))) @@ -2952,8 +2613,7 @@ void CheckOther::checkCharVariable() break; } - if (isPointer && Token::Match(tok2, "[;{}] %var% = %any% [&|] ( * %varid% ) ;", tok->varId())) - { + if (isPointer && Token::Match(tok2, "[;{}] %var% = %any% [&|] ( * %varid% ) ;", tok->varId())) { // it's ok with a bitwise and where the other operand is 0xff or less.. if (tok2->strAt(4) == "&" && tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) continue; @@ -2986,10 +2646,8 @@ void CheckOther::checkIncompleteStatement() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (tok->str() == "(") - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (tok->str() == "(") { tok = tok->link(); if (Token::simpleMatch(tok, ") {") && Token::simpleMatch(tok->next()->link(), "} ;")) tok = tok->next()->link(); @@ -3001,12 +2659,10 @@ void CheckOther::checkIncompleteStatement() else if (tok->str() == "{" && Token::Match(tok->tokAt(-2), "%type% %var%")) tok = tok->link(); - else if (Token::Match(tok, "[;{}] %str%") || Token::Match(tok, "[;{}] %num%")) - { + else if (Token::Match(tok, "[;{}] %str%") || Token::Match(tok, "[;{}] %num%")) { // bailout if there is a "? :" in this statement bool bailout = false; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "?") bailout = true; else if (tok2->str() == ";") @@ -3033,26 +2689,22 @@ void CheckOther::checkIncompleteStatement() void CheckOther::strPlusChar() { // Don't use this check for Java and C# programs.. - if (_tokenizer->isJavaOrCSharp()) - { + if (_tokenizer->isJavaOrCSharp()) { return; } bool charVars[10000] = {0}; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring char variable.. - if (Token::Match(tok, "char|int|short %var% [;=]")) - { + if (Token::Match(tok, "char|int|short %var% [;=]")) { unsigned int varid = tok->next()->varId(); if (varid > 0 && varid < 10000) charVars[varid] = true; } // - else if (Token::Match(tok, "[=(] %str% + %any%")) - { + else if (Token::Match(tok, "[=(] %str% + %any%")) { // char constant.. const std::string s = tok->strAt(3); if (s[0] == '\'') @@ -3068,19 +2720,15 @@ void CheckOther::strPlusChar() void CheckOther::checkZeroDivision() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "/ %num%") && MathLib::isInt(tok->next()->str()) && - MathLib::toLongNumber(tok->next()->str()) == 0L) - { + MathLib::toLongNumber(tok->next()->str()) == 0L) { zerodivError(tok); - } - else if (Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && - MathLib::isInt(tok->tokAt(4)->str()) && - MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) - { + } else if (Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && + MathLib::isInt(tok->tokAt(4)->str()) && + MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) { zerodivError(tok); } } @@ -3089,15 +2737,13 @@ void CheckOther::checkZeroDivision() void CheckOther::checkMathFunctions() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // case log(-2) if (tok->varId() == 0 && Token::Match(tok, "log|log10 ( %num% )") && MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) { mathfunctionCallError(tok); } // case log(-2.0) @@ -3105,8 +2751,7 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) - { + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) { mathfunctionCallError(tok); } @@ -3115,8 +2760,7 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && !MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) - { + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) { mathfunctionCallError(tok); } @@ -3125,45 +2769,39 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && !MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) { mathfunctionCallError(tok); } // acos( x ), asin( x ) where x is defined for intervall [-1,+1], but not beyound else if (tok->varId() == 0 && Token::Match(tok, "acos|asin ( %num% )") && - std::fabs(MathLib::toDoubleNumber(tok->tokAt(2)->str())) > 1.0) - { + std::fabs(MathLib::toDoubleNumber(tok->tokAt(2)->str())) > 1.0) { mathfunctionCallError(tok); } // sqrt( x ): if x is negative the result is undefined else if (tok->varId() == 0 && Token::Match(tok, "sqrt|sqrtf|sqrtl ( %num% )") && - MathLib::isNegative(tok->tokAt(2)->str())) - { + MathLib::isNegative(tok->tokAt(2)->str())) { mathfunctionCallError(tok); } // atan2 ( x , y): x and y can not be zero, because this is mathematically not defined else if (tok->varId() == 0 && Token::Match(tok, "atan2 ( %num% , %num% )") && MathLib::isNullValue(tok->tokAt(2)->str()) && - MathLib::isNullValue(tok->tokAt(4)->str())) - { + MathLib::isNullValue(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } // fmod ( x , y) If y is zero, then either a range error will occur or the function will return zero (implementation-defined). else if (tok->varId() == 0 && Token::Match(tok, "fmod ( %num% , %num% )") && - MathLib::isNullValue(tok->tokAt(4)->str())) - { + MathLib::isNullValue(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } // pow ( x , y) If x is zero, and y is negative --> division by zero else if (tok->varId() == 0 && Token::Match(tok, "pow ( %num% , %num% )") && MathLib::isNullValue(tok->tokAt(2)->str()) && - MathLib::isNegative(tok->tokAt(4)->str())) - { + MathLib::isNegative(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } @@ -3174,11 +2812,9 @@ void CheckOther::checkMathFunctions() static bool isFunction(const std::string &name, const Token *startToken) { const std::string pattern1(name + " ("); - for (const Token *tok = startToken; tok; tok = tok->next()) - { + for (const Token *tok = startToken; tok; tok = tok->next()) { // skip executable scopes etc - if (tok->str() == "(") - { + if (tok->str() == "(") { tok = tok->link(); if (Token::simpleMatch(tok, ") {")) tok = tok->next()->link(); @@ -3201,8 +2837,7 @@ void CheckOther::checkMisusedScopedObject() const std::string fname = _tokenizer->getFiles()->at(0); size_t position = fname.rfind("."); - if (position != std::string::npos) - { + if (position != std::string::npos) { const std::string ext = fname.substr(position); if (ext == ".c" || ext == ".C") return; @@ -3213,22 +2848,17 @@ void CheckOther::checkMisusedScopedObject() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; unsigned int depth = 0; - for (const Token *tok = scope->classStart; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (const Token *tok = scope->classStart; tok; tok = tok->next()) { + if (tok->str() == "{") { ++depth; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --depth; if (depth == 0) break; @@ -3237,8 +2867,7 @@ void CheckOther::checkMisusedScopedObject() if (Token::Match(tok, "[;{}] %var% (") && Token::simpleMatch(tok->tokAt(2)->link(), ") ;") && symbolDatabase->isClassOrStruct(tok->next()->str()) - && !isFunction(tok->next()->str(), _tokenizer->tokens())) - { + && !isFunction(tok->next()->str(), _tokenizer->tokens())) { tok = tok->next(); misusedScopeObjectError(tok, tok->str()); tok = tok->next(); @@ -3249,23 +2878,18 @@ void CheckOther::checkMisusedScopedObject() void CheckOther::checkIncorrectStringCompare() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, ". substr ( %any% , %num% ) ==|!= %str%")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, ". substr ( %any% , %num% ) ==|!= %str%")) { size_t clen = MathLib::toLongNumber(tok->tokAt(5)->str()); size_t slen = Token::getStrLength(tok->tokAt(8)); - if (clen != slen) - { + if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", tok->tokAt(8)->str(), tok->tokAt(5)->str()); } } - if (Token::Match(tok, "%str% ==|!= %var% . substr ( %any% , %num% )")) - { + if (Token::Match(tok, "%str% ==|!= %var% . substr ( %any% , %num% )")) { size_t clen = MathLib::toLongNumber(tok->tokAt(8)->str()); size_t slen = Token::getStrLength(tok); - if (clen != slen) - { + if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", tok->str(), tok->tokAt(8)->str()); } } @@ -3292,8 +2916,7 @@ static const std::string stringifyTokens(const Token *start, const Token *end) stringified.append(tok->str()); - while (tok && tok->next() && tok != end) - { + while (tok && tok->next() && tok != end) { if (tok->isUnsigned()) stringified.append("unsigned "); else if (tok->isSigned()) @@ -3312,8 +2935,7 @@ static const std::string stringifyTokens(const Token *start, const Token *end) static bool expressionHasSideEffects(const Token *first, const Token *last) { - for (const Token *tok = first; tok != last->next(); tok = tok->next()) - { + for (const Token *tok = first; tok != last->next(); tok = tok->next()) { // check for assignment if (tok->isAssignmentOp()) return true; @@ -3340,18 +2962,15 @@ void CheckOther::checkDuplicateIf() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function for if (...) and else if (...) statements - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::simpleMatch(tok, "if (") && tok->strAt(-1) != "else" && - Token::simpleMatch(tok->next()->link(), ") {")) - { + Token::simpleMatch(tok->next()->link(), ") {")) { std::map expressionMap; // get the expression from the token stream @@ -3365,8 +2984,7 @@ void CheckOther::checkDuplicateIf() // check all the else if (...) statements while (Token::simpleMatch(tok1, "} else if (") && - Token::simpleMatch(tok1->tokAt(3)->link(), ") {")) - { + Token::simpleMatch(tok1->tokAt(3)->link(), ") {")) { // get the expression from the token stream expression = stringifyTokens(tok1->tokAt(4), tok1->tokAt(3)->link()->previous()); @@ -3374,8 +2992,7 @@ void CheckOther::checkDuplicateIf() std::map::iterator it = expressionMap.find(expression); // found a duplicate - if (it != expressionMap.end()) - { + if (it != expressionMap.end()) { // check for expressions that have side effects and ignore them if (!expressionHasSideEffects(tok1->tokAt(4), tok1->tokAt(3)->link()->previous())) duplicateIfError(it->second, tok1->next()); @@ -3424,19 +3041,16 @@ void CheckOther::checkDuplicateBranch() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function for if (..) else - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::simpleMatch(tok, "if (") && tok->strAt(-1) != "else" && Token::simpleMatch(tok->next()->link(), ") {") && - Token::simpleMatch(tok->next()->link()->next()->link(), "} else {")) - { + Token::simpleMatch(tok->next()->link()->next()->link(), "} else {")) { // save if branch code std::string branch1 = stringifyTokens(tok->next()->link()->tokAt(2), tok->next()->link()->next()->link()->previous()); @@ -3484,33 +3098,26 @@ void CheckOther::checkDuplicateExpression() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::Match(tok, "(|&&|%oror% %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% )|&&|%oror%") && - tok->strAt(1) == tok->strAt(3)) - { + tok->strAt(1) == tok->strAt(3)) { // float == float and float != float are valid NaN checks - if (Token::Match(tok->tokAt(2), "==|!=") && tok->next()->varId()) - { + if (Token::Match(tok->tokAt(2), "==|!=") && tok->next()->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId()); - if (var && var->typeStartToken() == var->typeEndToken()) - { + if (var && var->typeStartToken() == var->typeEndToken()) { if (Token::Match(var->typeStartToken(), "float|double")) continue; } } duplicateExpressionError(tok->next(), tok->tokAt(3), tok->strAt(2)); - } - else if (Token::Match(tok, "(|&&|%oror% %var% . %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% . %var% )|&&|%oror%") && - tok->strAt(1) == tok->strAt(5) && tok->strAt(3) == tok->strAt(7)) - { + } else if (Token::Match(tok, "(|&&|%oror% %var% . %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% . %var% )|&&|%oror%") && + tok->strAt(1) == tok->strAt(5) && tok->strAt(3) == tok->strAt(7)) { duplicateExpressionError(tok->next(), tok->tokAt(6), tok->strAt(4)); } } @@ -3544,15 +3151,13 @@ void CheckOther::checkAlwaysTrueOrFalseStringCompare() const char pattern2[] = "QString :: compare ( %str% , %str% )"; const Token *tok = _tokenizer->tokens(); - while (tok && (tok = Token::findmatch(tok, pattern1)) != NULL) - { + while (tok && (tok = Token::findmatch(tok, pattern1)) != NULL) { alwaysTrueFalseStringCompare(tok, tok->strAt(2), tok->strAt(4)); tok = tok->tokAt(5); } tok = _tokenizer->tokens(); - while (tok && (tok = Token::findmatch(tok, pattern2)) != NULL) - { + while (tok && (tok = Token::findmatch(tok, pattern2)) != NULL) { alwaysTrueFalseStringCompare(tok, tok->strAt(4), tok->strAt(6)); tok = tok->tokAt(7); } @@ -3564,16 +3169,13 @@ void CheckOther::alwaysTrueFalseStringCompare(const Token *tok, const std::strin const std::string string1 = (str1.size() < stringLen) ? str1 : (str1.substr(0, stringLen-2) + ".."); const std::string string2 = (str2.size() < stringLen) ? str2 : (str2.substr(0, stringLen-2) + ".."); - if (str1 == str2) - { + if (str1 == str2) { reportError(tok, Severity::warning, "staticStringCompare", "Comparison of always identical static strings.\n" "The compared strings, '" + string1 + "' and '" + string2 + "', are always identical. " "If the purpose is to compare these two strings, the comparison is unnecessary. " "If the strings are supposed to be different, then there is a bug somewhere."); - } - else - { + } else { reportError(tok, Severity::performance, "staticStringCompare", "Unnecessary comparison of static strings.\n" "The compared strings, '" + string1 + "' and '" + string2 + "', are static and always different. " @@ -3692,14 +3294,12 @@ void CheckOther::zerodivError(const Token *tok) void CheckOther::mathfunctionCallError(const Token *tok, const unsigned int numParam) { - if (tok) - { + if (tok) { if (numParam == 1) reportError(tok, Severity::error, "wrongmathcall", "Passing value " + tok->tokAt(2)->str() + " to " + tok->str() + "() leads to undefined result"); else if (numParam == 2) reportError(tok, Severity::error, "wrongmathcall", "Passing value " + tok->tokAt(2)->str() + " and " + tok->tokAt(4)->str() + " to " + tok->str() + "() leads to undefined result"); - } - else + } else reportError(tok, Severity::error, "wrongmathcall", "Passing value " " to " "() leads to undefined result"); } @@ -3713,10 +3313,8 @@ void CheckOther::sizeofsizeof() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "sizeof (| sizeof")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "sizeof (| sizeof")) { sizeofsizeofError(tok); tok = tok->next(); } @@ -3736,23 +3334,17 @@ void CheckOther::sizeofCalculation() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "sizeof (")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "sizeof (")) { unsigned int parlevel = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel <= 1) break; --parlevel; - } - else if (Token::Match(tok2, "+|/")) - { + } else if (Token::Match(tok2, "+|/")) { sizeofCalculationError(tok2); break; } @@ -3848,10 +3440,8 @@ void CheckOther::duplicateBreakError(const Token *tok) void CheckOther::checkAssignBoolToPointer() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] %var% = %bool% ;")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] %var% = %bool% ;")) { const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const Variable *var1(symbolDatabase->getVariableFromVarId(tok->next()->varId())); @@ -3882,29 +3472,22 @@ void CheckOther::checkSignOfUnsignedVariable() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { - if (Token::Match(tok, "( %var% <|<= 0 )") && tok->next()->varId()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { + if (Token::Match(tok, "( %var% <|<= 0 )") && tok->next()->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedLessThanZero(tok->next(), tok->next()->str()); - } - else if (Token::Match(tok, "( 0 > %var% )") && tok->tokAt(3)->varId()) - { + } else if (Token::Match(tok, "( 0 > %var% )") && tok->tokAt(3)->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedLessThanZero(tok->tokAt(3), tok->strAt(3)); - } - else if (Token::Match(tok, "( 0 <= %var% )") && tok->tokAt(3)->varId()) - { + } else if (Token::Match(tok, "( 0 <= %var% )") && tok->tokAt(3)->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedPositive(tok->tokAt(3), tok->strAt(3)); diff --git a/gui/test/filelist/testfilelist.h b/gui/test/filelist/testfilelist.h index 314b701ed..d9171b130 100644 --- a/gui/test/filelist/testfilelist.h +++ b/gui/test/filelist/testfilelist.h @@ -19,8 +19,7 @@ #include #include -class TestFileList: public QObject -{ +class TestFileList: public QObject { Q_OBJECT private slots: diff --git a/gui/test/projectfile/testprojectfile.h b/gui/test/projectfile/testprojectfile.h index 860161018..253b2e3d4 100644 --- a/gui/test/projectfile/testprojectfile.h +++ b/gui/test/projectfile/testprojectfile.h @@ -19,8 +19,7 @@ #include #include -class TestProjectFile: public QObject -{ +class TestProjectFile: public QObject { Q_OBJECT private slots: diff --git a/gui/test/translationhandler/testtranslationhandler.h b/gui/test/translationhandler/testtranslationhandler.h index 92402f2e2..2b1286e60 100644 --- a/gui/test/translationhandler/testtranslationhandler.h +++ b/gui/test/translationhandler/testtranslationhandler.h @@ -19,8 +19,7 @@ #include #include -class TestTranslationHandler: public QObject -{ +class TestTranslationHandler: public QObject { Q_OBJECT private slots: diff --git a/gui/test/xmlreport/testxmlreport.h b/gui/test/xmlreport/testxmlreport.h index fa97d7c6a..1f783e277 100644 --- a/gui/test/xmlreport/testxmlreport.h +++ b/gui/test/xmlreport/testxmlreport.h @@ -19,8 +19,7 @@ #include #include -class TestXmlReport: public QObject -{ +class TestXmlReport: public QObject { Q_OBJECT private slots: diff --git a/gui/test/xmlreportv1/testxmlreportv1.h b/gui/test/xmlreportv1/testxmlreportv1.h index ee8ea0fb5..1261a5b79 100644 --- a/gui/test/xmlreportv1/testxmlreportv1.h +++ b/gui/test/xmlreportv1/testxmlreportv1.h @@ -19,8 +19,7 @@ #include #include -class TestXmlReportV1: public QObject -{ +class TestXmlReportV1: public QObject { Q_OBJECT private slots: diff --git a/gui/test/xmlreportv2/testxmlreportv2.h b/gui/test/xmlreportv2/testxmlreportv2.h index bc84bcce2..817153646 100644 --- a/gui/test/xmlreportv2/testxmlreportv2.h +++ b/gui/test/xmlreportv2/testxmlreportv2.h @@ -19,8 +19,7 @@ #include #include -class TestXmlReportV2: public QObject -{ +class TestXmlReportV2: public QObject { Q_OBJECT private slots: diff --git a/gui/threadhandler.cpp b/gui/threadhandler.cpp index 185d57cdb..77590f001 100644 --- a/gui/threadhandler.cpp +++ b/gui/threadhandler.cpp @@ -50,13 +50,11 @@ void ThreadHandler::SetFiles(const QStringList &files) void ThreadHandler::Check(const Settings &settings, bool recheck) { - if (recheck && mRunningThreadCount == 0) - { + if (recheck && mRunningThreadCount == 0) { mResults.SetFiles(mLastFiles); } - if (mResults.GetFileCount() == 0 || mRunningThreadCount > 0 || settings._jobs <= 0) - { + if (mResults.GetFileCount() == 0 || mRunningThreadCount > 0 || settings._jobs <= 0) { qDebug() << "Can't start checking if there's no files to check or if check is in progress."; emit Done(); return; @@ -66,13 +64,11 @@ void ThreadHandler::Check(const Settings &settings, bool recheck) mRunningThreadCount = mThreads.size(); - if (mResults.GetFileCount() < mRunningThreadCount) - { + if (mResults.GetFileCount() < mRunningThreadCount) { mRunningThreadCount = mResults.GetFileCount(); } - for (int i = 0; i < mRunningThreadCount; i++) - { + for (int i = 0; i < mRunningThreadCount; i++) { mThreads[i]->Check(settings); } @@ -88,16 +84,14 @@ void ThreadHandler::SetThreadCount(const int count) { if (mRunningThreadCount > 0 || count == mThreads.size() || - count <= 0) - { + count <= 0) { return; } //Remove unused old threads RemoveThreads(); //Create new threads - for (int i = mThreads.size(); i < count; i++) - { + for (int i = mThreads.size(); i < count; i++) { mThreads << new CheckThread(mResults); connect(mThreads.last(), SIGNAL(Done()), this, SLOT(ThreadDone())); @@ -110,8 +104,7 @@ void ThreadHandler::SetThreadCount(const int count) void ThreadHandler::RemoveThreads() { - for (int i = 0; i < mThreads.size(); i++) - { + for (int i = 0; i < mThreads.size(); i++) { mThreads[i]->terminate(); disconnect(mThreads.last(), SIGNAL(Done()), this, SLOT(ThreadDone())); @@ -127,8 +120,7 @@ void ThreadHandler::RemoveThreads() void ThreadHandler::ThreadDone() { mRunningThreadCount--; - if (mRunningThreadCount == 0) - { + if (mRunningThreadCount == 0) { emit Done(); mScanDuration = mTime.elapsed(); @@ -137,8 +129,7 @@ void ThreadHandler::ThreadDone() void ThreadHandler::Stop() { - for (int i = 0; i < mThreads.size(); i++) - { + for (int i = 0; i < mThreads.size(); i++) { mThreads[i]->stop(); } } diff --git a/gui/threadhandler.h b/gui/threadhandler.h index a07915535..d6e4cf45e 100644 --- a/gui/threadhandler.h +++ b/gui/threadhandler.h @@ -37,8 +37,7 @@ * @brief This class handles creating threadresult and starting threads * */ -class ThreadHandler : public QObject -{ +class ThreadHandler : public QObject { Q_OBJECT public: ThreadHandler(QObject *parent = 0); diff --git a/gui/threadresult.cpp b/gui/threadresult.cpp index ac722273f..ce9fcedc5 100644 --- a/gui/threadresult.cpp +++ b/gui/threadresult.cpp @@ -49,8 +49,7 @@ void ThreadResult::FileChecked(const QString &file) mProgress += QFile(file).size(); mFilesChecked ++; - if (mMaxProgress > 0) - { + if (mMaxProgress > 0) { const int value = static_cast(PROGRESS_MAX * mProgress / mMaxProgress); const QString description = tr("%1 of %2 files checked").arg(mFilesChecked).arg(mTotalFiles); @@ -67,8 +66,7 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg) for (std::list::const_iterator tok = msg._callStack.begin(); tok != msg._callStack.end(); - ++tok) - { + ++tok) { files << QString((*tok).getfile(false).c_str()); lines << (*tok).line; } @@ -92,8 +90,7 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg) QString ThreadResult::GetNextFile() { QMutexLocker locker(&mutex); - if (mFiles.size() == 0) - { + if (mFiles.size() == 0) { return ""; } @@ -111,8 +108,7 @@ void ThreadResult::SetFiles(const QStringList &files) // Determine the total size of all of the files to check, so that we can // show an accurate progress estimate quint64 sizeOfFiles = 0; - foreach(const QString& file, files) - { + foreach(const QString& file, files) { sizeOfFiles += QFile(file).size(); } mMaxProgress = sizeOfFiles; diff --git a/gui/threadresult.h b/gui/threadresult.h index 5b4cdbd63..09200d8e1 100644 --- a/gui/threadresult.h +++ b/gui/threadresult.h @@ -35,8 +35,7 @@ class ErrorItem; * @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 public: ThreadResult(); diff --git a/gui/translationhandler.cpp b/gui/translationhandler.cpp index 7abcead4b..061b00eca 100644 --- a/gui/translationhandler.cpp +++ b/gui/translationhandler.cpp @@ -43,12 +43,9 @@ TranslationHandler::TranslationHandler(QObject *parent) : //Load English as a fallback language QTranslator *english = new QTranslator(); - if (english->load("cppcheck_en")) - { + if (english->load("cppcheck_en")) { qApp->installTranslator(english); - } - else - { + } else { qDebug() << "Failed to load English translation!"; delete english; } @@ -61,8 +58,7 @@ TranslationHandler::~TranslationHandler() const QStringList TranslationHandler::GetNames() const { QStringList names; - foreach(TranslationInfo translation, mTranslations) - { + foreach(TranslationInfo translation, mTranslations) { names.append(translation.mName); } return names; @@ -71,11 +67,9 @@ const QStringList TranslationHandler::GetNames() const bool TranslationHandler::SetLanguage(const QString &code, QString &error) { //If English is the language - if (code == "en") - { + if (code == "en") { //Just remove all extra translators - if (mTranslator) - { + if (mTranslator) { qApp->removeTranslator(mTranslator); } @@ -85,18 +79,15 @@ bool TranslationHandler::SetLanguage(const QString &code, QString &error) //Make sure the translator is otherwise valid int index = GetLanguageIndexByCode(code); - if (index == -1) - { + if (index == -1) { error = QObject::tr("Unknown language specified!"); return false; } //Load the new language - if (!mTranslator->load(mTranslations[index].mFilename)) - { + if (!mTranslator->load(mTranslations[index].mFilename)) { //If it failed, lets check if the default file exists - if (!QFile::exists(mTranslations[index].mFilename + ".qm")) - { + if (!QFile::exists(mTranslations[index].mFilename + ".qm")) { error = QObject::tr("Language file %1 not found!"); error = error.arg(mTranslations[index].mFilename + ".qm"); return false; @@ -136,8 +127,7 @@ QString TranslationHandler::SuggestLanguage() const int index = GetLanguageIndexByCode(language); //If nothing found, return English - if (index < 0) - { + if (index < 0) { return "en"; } @@ -156,10 +146,8 @@ void TranslationHandler::AddTranslation(const char *name, const char *filename) int TranslationHandler::GetLanguageIndexByCode(const QString &code) const { int index = -1; - for (int i = 0; i < mTranslations.size(); i++) - { - if (mTranslations[i].mCode == code) - { + for (int i = 0; i < mTranslations.size(); i++) { + if (mTranslations[i].mCode == code) { index = i; break; } diff --git a/gui/translationhandler.h b/gui/translationhandler.h index 2d396c579..3d0b2b8bd 100644 --- a/gui/translationhandler.h +++ b/gui/translationhandler.h @@ -31,8 +31,7 @@ * @brief Information for one translation. * */ -struct TranslationInfo -{ +struct TranslationInfo { /** * @brief Readable name for the translation (e.g. "English"). * @@ -59,8 +58,7 @@ struct TranslationInfo * track which translation is the currently active translation. * */ -class TranslationHandler : QObject -{ +class TranslationHandler : QObject { Q_OBJECT public: TranslationHandler(QObject *parent = 0); @@ -78,8 +76,7 @@ public: * @return List of available translations. * */ - QList GetTranslations() const - { + QList GetTranslations() const { return mTranslations; } diff --git a/gui/txtreport.cpp b/gui/txtreport.cpp index 3576e378a..501ccc5cc 100644 --- a/gui/txtreport.cpp +++ b/gui/txtreport.cpp @@ -34,8 +34,7 @@ TxtReport::~TxtReport() bool TxtReport::Create() { bool success = false; - if (Report::Create()) - { + if (Report::Create()) { mTxtWriter.setDevice(Report::GetFile()); success = true; } @@ -61,23 +60,19 @@ void TxtReport::WriteError(const ErrorItem &error) QString line; - for (int i = 0; i < error.lines.size(); i++) - { + for (int i = 0; i < error.lines.size(); i++) { const QString file = QDir::toNativeSeparators(error.files[i]); line += QString("[%1:%2]").arg(file).arg(error.lines[i]); - if (i < error.lines.size() - 1 && error.lines.size() > 0) - { + if (i < error.lines.size() - 1 && error.lines.size() > 0) { line += " -> "; } - if (i == error.lines.size() - 1) - { + if (i == error.lines.size() - 1) { line += ": "; } } line += QString("(%1) ").arg(GuiSeverity::toString(error.severity)); - if (error.inconclusive) - { + if (error.inconclusive) { line += tr("inconclusive"); line += " "; } diff --git a/gui/txtreport.h b/gui/txtreport.h index 398ac80a7..7e10ce97b 100644 --- a/gui/txtreport.h +++ b/gui/txtreport.h @@ -34,8 +34,7 @@ * @brief Text file report. * This report mimics the output of the command line cppcheck. */ -class TxtReport : public Report -{ +class TxtReport : public Report { Q_OBJECT public: diff --git a/gui/xmlreport.cpp b/gui/xmlreport.cpp index dc8f4be30..9c6595304 100644 --- a/gui/xmlreport.cpp +++ b/gui/xmlreport.cpp @@ -62,20 +62,15 @@ int XmlReport::determineVersion(const QString &filename) return 0; QXmlStreamReader reader(&file); - while (!reader.atEnd()) - { - switch (reader.readNext()) - { + while (!reader.atEnd()) { + switch (reader.readNext()) { case QXmlStreamReader::StartElement: - if (reader.name() == ResultElementName) - { + if (reader.name() == ResultElementName) { QXmlStreamAttributes attribs = reader.attributes(); - if (attribs.hasAttribute(QString(VersionAttribute))) - { + if (attribs.hasAttribute(QString(VersionAttribute))) { int ver = attribs.value("", VersionAttribute).toString().toInt(); return ver; - } - else + } else return 1; } break; diff --git a/gui/xmlreport.h b/gui/xmlreport.h index 74d2107d8..f044ce7aa 100644 --- a/gui/xmlreport.h +++ b/gui/xmlreport.h @@ -33,8 +33,7 @@ class QObject; /** * @brief Base class for XML report classes. */ -class XmlReport : public Report -{ +class XmlReport : public Report { public: XmlReport(const QString &filename, QObject * parent = 0); diff --git a/gui/xmlreportv1.cpp b/gui/xmlreportv1.cpp index 3589c7893..07a478cda 100644 --- a/gui/xmlreportv1.cpp +++ b/gui/xmlreportv1.cpp @@ -53,8 +53,7 @@ XmlReportV1::~XmlReportV1() bool XmlReportV1::Create() { bool success = false; - if (Report::Create()) - { + if (Report::Create()) { mXmlWriter = new QXmlStreamWriter(Report::GetFile()); success = true; } @@ -64,8 +63,7 @@ bool XmlReportV1::Create() bool XmlReportV1::Open() { bool success = false; - if (Report::Open()) - { + if (Report::Open()) { mXmlReader = new QXmlStreamReader(Report::GetFile()); success = true; } @@ -116,22 +114,18 @@ QList XmlReportV1::Read() { QList errors; bool insideResults = false; - if (!mXmlReader) - { + if (!mXmlReader) { qDebug() << "You must Open() the file before reading it!"; return errors; } - while (!mXmlReader->atEnd()) - { - switch (mXmlReader->readNext()) - { + while (!mXmlReader->atEnd()) { + switch (mXmlReader->readNext()) { case QXmlStreamReader::StartElement: if (mXmlReader->name() == ResultElementName) insideResults = true; // Read error element from inside result element - if (insideResults && mXmlReader->name() == ErrorElementName) - { + if (insideResults && mXmlReader->name() == ErrorElementName) { ErrorItem item = ReadError(mXmlReader); errors.append(item); } @@ -161,8 +155,7 @@ QList XmlReportV1::Read() ErrorItem XmlReportV1::ReadError(QXmlStreamReader *reader) { ErrorItem item; - if (reader->name().toString() == ErrorElementName) - { + if (reader->name().toString() == ErrorElementName) { QXmlStreamAttributes attribs = reader->attributes(); QString file = attribs.value("", FilenameAttribute).toString(); file = XmlReport::unquoteMessage(file); diff --git a/gui/xmlreportv1.h b/gui/xmlreportv1.h index 181b21e4b..d4362ae73 100644 --- a/gui/xmlreportv1.h +++ b/gui/xmlreportv1.h @@ -36,8 +36,7 @@ * This report outputs XML-formatted report, version 1. The XML format must match command * line version's XML output. */ -class XmlReportV1 : public XmlReport -{ +class XmlReportV1 : public XmlReport { public: XmlReportV1(const QString &filename, QObject * parent = 0); virtual ~XmlReportV1(); diff --git a/gui/xmlreportv2.cpp b/gui/xmlreportv2.cpp index 2ba68b956..f81bfdde4 100644 --- a/gui/xmlreportv2.cpp +++ b/gui/xmlreportv2.cpp @@ -59,8 +59,7 @@ XmlReportV2::~XmlReportV2() bool XmlReportV2::Create() { bool success = false; - if (Report::Create()) - { + if (Report::Create()) { mXmlWriter = new QXmlStreamWriter(Report::GetFile()); success = true; } @@ -70,8 +69,7 @@ bool XmlReportV2::Create() bool XmlReportV2::Open() { bool success = false; - if (Report::Open()) - { + if (Report::Open()) { mXmlReader = new QXmlStreamReader(Report::GetFile()); success = true; } @@ -122,8 +120,7 @@ void XmlReportV2::WriteError(const ErrorItem &error) const QString message = XmlReport::quoteMessage(error.message); mXmlWriter->writeAttribute(VerboseAttribute, message); - for (int i = 0; i < error.files.count(); i++) - { + for (int i = 0; i < error.files.count(); i++) { mXmlWriter->writeStartElement(LocationElementName); QString file = QDir::toNativeSeparators(error.files[i]); @@ -142,22 +139,18 @@ QList XmlReportV2::Read() { QList errors; bool insideResults = false; - if (!mXmlReader) - { + if (!mXmlReader) { qDebug() << "You must Open() the file before reading it!"; return errors; } - while (!mXmlReader->atEnd()) - { - switch (mXmlReader->readNext()) - { + while (!mXmlReader->atEnd()) { + switch (mXmlReader->readNext()) { case QXmlStreamReader::StartElement: if (mXmlReader->name() == ResultElementName) insideResults = true; // Read error element from inside result element - if (insideResults && mXmlReader->name() == ErrorElementName) - { + if (insideResults && mXmlReader->name() == ErrorElementName) { ErrorItem item = ReadError(mXmlReader); errors.append(item); } @@ -198,8 +191,7 @@ ErrorItem XmlReportV2::ReadError(QXmlStreamReader *reader) ErrorItem item; // Read error element from inside errors element - if (mXmlReader->name() == ErrorElementName) - { + if (mXmlReader->name() == ErrorElementName) { QXmlStreamAttributes attribs = reader->attributes(); item.errorId = attribs.value("", IdAttribute).toString(); item.severity = GuiSeverity::fromString(attribs.value("", SeverityAttribute).toString()); @@ -210,15 +202,12 @@ ErrorItem XmlReportV2::ReadError(QXmlStreamReader *reader) } bool errorRead = false; - while (!errorRead && !mXmlReader->atEnd()) - { - switch (mXmlReader->readNext()) - { + while (!errorRead && !mXmlReader->atEnd()) { + switch (mXmlReader->readNext()) { case QXmlStreamReader::StartElement: // Read location element from inside error element - if (mXmlReader->name() == LocationElementName) - { + if (mXmlReader->name() == LocationElementName) { QXmlStreamAttributes attribs = mXmlReader->attributes(); QString file = attribs.value("", FilenameAttribute).toString(); file = XmlReport::unquoteMessage(file); diff --git a/gui/xmlreportv2.h b/gui/xmlreportv2.h index 47b5a5775..3c2324ffb 100644 --- a/gui/xmlreportv2.h +++ b/gui/xmlreportv2.h @@ -37,8 +37,7 @@ * This report outputs XML-formatted report. The XML format must match command * line version's XML output. */ -class XmlReportV2 : public XmlReport -{ +class XmlReportV2 : public XmlReport { public: XmlReportV2(const QString &filename, QObject * parent = 0); virtual ~XmlReportV2(); diff --git a/lib/check.h b/lib/check.h index 2d7f5baee..186baa603 100644 --- a/lib/check.h +++ b/lib/check.h @@ -35,8 +35,7 @@ * @brief Interface class that cppcheck uses to communicate with the checks. * All checking classes must inherit from this class */ -class Check -{ +class Check { public: /** This constructor is used when registering the CheckClass */ Check(const std::string &aname); @@ -46,16 +45,14 @@ public: : _name(aname), _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger) { } - virtual ~Check() - { + virtual ~Check() { #ifndef DJGPP instances().remove(this); #endif } /** List of registered check classes. This is used by Cppcheck to run checks and generate documentation */ - static std::list &instances() - { + static std::list &instances() { static std::list _instances; return _instances; } @@ -65,8 +62,7 @@ public: * @param tokens The tokens to analyse * @param result container where results are stored */ - virtual void analyse(const Token *tokens, std::set &result) const - { + virtual void analyse(const Token *tokens, std::set &result) const { // suppress compiler warnings (void)tokens; (void)result; @@ -76,8 +72,7 @@ public: * Save analysis data - the caller ensures thread safety * @param data The data where the results are saved */ - virtual void saveAnalysisData(const std::set &data) const - { + virtual void saveAnalysisData(const std::set &data) const { // suppress compiler warnings (void)data; } @@ -93,8 +88,7 @@ public: virtual void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) = 0; /** class name, used to generate documentation */ - std::string name() const - { + std::string name() const { return _name; } @@ -106,8 +100,7 @@ public: * This is for for printout out the error list with --errorlist * @param errmsg Error message to write */ - static void reportError(const ErrorLogger::ErrorMessage &errmsg) - { + static void reportError(const ErrorLogger::ErrorMessage &errmsg) { std::cout << errmsg.toXML(true, 1) << std::endl; } @@ -118,8 +111,7 @@ protected: ErrorLogger * const _errorLogger; /** report an error */ - void reportError(const Token *tok, const Severity::SeverityType severity, const std::string &id, const std::string &msg) - { + void reportError(const Token *tok, const Severity::SeverityType severity, const std::string &id, const std::string &msg) { std::list callstack; if (tok) callstack.push_back(tok); @@ -127,14 +119,12 @@ protected: } /** report an error */ - void reportError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg) - { + void reportError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg) { reportError(callstack, severity, id, msg, false); } /** report an inconclusive error */ - void reportInconclusiveError(const Token *tok, const Severity::SeverityType severity, const std::string &id, const std::string &msg) - { + void reportInconclusiveError(const Token *tok, const Severity::SeverityType severity, const std::string &id, const std::string &msg) { std::list callstack; if (tok) callstack.push_back(tok); @@ -142,8 +132,7 @@ protected: } /** report an inconclusive error */ - void reportInconclusiveError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg) - { + void reportInconclusiveError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg) { reportError(callstack, severity, id, msg, true); } @@ -153,11 +142,9 @@ private: void operator=(const Check &); /** report an error */ - void reportError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg, bool inconclusive) - { + void reportError(const std::list &callstack, Severity::SeverityType severity, const std::string &id, std::string msg, bool inconclusive) { std::list locationList; - for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) - { + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { // --errorlist can provide null values here if (!(*it)) continue; @@ -179,16 +166,13 @@ private: }; -namespace std -{ -/** compare the names of Check classes, used when sorting the Check descendants */ -template <> struct less -{ - bool operator()(const Check *p1, const Check *p2) const - { - return (p1->name() < p2->name()); - } -}; +namespace std { + /** compare the names of Check classes, used when sorting the Check descendants */ + template <> struct less { + bool operator()(const Check *p1, const Check *p2) const { + return (p1->name() < p2->name()); + } + }; } inline Check::Check(const std::string &aname) diff --git a/lib/check64bit.cpp b/lib/check64bit.cpp index c33f49bd7..b664ba5f8 100644 --- a/lib/check64bit.cpp +++ b/lib/check64bit.cpp @@ -26,9 +26,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -Check64BitPortability instance; +namespace { + Check64BitPortability instance; } /** Is given variable a pointer or array? */ @@ -49,10 +48,8 @@ void Check64BitPortability::pointerassignment() if (!_settings->isEnabled("portability")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] %var% = %var% [;+]")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] %var% = %var% [;+]")) { const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const Variable *var1(symbolDatabase->getVariableFromVarId(tok->tokAt(1)->varId())); @@ -61,8 +58,7 @@ void Check64BitPortability::pointerassignment() if (isaddr(var1) && isint(var2) && tok->strAt(4) != "+") assignmentIntegerToAddressError(tok->next()); - else if (isint(var1) && isaddr(var2) && !tok->tokAt(3)->isPointerCompare()) - { + else if (isint(var1) && isaddr(var2) && !tok->tokAt(3)->isPointerCompare()) { // assigning address => warning // some trivial addition => warning if (Token::Match(tok->tokAt(4), "+ %any% !!;")) diff --git a/lib/check64bit.h b/lib/check64bit.h index 09d455969..ef588c8ec 100644 --- a/lib/check64bit.h +++ b/lib/check64bit.h @@ -32,30 +32,25 @@ * @brief Check for 64-bit portability issues */ -class Check64BitPortability : public Check -{ +class Check64BitPortability : public Check { public: /** This constructor is used when registering the Check64BitPortability */ - Check64BitPortability() : Check(myName()) - { + Check64BitPortability() : Check(myName()) { } /** This constructor is used when running checks. */ 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 */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { Check64BitPortability check64BitPortability(tokenizer, settings, errorLogger); check64BitPortability.pointerassignment(); } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { (void)tokenizer; (void)settings; (void)errorLogger; @@ -69,20 +64,17 @@ private: void assignmentAddressToIntegerError(const Token *tok); void assignmentIntegerToAddressError(const Token *tok); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { Check64BitPortability c(0, settings, errorLogger); c.assignmentAddressToIntegerError(0); c.assignmentIntegerToAddressError(0); } - std::string myName() const - { + std::string myName() const { return "64-bit portability"; } - std::string classInfo() const - { + std::string classInfo() const { return "Check if there is 64-bit portability issues:\n" " * assign address to/from int/long"; } diff --git a/lib/checkassignif.cpp b/lib/checkassignif.cpp index edfd06969..d2eff85e0 100644 --- a/lib/checkassignif.cpp +++ b/lib/checkassignif.cpp @@ -26,9 +26,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckAssignIf instance; +namespace { + CheckAssignIf instance; } @@ -37,13 +36,11 @@ void CheckAssignIf::assignIf() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() != "=") continue; - if (Token::Match(tok->tokAt(-2), "[;{}] %var% = %var% [&|] %num% ;")) - { + if (Token::Match(tok->tokAt(-2), "[;{}] %var% = %var% [&|] %num% ;")) { const unsigned int varid(tok->previous()->varId()); if (varid == 0) continue; @@ -54,12 +51,10 @@ void CheckAssignIf::assignIf() if (num < 0) continue; - for (const Token *tok2 = tok->tokAt(4); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(4); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "}" || tok2->str() == "=") break; - if (Token::Match(tok2,"if ( %varid% %any% %num% &&|%oror%|)", varid)) - { + if (Token::Match(tok2,"if ( %varid% %any% %num% &&|%oror%|)", varid)) { const std::string op(tok2->strAt(3)); const MathLib::bigint num2 = MathLib::toLongNumber(tok2->strAt(4)); if (op == "==" && (num & num2) != ((bitop=='&') ? num2 : num)) @@ -89,20 +84,17 @@ void CheckAssignIf::comparison() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() != "&") continue; - if (Token::Match(tok, "& %num% )| ==|!= %num% &&|%oror%|)")) - { + if (Token::Match(tok, "& %num% )| ==|!= %num% &&|%oror%|)")) { const MathLib::bigint num1 = MathLib::toLongNumber(tok->strAt(1)); if (num1 < 0) continue; const Token *compareToken = tok->tokAt(2); - if (compareToken->str() == ")") - { + if (compareToken->str() == ")") { if (!Token::Match(compareToken->link()->previous(), "(|%oror%|&&")) continue; compareToken = compareToken->next(); @@ -112,8 +104,7 @@ void CheckAssignIf::comparison() if (num2 < 0) continue; - if ((num1 & num2) != num2) - { + if ((num1 & num2) != num2) { const std::string op(compareToken->str()); comparisonError(tok, op=="==" ? false : true); } @@ -145,10 +136,8 @@ void CheckAssignIf::multiCondition() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "if ( %var% & %num% ) {")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "if ( %var% & %num% ) {")) { const unsigned int varid(tok->tokAt(2)->varId()); if (varid == 0) continue; @@ -158,8 +147,7 @@ void CheckAssignIf::multiCondition() continue; const Token *tok2 = tok->tokAt(6)->link(); - while (Token::simpleMatch(tok2, "} else { if (")) - { + while (Token::simpleMatch(tok2, "} else { if (")) { // Goto '(' const Token * const opar = tok2->tokAt(4); @@ -169,14 +157,12 @@ void CheckAssignIf::multiCondition() tok2 = tok2->next()->link(); // check condition.. - if (Token::Match(opar, "( %varid% ==|& %num% &&|%oror%|)", varid)) - { + if (Token::Match(opar, "( %varid% ==|& %num% &&|%oror%|)", varid)) { const MathLib::bigint num2 = MathLib::toLongNumber(opar->strAt(3)); if (num2 < 0) continue; - if ((num1 & num2) == num2) - { + if ((num1 & num2) == num2) { multiConditionError(opar, tok->linenr()); } } diff --git a/lib/checkassignif.h b/lib/checkassignif.h index ee6f6e801..136014e66 100644 --- a/lib/checkassignif.h +++ b/lib/checkassignif.h @@ -32,23 +32,19 @@ * @brief Check for assignment / condition mismatches */ -class CheckAssignIf : public Check -{ +class CheckAssignIf : public Check { public: /** This constructor is used when registering the CheckAssignIf */ - CheckAssignIf() : Check(myName()) - { + CheckAssignIf() : Check(myName()) { } /** This constructor is used when running checks. */ CheckAssignIf(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(myName(), tokenizer, settings, errorLogger) - { + : Check(myName(), tokenizer, settings, errorLogger) { } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckAssignIf checkAssignIf(tokenizer, settings, errorLogger); checkAssignIf.assignIf(); checkAssignIf.comparison(); @@ -70,21 +66,18 @@ private: void comparisonError(const Token *tok, bool result); void multiConditionError(const Token *tok, unsigned int line1); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckAssignIf c(0, settings, errorLogger); c.assignIfError(0, false); c.comparisonError(0, false); c.multiConditionError(0,1); } - std::string myName() const - { + std::string myName() const { return "match assignments and conditions"; } - std::string classInfo() const - { + std::string classInfo() const { return "Match assignments and conditions:\n" " * Mismatching assignment and comparison => comparison is always true/false\n" " * Mismatching lhs and rhs in comparison => comparison is always true/false\n" diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index 9a71264cc..93ff29b8e 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -31,9 +31,8 @@ // Register this check class into cppcheck by creating a static instance of it.. -namespace -{ -static CheckAutoVariables instance; +namespace { + static CheckAutoVariables instance; } @@ -56,8 +55,7 @@ bool CheckAutoVariables::isAutoVar(unsigned int varId) if (!var || !var->isLocal() || var->isStatic() || var->isArray() || var->typeEndToken()->str() == "*") return false; - if (Token::simpleMatch(var->nameToken()->previous(), "&")) - { + if (Token::simpleMatch(var->nameToken()->previous(), "&")) { // address of reference variable can be taken if the address // of the variable it points at is not a auto-var // TODO: check what the reference variable references. @@ -83,97 +81,74 @@ void CheckAutoVariables::autoVariables() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; unsigned int indentlevel = 0; - for (const Token *tok = scope->classDef->next()->link(); tok; tok = tok->next()) - { + for (const Token *tok = scope->classDef->next()->link(); tok; tok = tok->next()) { // indentlevel.. if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } //Critical assignment - if (Token::Match(tok, "[;{}] * %var% = & %var%") && errorAv(tok->tokAt(2), tok->tokAt(5))) - { + if (Token::Match(tok, "[;{}] * %var% = & %var%") && errorAv(tok->tokAt(2), tok->tokAt(5))) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(5)->varId()); if (var && (!var->isClass() || var->type())) errorAutoVariableAssignment(tok->next(), false); - } - else if (Token::Match(tok, "[;{}] %var% . %var% = & %var%")) - { + } else if (Token::Match(tok, "[;{}] %var% . %var% = & %var%")) { // TODO: check if the parameter is only changed temporarily (#2969) - if (_settings->inconclusive) - { + if (_settings->inconclusive) { const Variable * var1 = symbolDatabase->getVariableFromVarId(tok->tokAt(1)->varId()); - if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-2), "%type% *")) - { + if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-2), "%type% *")) { const Variable * var2 = symbolDatabase->getVariableFromVarId(tok->tokAt(6)->varId()); if (var2 && var2->isLocal() && !var2->isStatic() && !Token::simpleMatch(var2->typeEndToken(), "*")) errorAutoVariableAssignment(tok->next(), _settings->inconclusive); } } tok = tok->tokAt(6); - } - else if (Token::Match(tok, "[;{}] %var% . %var% = %var% ;")) - { + } else if (Token::Match(tok, "[;{}] %var% . %var% = %var% ;")) { // TODO: check if the parameter is only changed temporarily (#2969) - if (_settings->inconclusive) - { + if (_settings->inconclusive) { const Variable * var1 = symbolDatabase->getVariableFromVarId(tok->tokAt(1)->varId()); - if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-2), "%type% *")) - { + if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-2), "%type% *")) { const Variable * var2 = symbolDatabase->getVariableFromVarId(tok->tokAt(5)->varId()); if (var2 && var2->isLocal() && var2->isArray() && !var2->isStatic()) errorAutoVariableAssignment(tok->next(), _settings->inconclusive); } } tok = tok->tokAt(5); - } - else if (Token::Match(tok, "[;{}] * %var% = %var% ;")) - { + } else if (Token::Match(tok, "[;{}] * %var% = %var% ;")) { const Variable * var1 = symbolDatabase->getVariableFromVarId(tok->tokAt(2)->varId()); - if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-3), "%type% * *")) - { + if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-3), "%type% * *")) { const Variable * var2 = symbolDatabase->getVariableFromVarId(tok->tokAt(4)->varId()); if (var2 && var2->isLocal() && var2->isArray() && !var2->isStatic()) errorAutoVariableAssignment(tok->next(), false); } tok = tok->tokAt(4); - } - else if (Token::Match(tok, "[;{}] %var% [ %any% ] = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(7))) - { + } else if (Token::Match(tok, "[;{}] %var% [ %any% ] = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(7))) { errorAutoVariableAssignment(tok->next(), false); } // Critical return - else if (Token::Match(tok, "return & %var% ;") && isAutoVar(tok->tokAt(2)->varId())) - { + else if (Token::Match(tok, "return & %var% ;") && isAutoVar(tok->tokAt(2)->varId())) { errorReturnAddressToAutoVariable(tok); - } - else if (Token::Match(tok, "return & %var% [") && - Token::Match(tok->tokAt(3)->link(), "] ;") && - isAutoVarArray(tok->tokAt(2)->varId())) - { + } else if (Token::Match(tok, "return & %var% [") && + Token::Match(tok->tokAt(3)->link(), "] ;") && + isAutoVarArray(tok->tokAt(2)->varId())) { errorReturnAddressToAutoVariable(tok); - } - else if (Token::Match(tok, "return & %var% ;") && tok->tokAt(2)->varId()) - { + } else if (Token::Match(tok, "return & %var% ;") && tok->tokAt(2)->varId()) { const Variable * var1 = symbolDatabase->getVariableFromVarId(tok->tokAt(2)->varId()); if (var1 && var1->isArgument() && var1->typeEndToken()->str() != "&") errorReturnAddressOfFunctionParameter(tok, tok->strAt(2)); } // Invalid pointer deallocation - else if (Token::Match(tok, "free ( %var% ) ;") && isAutoVarArray(tok->tokAt(2)->varId())) - { + else if (Token::Match(tok, "free ( %var% ) ;") && isAutoVarArray(tok->tokAt(2)->varId())) { errorInvalidDeallocation(tok); } } @@ -188,8 +163,7 @@ void CheckAutoVariables::returnPointerToLocalArray() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -201,8 +175,7 @@ void CheckAutoVariables::returnPointerToLocalArray() tok = tok->tokAt(-2); // have we reached a function that returns a pointer - if (Token::Match(tok->tokAt(-2), "%type% *")) - { + if (Token::Match(tok->tokAt(-2), "%type% *")) { // go to the '(' const Token *tok2 = scope->classDef->next(); @@ -210,26 +183,22 @@ void CheckAutoVariables::returnPointerToLocalArray() tok2 = tok2->next()->link(); unsigned int indentlevel = 0; - for (; tok2; tok2 = tok2->next()) - { + for (; tok2; tok2 = tok2->next()) { // indentlevel.. if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // Return pointer to local array variable.. - if (Token::Match(tok2, "return %var% ;")) - { + if (Token::Match(tok2, "return %var% ;")) { const unsigned int varid = tok2->next()->varId(); const Variable *var = symbolDatabase->getVariableFromVarId(varid); - if (var && var->isLocal() && !var->isStatic() && var->isArray()) - { + if (var && var->isLocal() && !var->isStatic() && var->isArray()) { errorReturnPointerToLocalArray(tok2); } } @@ -250,17 +219,14 @@ void CheckAutoVariables::errorReturnPointerToLocalArray(const Token *tok) void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok, bool inconclusive) { - if (!inconclusive) - { + if (!inconclusive) { reportError(tok, Severity::error, "autoVariables", "Assigning address of local auto-variable to a function parameter.\n" "Dangerous assignment - function parameter takes the address of a local " "auto-variable. Local auto-variables are reserved from the stack. And the " "stack is freed when the function ends. So the pointer to a local variable " "is invalid after the function ends."); - } - else - { + } else { reportInconclusiveError(tok, Severity::error, "autoVariables", "Inconclusive: Assigning address of local auto-variable to a function parameter.\n" "Inconclusive: function parameter takes the address of a local auto-variable. " @@ -296,8 +262,7 @@ void CheckAutoVariables::returnReference() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -310,8 +275,7 @@ void CheckAutoVariables::returnReference() // have we reached a function that returns a reference? if (Token::Match(tok->tokAt(-2), "%type% &") || - Token::Match(tok->tokAt(-2), "> &")) - { + Token::Match(tok->tokAt(-2), "> &")) { // go to the '(' const Token *tok2 = scope->classDef->next(); @@ -319,35 +283,30 @@ void CheckAutoVariables::returnReference() tok2 = tok2->link(); unsigned int indentlevel = 0; - for (; tok2; tok2 = tok2->next()) - { + for (; tok2; tok2 = tok2->next()) { // indentlevel.. if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // return.. - if (Token::Match(tok2, "return %var% ;")) - { + if (Token::Match(tok2, "return %var% ;")) { // is the returned variable a local variable? const unsigned int varid = tok2->next()->varId(); const Variable *var = symbolDatabase->getVariableFromVarId(varid); - if (var && var->isLocal() && !var->isStatic()) - { + if (var && var->isLocal() && !var->isStatic()) { // report error.. errorReturnReference(tok2); } } // return reference to temporary.. - else if (returnTemporary(tok2)) - { + else if (returnTemporary(tok2)) { // report error.. errorReturnTempReference(tok2); } @@ -382,8 +341,7 @@ void CheckAutoVariables::returncstr() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -395,8 +353,7 @@ void CheckAutoVariables::returncstr() tok = tok->tokAt(-2); // have we reached a function that returns a const char * - if (Token::simpleMatch(tok->tokAt(-3), "const char *")) - { + if (Token::simpleMatch(tok->tokAt(-3), "const char *")) { // go to the '(' const Token *tok2 = scope->classDef->next(); @@ -404,35 +361,30 @@ void CheckAutoVariables::returncstr() tok2 = tok2->next()->link(); unsigned int indentlevel = 0; - for (; tok2; tok2 = tok2->next()) - { + for (; tok2; tok2 = tok2->next()) { // indentlevel.. if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // return.. - if (Token::Match(tok2, "return %var% . c_str ( ) ;")) - { + if (Token::Match(tok2, "return %var% . c_str ( ) ;")) { // is the returned variable a local variable? const unsigned int varid = tok2->next()->varId(); const Variable *var = symbolDatabase->getVariableFromVarId(varid); - if (var && var->isLocal() && !var->isStatic()) - { + if (var && var->isLocal() && !var->isStatic()) { // report error.. errorReturnAutocstr(tok2); } } // return pointer to temporary.. - else if (returnTemporary(tok2)) - { + else if (returnTemporary(tok2)) { // report error.. errorReturnTempPointer(tok2); } diff --git a/lib/checkautovariables.h b/lib/checkautovariables.h index bddfb4bc3..8a81b1a90 100644 --- a/lib/checkautovariables.h +++ b/lib/checkautovariables.h @@ -30,8 +30,7 @@ /// @{ -class CheckAutoVariables : public Check -{ +class CheckAutoVariables : public Check { public: /** This constructor is used when registering the CheckClass */ CheckAutoVariables() : Check(myName()) @@ -43,14 +42,12 @@ public: { } /** @brief Run checks against the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckAutoVariables checkAutoVariables(tokenizer, settings, errorLogger); checkAutoVariables.returnReference(); } - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckAutoVariables checkAutoVariables(tokenizer, settings, errorLogger); checkAutoVariables.autoVariables(); checkAutoVariables.returnPointerToLocalArray(); @@ -91,8 +88,7 @@ private: void errorInvalidDeallocation(const Token *tok); void errorReturnAddressOfFunctionParameter(const Token *tok, const std::string &varname); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckAutoVariables c(0,settings,errorLogger); c.errorAutoVariableAssignment(0, false); c.errorReturnAddressToAutoVariable(0); @@ -105,13 +101,11 @@ private: c.errorReturnAddressOfFunctionParameter(0, "parameter"); } - std::string myName() const - { + std::string myName() const { return "Auto Variables"; } - std::string classInfo() const - { + std::string classInfo() const { return "A pointer to a variable is only valid as long as the variable is in scope.\n" "Check:\n" "* returning a pointer to auto or temporary variable\n" diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index 4e9a7dbbe..ce93d75c8 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -40,9 +40,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckBufferOverrun instance; +namespace { + CheckBufferOverrun instance; } //--------------------------------------------------------------------------- @@ -56,8 +55,7 @@ void CheckBufferOverrun::arrayIndexOutOfBoundsError(const Token *tok, const Arra oss << "' index "; if (index.size() == 1) oss << index[0]; - else - { + else { oss << arrayInfo.varname(); for (unsigned int i = 0; i < index.size(); ++i) oss << "[" << index[i] << "]"; @@ -75,8 +73,7 @@ void CheckBufferOverrun::arrayIndexOutOfBoundsError(const std::liststr(); } @@ -218,20 +212,15 @@ static bool bailoutIfSwitch(const Token *tok, const unsigned int varid) // Count { and } unsigned int indentlevel = 0; - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (tok->str() == "{") indentlevel++; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { // scan the else-block - if (indentlevel == 1 && Token::simpleMatch(tok, "} else {")) - { + if (indentlevel == 1 && Token::simpleMatch(tok, "} else {")) { --indentlevel; continue; - } - else if (indentlevel <= 1) - { + } else if (indentlevel <= 1) { break; } @@ -264,37 +253,28 @@ static bool bailoutIfSwitch(const Token *tok, const unsigned int varid) */ static const Token *for_init(const Token *tok, unsigned int &varid, std::string &init_value) { - if (Token::Match(tok, "%var% = %any% ;")) - { - if (tok->tokAt(2)->isNumber()) - { + if (Token::Match(tok, "%var% = %any% ;")) { + if (tok->tokAt(2)->isNumber()) { init_value = tok->strAt(2); } varid = tok->varId(); tok = tok->tokAt(4); - } - else if (Token::Match(tok, "%type% %var% = %any% ;")) - { - if (tok->tokAt(3)->isNumber()) - { + } else if (Token::Match(tok, "%type% %var% = %any% ;")) { + if (tok->tokAt(3)->isNumber()) { init_value = tok->strAt(3); } varid = tok->next()->varId(); tok = tok->tokAt(5); - } - else if (Token::Match(tok, "%type% %type% %var% = %any% ;")) - { - if (tok->tokAt(4)->isNumber()) - { + } else if (Token::Match(tok, "%type% %type% %var% = %any% ;")) { + if (tok->tokAt(4)->isNumber()) { init_value = tok->strAt(4); } varid = tok->tokAt(2)->varId(); tok = tok->tokAt(6); - } - else + } else return 0; return tok; @@ -306,34 +286,25 @@ static bool for_condition(const Token * const tok2, unsigned int varid, std::str { if (Token::Match(tok2, "%varid% < %num% ;", varid) || Token::Match(tok2, "%varid% != %num% ; ++ %varid%", varid) || - Token::Match(tok2, "%varid% != %num% ; %varid% ++", varid)) - { + Token::Match(tok2, "%varid% != %num% ; %varid% ++", varid)) { maxMinFlipped = false; const MathLib::bigint value = MathLib::toLongNumber(tok2->strAt(2)); max_value = MathLib::toString(value - 1); - } - else if (Token::Match(tok2, "%varid% <= %num% ;", varid)) - { + } else if (Token::Match(tok2, "%varid% <= %num% ;", varid)) { maxMinFlipped = false; max_value = tok2->strAt(2); - } - else if (Token::Match(tok2, "%num% < %varid% ;", varid) || - Token::Match(tok2, "%num% != %varid% ; ++ %varid%", varid) || - Token::Match(tok2, "%num% != %varid% ; %varid% ++", varid)) - { + } else if (Token::Match(tok2, "%num% < %varid% ;", varid) || + Token::Match(tok2, "%num% != %varid% ; ++ %varid%", varid) || + Token::Match(tok2, "%num% != %varid% ; %varid% ++", varid)) { maxMinFlipped = true; const MathLib::bigint value = MathLib::toLongNumber(tok2->str()); max_value = min_value; min_value = MathLib::toString(value + 1); - } - else if (Token::Match(tok2, "%num% <= %varid% ;", varid)) - { + } else if (Token::Match(tok2, "%num% <= %varid% ;", varid)) { maxMinFlipped = true; max_value = min_value; min_value = tok2->str(); - } - else - { + } else { return false; } @@ -385,31 +356,21 @@ static bool for3(const Token * const tok, { assert(tok != 0); if (Token::Match(tok, "%varid% += %num% )", varid) || - Token::Match(tok, "%varid% = %num% + %varid% )", varid)) - { + Token::Match(tok, "%varid% = %num% + %varid% )", varid)) { if (!for_maxvalue(tok->tokAt(2), min_value, max_value)) return false; - } - else if (Token::Match(tok, "%varid% = %varid% + %num% )", varid)) - { + } else if (Token::Match(tok, "%varid% = %varid% + %num% )", varid)) { if (!for_maxvalue(tok->tokAt(4), min_value, max_value)) return false; - } - else if (Token::Match(tok, "%varid% -= %num% )", varid) || - Token::Match(tok, "%varid% = %num% - %varid% )", varid)) - { + } else if (Token::Match(tok, "%varid% -= %num% )", varid) || + Token::Match(tok, "%varid% = %num% - %varid% )", varid)) { if (!for_maxvalue(tok->tokAt(2), min_value, max_value)) return false; - } - else if (Token::Match(tok, "%varid% = %varid% - %num% )", varid)) - { + } else if (Token::Match(tok, "%varid% = %varid% - %num% )", varid)) { if (!for_maxvalue(tok->tokAt(4), min_value, max_value)) return false; - } - else if (Token::Match(tok, "--| %varid% --| )", varid)) - { - if (!maxMinFlipped && MathLib::toLongNumber(min_value) < MathLib::toLongNumber(max_value)) - { + } else if (Token::Match(tok, "--| %varid% --| )", varid)) { + if (!maxMinFlipped && MathLib::toLongNumber(min_value) < MathLib::toLongNumber(max_value)) { // Code relies on the fact that integer will overflow: // for (unsigned int i = 3; i < 5; --i) @@ -417,9 +378,7 @@ static bool for3(const Token * const tok, max_value = min_value; min_value = "0"; } - } - else if (! Token::Match(tok, "++| %varid% ++| )", varid)) - { + } else if (! Token::Match(tok, "++| %varid% ++| )", varid)) { return false; } return true; @@ -436,14 +395,11 @@ static bool for3(const Token * const tok, */ static bool for_bailout(const Token * const tok1, unsigned int varid) { - for (const Token *loopTok = tok1; loopTok && loopTok != tok1->link(); loopTok = loopTok->next()) - { - if (loopTok->varId() == varid) - { + for (const Token *loopTok = tok1; loopTok && loopTok != tok1->link(); loopTok = loopTok->next()) { + if (loopTok->varId() == varid) { // Counter variable used inside loop if (Token::Match(loopTok->next(), "+=|-=|++|--|=") || - Token::Match(loopTok->previous(), "++|--")) - { + Token::Match(loopTok->previous(), "++|--")) { return true; } } @@ -458,16 +414,14 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra // count { and } for tok2 int indentlevel2 = 0; - for (; tok2; tok2 = tok2->next()) - { + for (; tok2; tok2 = tok2->next()) { if (tok2->str() == ";" && indentlevel2 == 0) break; if (tok2->str() == "{") ++indentlevel2; - if (tok2->str() == "}") - { + if (tok2->str() == "}") { --indentlevel2; if (indentlevel2 <= 0) break; @@ -478,8 +432,7 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra if (tok2->str() == "?") break; - if (Token::simpleMatch(tok2, "for (") && Token::simpleMatch(tok2->next()->link(), ") {")) - { + if (Token::simpleMatch(tok2, "for (") && Token::simpleMatch(tok2->next()->link(), ") {")) { const Token *endpar = tok2->next()->link(); const Token *startbody = endpar->next(); const Token *endbody = startbody->link(); @@ -487,20 +440,17 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra continue; } - if (Token::Match(tok2, "if|switch")) - { + if (Token::Match(tok2, "if|switch")) { if (bailoutIfSwitch(tok2, arrayInfo.varid())) break; } - if (condition_out_of_bounds && Token::Match(tok2, pattern.c_str(), arrayInfo.varid())) - { + if (condition_out_of_bounds && Token::Match(tok2, pattern.c_str(), arrayInfo.varid())) { bufferOverrunError(tok2, arrayInfo.varname()); break; } - else if (arrayInfo.varid() && counter_varid > 0 && !min_counter_value.empty() && !max_counter_value.empty()) - { + else if (arrayInfo.varid() && counter_varid > 0 && !min_counter_value.empty() && !max_counter_value.empty()) { // Is the loop variable used to calculate the array index? // In this scope it is determined if such calculated // array indexes are out of bounds. @@ -514,8 +464,7 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra int max_index = 0; if (Token::Match(tok2, "%varid% [ %var% +|-|*|/ %num% ]", arrayInfo.varid()) && - tok2->tokAt(2)->varId() == counter_varid) - { + tok2->tokAt(2)->varId() == counter_varid) { // operator: +-*/ const char action = tok2->strAt(3)[0]; @@ -527,10 +476,8 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra min_index = std::atoi(MathLib::calculate(min_counter_value, second, action, _tokenizer).c_str()); max_index = std::atoi(MathLib::calculate(max_counter_value, second, action, _tokenizer).c_str()); - } - else if (Token::Match(tok2, "%varid% [ %num% +|-|*|/ %var% ]", arrayInfo.varid()) && - tok2->tokAt(4)->varId() == counter_varid) - { + } else if (Token::Match(tok2, "%varid% [ %num% +|-|*|/ %var% ]", arrayInfo.varid()) && + tok2->tokAt(4)->varId() == counter_varid) { // operator: +-*/ const char action = tok2->strAt(3)[0]; @@ -545,16 +492,14 @@ void CheckBufferOverrun::parse_for_body(const Token *tok2, const ArrayInfo &arra } //printf("min_index = %d, max_index = %d, size = %d\n", min_index, max_index, size); - if (min_index < 0 || max_index < 0) - { + if (min_index < 0 || max_index < 0) { std::vector indexes; indexes.push_back(std::min(min_index, max_index)); arrayIndexOutOfBoundsError(tok2, arrayInfo, indexes); } // skip 0 length arrays - if (arrayInfo.num(0) && (min_index >= (int)arrayInfo.num(0) || max_index >= (int)arrayInfo.num(0))) - { + if (arrayInfo.num(0) && (min_index >= (int)arrayInfo.num(0) || max_index >= (int)arrayInfo.num(0))) { std::vector indexes; indexes.push_back(std::max(min_index, max_index)); arrayIndexOutOfBoundsError(tok2, arrayInfo, indexes); @@ -575,8 +520,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p total_size["memcpy"] = 3; total_size["memmove"] = 3; - if (par == 1) - { + if (par == 1) { // reading from array // if it is zero terminated properly there won't be buffer overruns total_size["strncat"] = 3; @@ -586,8 +530,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p total_size["fwrite"] = 1001; // parameter 2 * parameter 3 } - if (par == 2) - { + if (par == 2) { total_size["read"] = 3; total_size["pread"] = 3; total_size["write"] = 3; @@ -598,8 +541,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p } std::map::const_iterator it = total_size.find(tok.str()); - if (it != total_size.end()) - { + if (it != total_size.end()) { if (arrayInfo.element_size() == 0) return; @@ -609,50 +551,40 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p // Parse function call. When a ',' is seen, arg is decremented. // if arg becomes 1 then the current function parameter is the wanted parameter. // if arg becomes 1000 then multiply current and next argument. - for (const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "(") - { + for (const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == "(") { tok2 = tok2->link(); continue; } if (tok2->str() == ")") break; - if (tok2->str() == ",") - { + if (tok2->str() == ",") { --arg; - if (arg == 1) - { - if (Token::Match(tok2, ", %num% ,|)")) - { + if (arg == 1) { + if (Token::Match(tok2, ", %num% ,|)")) { const MathLib::bigint sz = MathLib::toLongNumber(tok2->strAt(1)); MathLib::bigint elements = 1; for (unsigned int i = 0; i < arrayInfo.num().size(); ++i) elements *= arrayInfo.num(i); - if (sz < 0 || sz > int(elements * arrayInfo.element_size())) - { + if (sz < 0 || sz > int(elements * arrayInfo.element_size())) { bufferOverrunError(&tok, arrayInfo.varname()); } } - else if (Token::Match(tok2, ", %any% ,|)") && tok2->next()->str()[0] == '\'') - { + else if (Token::Match(tok2, ", %any% ,|)") && tok2->next()->str()[0] == '\'') { sizeArgumentAsCharError(tok2->next()); } break; } - if (arg == 1000) // special code. This parameter multiplied with the next must not exceed total_size - { - if (Token::Match(tok2, ", %num% , %num% ,|)")) - { + if (arg == 1000) { // special code. This parameter multiplied with the next must not exceed total_size + if (Token::Match(tok2, ", %num% , %num% ,|)")) { const MathLib::bigint sz = MathLib::toLongNumber(MathLib::multiply(tok2->strAt(1), tok2->strAt(3))); MathLib::bigint elements = 1; for (unsigned int i = 0; i < arrayInfo.num().size(); ++i) elements *= arrayInfo.num(i); - if (sz < 0 || sz > int(elements * arrayInfo.element_size())) - { + if (sz < 0 || sz > int(elements * arrayInfo.element_size())) { bufferOverrunError(&tok, arrayInfo.varname()); } } @@ -664,26 +596,20 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p // Calling a user function? // only 1-dimensional arrays can be checked currently - else if (arrayInfo.num().size() == 1) - { + else if (arrayInfo.num().size() == 1) { const Token *ftok = _tokenizer->getFunctionTokenByName(tok.str().c_str()); - if (Token::Match(ftok, "%var% (") && Token::Match(ftok->next()->link(), ") const| {")) - { + if (Token::Match(ftok, "%var% (") && Token::Match(ftok->next()->link(), ") const| {")) { // Get varid for the corresponding parameter.. unsigned int parameter = 1; unsigned int parameterVarId = 0; - for (const Token *ftok2 = ftok->tokAt(2); ftok2; ftok2 = ftok2->next()) - { - if (ftok2->str() == ",") - { + for (const Token *ftok2 = ftok->tokAt(2); ftok2; ftok2 = ftok2->next()) { + if (ftok2->str() == ",") { if (parameter >= par) break; ++parameter; - } - else if (ftok2->str() == ")") + } else if (ftok2->str() == ")") break; - else if (parameter == par && Token::Match(ftok2, "%var% ,|)|[")) - { + else if (parameter == par && Token::Match(ftok2, "%var% ,|)|[")) { // check type.. const Token *type = ftok2->previous(); while (Token::Match(type, "*|const")) @@ -705,19 +631,15 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p ftok = ftok->next(); // Check the parameter usage in the function scope.. - for (; ftok; ftok = ftok->next()) - { - if (Token::Match(ftok, "if|for|while (")) - { + for (; ftok; ftok = ftok->next()) { + if (Token::Match(ftok, "if|for|while (")) { // bailout if there is buffer usage.. - if (bailoutIfSwitch(ftok, parameterVarId)) - { + if (bailoutIfSwitch(ftok, parameterVarId)) { break; } // no bailout is needed. skip the if-block - else - { + else { // goto end of if block.. ftok = ftok->next()->link()->next()->link(); if (Token::simpleMatch(ftok, "} else {")) @@ -731,17 +653,14 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &tok, unsigned int p if (ftok->str() == "}") break; - if (ftok->varId() == parameterVarId) - { + if (ftok->varId() == parameterVarId) { if (Token::Match(ftok->previous(), "-- %var%") || Token::Match(ftok, "%var% --")) break; - if (Token::Match(ftok->previous(), "=|;|{|}|%op% %var% [ %num% ]")) - { + if (Token::Match(ftok->previous(), "=|;|{|}|%op% %var% [ %num% ]")) { const MathLib::bigint index = MathLib::toLongNumber(ftok->strAt(2)); - if (index >= 0 && arrayInfo.num(0) > 0 && index >= arrayInfo.num(0)) - { + if (index >= 0 && arrayInfo.num(0) > 0 && index >= arrayInfo.num(0)) { std::list callstack; callstack.push_back(&tok); callstack.push_back(ftok); @@ -765,28 +684,23 @@ void CheckBufferOverrun::checkFunctionCall(const Token *tok, const ArrayInfo &ar // 1st parameter.. if (Token::Match(tok->tokAt(2), "%varid% ,|)", arrayInfo.varid())) checkFunctionParameter(*tok, 1, arrayInfo); - else if (Token::Match(tok->tokAt(2), "%varid% + %num% ,|)", arrayInfo.varid())) - { + else if (Token::Match(tok->tokAt(2), "%varid% + %num% ,|)", arrayInfo.varid())) { const ArrayInfo ai(arrayInfo.limit(MathLib::toLongNumber(tok->strAt(4)))); checkFunctionParameter(*tok, 1, ai); } // goto 2nd parameter and check it.. - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "(") - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == "(") { tok2 = tok2->link(); continue; } if (tok2->str() == ";" || tok2->str() == ")") break; - if (tok2->str() == ",") - { + if (tok2->str() == ",") { if (Token::Match(tok2, ", %varid% ,|)", arrayInfo.varid())) checkFunctionParameter(*tok, 2, arrayInfo); - else if (Token::Match(tok2, ", %varid% + %num% ,|)", arrayInfo.varid())) - { + else if (Token::Match(tok2, ", %varid% + %num% ,|)", arrayInfo.varid())) { const ArrayInfo ai(arrayInfo.limit(MathLib::toLongNumber(tok2->strAt(3)))); checkFunctionParameter(*tok, 2, ai); } @@ -836,16 +750,14 @@ void CheckBufferOverrun::checkScopeForBody(const Token *tok, const ArrayInfo &ar // Goto the end parenthesis of the for-statement: "for (x; y; z)" .. tok2 = tok->next()->link(); - if (!tok2 || !tok2->tokAt(5)) - { + if (!tok2 || !tok2->tokAt(5)) { bailout = true; return; } // Check is the counter variable increased elsewhere inside the loop or used // for anything else except reading - if (for_bailout(tok2->next(), counter_varid)) - { + if (for_bailout(tok2->next(), counter_varid)) { bailout = true; return; } @@ -866,8 +778,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector(varname.empty() ? 0U : (varname.size() - 1) * 2U)); - if (Token::simpleMatch(tok, "return")) - { + if (Token::simpleMatch(tok, "return")) { tok = tok->next(); if (!tok) return; @@ -875,11 +786,9 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && Token::Match(tok, "%varid% [ %num% ]", varid)) || - (varid == 0 && Token::Match(tok, (varnames + " [ %num% ]").c_str()))) - { + (varid == 0 && Token::Match(tok, (varnames + " [ %num% ]").c_str()))) { const MathLib::bigint index = MathLib::toLongNumber(tok->strAt(2 + varc)); - if (index >= size) - { + if (index >= size) { std::vector indexes; indexes.push_back(index); arrayIndexOutOfBoundsError(tok->tokAt(varc), arrayInfo, indexes); @@ -892,29 +801,24 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectornext()) - { - if (tok->str() == "{") - { + for (; tok; tok = tok->next()) { + if (tok->str() == "{") { ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { --indentlevel; if (indentlevel < 0) return; } - if (varid != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", varid)) - { + if (varid != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", varid)) { // Abort break; } // reassign buffer - if (varid > 0 && Token::Match(tok, "[;{}] %varid% =", varid)) - { + if (varid > 0 && Token::Match(tok, "[;{}] %varid% =", varid)) { // using varid .. bailout if (!Token::Match(tok->tokAt(3), "%varid%", varid)) break; @@ -923,18 +827,15 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && ((tok->str() == "return" || (!tok->isName() && !Token::Match(tok, "[.&]"))) && Token::Match(tok->next(), "%varid% [ %num% ]", varid))) || - (varid == 0 && ((tok->str() == "return" || (!tok->isName() && !Token::Match(tok, "[.&]"))) && Token::Match(tok->next(), (varnames + " [ %num% ]").c_str())))) - { + (varid == 0 && ((tok->str() == "return" || (!tok->isName() && !Token::Match(tok, "[.&]"))) && Token::Match(tok->next(), (varnames + " [ %num% ]").c_str())))) { std::vector indexes; const Token *tok2 = tok->tokAt(2 + varc); - for (; Token::Match(tok2, "[ %num% ]"); tok2 = tok2->tokAt(3)) - { + for (; Token::Match(tok2, "[ %num% ]"); tok2 = tok2->tokAt(3)) { const MathLib::bigint index = MathLib::toLongNumber(tok2->strAt(1)); indexes.push_back(index); } - if (indexes.size() == arrayInfo.num().size()) - { + if (indexes.size() == arrayInfo.num().size()) { // Check if the indexes point outside the whole array.. // char a[10][10]; // a[0][20] <-- ok. @@ -947,8 +848,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector totalElements || totalIndex < 0) - { + if (totalIndex > totalElements || totalIndex < 0) { arrayIndexOutOfBoundsError(tok->tokAt(1 + varc), arrayInfo, indexes); } // Is any array index out of bounds? - else - { + else { // check each index for overflow - for (unsigned int i = 0; i < indexes.size(); ++i) - { - if (indexes[i] >= arrayInfo.num(i)) - { + for (unsigned int i = 0; i < indexes.size(); ++i) { + if (indexes[i] >= arrayInfo.num(i)) { // The access is still within the memory range for the array // so it may be intentional. - if (_settings->inconclusive) - { + if (_settings->inconclusive) { arrayIndexOutOfBoundsError(tok->tokAt(1 + varc), arrayInfo, indexes); break; // only warn about the first one } @@ -999,8 +894,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0) - { + if (varid == 0 && size > 0) { if (Token::Match(tok, ("%var% ( " + varnames + " ,").c_str())) checkFunctionParameter(*tok, 1, arrayInfo); if (Token::Match(tok, ("%var% ( %var% , " + varnames + " ,").c_str())) @@ -1008,8 +902,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && Token::Match(tok, "strcpy|strcat ( %varid% , %str% )", varid)) || - (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %str% )").c_str()))) - { + (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %str% )").c_str()))) { const std::size_t len = Token::getStrLength(tok->tokAt(varc + 4)); - if (total_size > 0 && len >= (unsigned int)total_size) - { + if (total_size > 0 && len >= (unsigned int)total_size) { bufferOverrunError(tok, varid > 0 ? "" : varnames.c_str()); continue; } - } - else if ((varid > 0 && Token::Match(tok, "strcpy|strcat ( %varid% , %var% )", varid)) || - (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %var% )").c_str()))) - { + } else if ((varid > 0 && Token::Match(tok, "strcpy|strcat ( %varid% , %var% )", varid)) || + (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %var% )").c_str()))) { const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(tok->tokAt(4)->varId()); - if (var && var->isArray() && var->dimensions().size() == 1) - { + if (var && var->isArray() && var->dimensions().size() == 1) { const std::size_t len = (std::size_t)var->dimension(0); - if (total_size > 0 && len > (unsigned int)total_size) - { + if (total_size > 0 && len > (unsigned int)total_size) { if (_settings->inconclusive) possibleBufferOverrunError(tok, tok->strAt(4), tok->strAt(2), tok->str() == "strcat"); continue; @@ -1047,16 +934,13 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 ? std::string("strcat ( %varid% , %str% ) ;") : ("strcat ( " + varnames + " , %str% ) ;"); - if (Token::Match(tok, strcatPattern.c_str(), varid)) - { + if (Token::Match(tok, strcatPattern.c_str(), varid)) { size_t charactersAppend = 0; const Token *tok2 = tok; - while (tok2 && Token::Match(tok2, strcatPattern.c_str(), varid)) - { + while (tok2 && Token::Match(tok2, strcatPattern.c_str(), varid)) { charactersAppend += Token::getStrLength(tok2->tokAt(4 + varc)); - if (charactersAppend >= static_cast(total_size)) - { + if (charactersAppend >= static_cast(total_size)) { bufferOverrunError(tok2); break; } @@ -1067,23 +951,20 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0" check. const std::string sprintfPattern = varid > 0 ? std::string("sprintf ( %varid% , %str% [,)]") : ("sprintf ( " + varnames + " , %str% [,)]"); - if (Token::Match(tok, sprintfPattern.c_str(), varid) && total_size > 0) - { + if (Token::Match(tok, sprintfPattern.c_str(), varid) && total_size > 0) { checkSprintfCall(tok, static_cast(total_size)); } // snprintf.. const std::string snprintfPattern = varid > 0 ? std::string("snprintf ( %varid% , %num% ,") : ("snprintf ( " + varnames + " , %num% ,"); - if (Token::Match(tok, snprintfPattern.c_str(), varid)) - { + if (Token::Match(tok, snprintfPattern.c_str(), varid)) { const MathLib::bigint n = MathLib::toLongNumber(tok->strAt(4 + varc)); if (n > total_size) outOfBoundsError(tok->tokAt(4 + varc), "snprintf size", true, n, total_size); } // Check function call.. - if (Token::Match(tok, "%var% (") && total_size > 0) - { + if (Token::Match(tok, "%var% (") && total_size > 0) { // No varid => function calls are not handled if (varid == 0) continue; @@ -1093,8 +974,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorstrAt(3)); if (index > size && _settings->isEnabled("portability")) pointerOutOfBoundsError(tok->next(), "buffer"); @@ -1102,8 +982,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokAt(2), tok->strAt(2), false, 0, 0); } } @@ -1116,15 +995,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo // Count { and } for tok unsigned int indentlevel = 0; - for (; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (; tok; tok = tok->next()) { + if (tok->str() == "{") { ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel == 0) return; --indentlevel; @@ -1132,27 +1008,22 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo // Skip array declarations else if (Token::Match(tok, "[;{}] %type% *| %var% [") && - tok->strAt(1) != "return") - { + tok->strAt(1) != "return") { tok = tok->tokAt(3); continue; } - else if (Token::Match(tok, "%varid% [ %num% ]", arrayInfo.varid())) - { + else if (Token::Match(tok, "%varid% [ %num% ]", arrayInfo.varid())) { std::vector indexes; - for (const Token *tok2 = tok->next(); Token::Match(tok2, "[ %num% ]"); tok2 = tok2->tokAt(3)) - { + for (const Token *tok2 = tok->next(); Token::Match(tok2, "[ %num% ]"); tok2 = tok2->tokAt(3)) { const MathLib::bigint index = MathLib::toLongNumber(tok2->strAt(1)); - if (index < 0) - { + if (index < 0) { indexes.clear(); break; } indexes.push_back(index); } - if (indexes.size() == arrayInfo.num().size()) - { + if (indexes.size() == arrayInfo.num().size()) { // Check if the indexes point outside the whole array.. // char a[10][10]; // a[0][20] <-- ok. @@ -1165,8 +1036,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo MathLib::bigint totalIndex = 0; // calculate the totalElements and totalIndex.. - for (unsigned int i = 0; i < indexes.size(); ++i) - { + for (unsigned int i = 0; i < indexes.size(); ++i) { std::size_t ri = indexes.size() - 1 - i; totalIndex += indexes[ri] * totalElements; totalElements *= arrayInfo.num(ri); @@ -1189,22 +1059,17 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo continue; // Is totalIndex in bounds? - if (totalIndex > totalElements) - { + if (totalIndex > totalElements) { arrayIndexOutOfBoundsError(tok, arrayInfo, indexes); } // Is any array index out of bounds? - else - { + else { // check each index for overflow - for (unsigned int i = 0; i < indexes.size(); ++i) - { - if (indexes[i] >= arrayInfo.num(i)) - { + for (unsigned int i = 0; i < indexes.size(); ++i) { + if (indexes[i] >= arrayInfo.num(i)) { // The access is still within the memory range for the array // so it may be intentional. - if (_settings->inconclusive) - { + if (_settings->inconclusive) { arrayIndexOutOfBoundsError(tok, arrayInfo, indexes); break; // only warn about the first one } @@ -1215,8 +1080,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo } // Loop.. - else if (Token::simpleMatch(tok, "for (")) - { + else if (Token::simpleMatch(tok, "for (")) { bool bailout = false; checkScopeForBody(tok, arrayInfo, bailout); if (bailout) @@ -1226,41 +1090,32 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo // Check function call.. - if (Token::Match(tok, "%var% (")) - { + if (Token::Match(tok, "%var% (")) { checkFunctionCall(tok, arrayInfo); } - if (Token::Match(tok, "strncpy|memcpy|memmove ( %varid% , %str% , %num% )", arrayInfo.varid())) - { + if (Token::Match(tok, "strncpy|memcpy|memmove ( %varid% , %str% , %num% )", arrayInfo.varid())) { unsigned int num = (unsigned int)MathLib::toLongNumber(tok->strAt(6)); - if (Token::getStrLength(tok->tokAt(4)) >= (unsigned int)total_size && (unsigned int)total_size == num) - { + if (Token::getStrLength(tok->tokAt(4)) >= (unsigned int)total_size && (unsigned int)total_size == num) { if (_settings->inconclusive) bufferNotZeroTerminatedError(tok, tok->strAt(2), tok->str()); } } if ((Token::Match(tok, "strncpy|strncat ( %varid% , %var% , %num% )", arrayInfo.varid())) || - (Token::Match(tok, "strncpy|strncat ( %varid% , %var% [ %any% ] , %num% )", arrayInfo.varid()))) - { + (Token::Match(tok, "strncpy|strncat ( %varid% , %var% [ %any% ] , %num% )", arrayInfo.varid()))) { const int offset = tok->strAt(5) == "[" ? 3 : 0; // check for strncpy which is not terminated - if (tok->str() == "strncpy") - { + if (tok->str() == "strncpy") { // strncpy takes entire variable length as input size unsigned int num = (unsigned int)MathLib::toLongNumber(tok->strAt(6 + offset)); - if (num >= total_size) - { + if (num >= total_size) { const Token *tok2 = tok->next()->link()->next(); - for (; tok2; tok2 = tok2->next()) - { - if (tok2->varId() == tok->tokAt(2)->varId()) - { - if (!Token::Match(tok2, "%varid% [ %any% ] = 0 ;", tok->tokAt(2)->varId())) - { + for (; tok2; tok2 = tok2->next()) { + if (tok2->varId() == tok->tokAt(2)->varId()) { + if (!Token::Match(tok2, "%varid% [ %any% ] = 0 ;", tok->tokAt(2)->varId())) { // this is currently 'inconclusive'. See TestBufferOverrun::terminateStrncpy3 if (_settings->isEnabled("style") && _settings->inconclusive) terminateStrncpyError(tok, tok->strAt(2)); @@ -1273,16 +1128,14 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo } // Dangerous usage of strncat.. - if (tok->str() == "strncat") - { + if (tok->str() == "strncat") { const MathLib::bigint n = MathLib::toLongNumber(tok->strAt(6 + offset)); if (n >= total_size) strncatUsageError(tok); } // Dangerous usage of strncpy + strncat.. - if (Token::Match(tok->tokAt(8 + offset), "; strncat ( %varid% , %any% , %num% )", arrayInfo.varid())) - { + if (Token::Match(tok->tokAt(8 + offset), "; strncat ( %varid% , %any% , %num% )", arrayInfo.varid())) { const MathLib::bigint n = MathLib::toLongNumber(tok->strAt(6 + offset)) + MathLib::toLongNumber(tok->strAt(15 + offset)); if (n > total_size) strncatUsageError(tok->tokAt(9 + offset)); @@ -1290,27 +1143,22 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo } // Writing data into array.. - if (Token::Match(tok, "strcpy|strcat ( %varid% , %str% )", arrayInfo.varid())) - { + if (Token::Match(tok, "strcpy|strcat ( %varid% , %str% )", arrayInfo.varid())) { const std::size_t len = Token::getStrLength(tok->tokAt(4)); - if (total_size > 0 && len >= (unsigned int)total_size) - { + if (total_size > 0 && len >= (unsigned int)total_size) { bufferOverrunError(tok, arrayInfo.varname()); continue; } } // Detect few strcat() calls - if (total_size > 0 && Token::Match(tok, "strcat ( %varid% , %str% ) ;", arrayInfo.varid())) - { + if (total_size > 0 && Token::Match(tok, "strcat ( %varid% , %str% ) ;", arrayInfo.varid())) { std::size_t charactersAppend = 0; const Token *tok2 = tok; - while (tok2 && Token::Match(tok2, "strcat ( %varid% , %str% ) ;", arrayInfo.varid())) - { + while (tok2 && Token::Match(tok2, "strcat ( %varid% , %str% ) ;", arrayInfo.varid())) { charactersAppend += Token::getStrLength(tok2->tokAt(4)); - if (charactersAppend >= (unsigned int)total_size) - { + if (charactersAppend >= (unsigned int)total_size) { bufferOverrunError(tok2, arrayInfo.varname()); break; } @@ -1319,25 +1167,21 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo } - if (Token::Match(tok, "sprintf ( %varid% , %str% [,)]", arrayInfo.varid())) - { + if (Token::Match(tok, "sprintf ( %varid% , %str% [,)]", arrayInfo.varid())) { checkSprintfCall(tok, total_size); } // snprintf.. - if (total_size > 0 && Token::Match(tok, "snprintf ( %varid% , %num% ,", arrayInfo.varid())) - { + if (total_size > 0 && Token::Match(tok, "snprintf ( %varid% , %num% ,", arrayInfo.varid())) { const MathLib::bigint n = MathLib::toLongNumber(tok->strAt(4)); if (n > total_size) outOfBoundsError(tok->tokAt(4), "snprintf size", true, n, total_size); } // undefined behaviour: result of pointer arithmetic is out of bounds - if (_settings->isEnabled("portability") && Token::Match(tok, "= %varid% + %num% ;", arrayInfo.varid())) - { + if (_settings->isEnabled("portability") && Token::Match(tok, "= %varid% + %num% ;", arrayInfo.varid())) { const MathLib::bigint index = MathLib::toLongNumber(tok->strAt(3)); - if (index < 0 || index > arrayInfo.num(0)) - { + if (index < 0 || index > arrayInfo.num(0)) { pointerOutOfBoundsError(tok->next(), "array"); } } @@ -1352,17 +1196,13 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo void CheckBufferOverrun::checkGlobalAndLocalVariable() { // check all known fixed size arrays first by just looking them up - for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) - { + for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) { const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(i); - if (var && var->isArray() && var->dimension(0) > 0) - { + if (var && var->isArray() && var->dimension(0) > 0) { ArrayInfo arrayInfo(var, _tokenizer); const Token *tok = var->nameToken(); - while (tok && tok->str() != ";") - { - if (tok->str() == "{") - { + while (tok && tok->str() != ";") { + if (tok->str() == "{") { if (Token::simpleMatch(tok->previous(), "= {")) tok = tok->link(); else @@ -1381,8 +1221,7 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() // find all dynamically allocated arrays next by parsing the token stream // Count { and } when parsing all tokens int indentlevel = 0; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() == "{") ++indentlevel; @@ -1409,39 +1248,31 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() "Check (BufferOverrun::checkGlobalAndLocalVariable)", tok->progressValue()); - if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% [ %num% ]")) - { + if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% [ %num% ]")) { size = MathLib::toLongNumber(tok->strAt(6)); type = tok->strAt(4); varid = tok->tokAt(1)->varId(); nextTok = 8; - } - else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% ( %num% )")) - { + } else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% ( %num% )")) { size = 1; type = tok->strAt(4); varid = tok->tokAt(1)->varId(); nextTok = 8; - } - else if (indentlevel > 0 && - Token::Match(tok, "[;{}] %var% = %str% ;") && - tok->next()->varId() > 0 && - NULL != Token::findmatch(_tokenizer->tokens(), "[;{}] const| %type% * %varid% ;", tok->next()->varId())) - { + } else if (indentlevel > 0 && + Token::Match(tok, "[;{}] %var% = %str% ;") && + tok->next()->varId() > 0 && + NULL != Token::findmatch(_tokenizer->tokens(), "[;{}] const| %type% * %varid% ;", tok->next()->varId())) { size = 1 + int(tok->tokAt(3)->strValue().size()); type = "char"; varid = tok->next()->varId(); nextTok = 4; - } - else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = malloc|alloca ( %num% ) ;")) - { + } else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = malloc|alloca ( %num% ) ;")) { size = MathLib::toLongNumber(tok->strAt(5)); type = "char"; // minimum type, typesize=1 varid = tok->tokAt(1)->varId(); nextTok = 7; - if (varid > 0) - { + if (varid > 0) { // get type of variable const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(varid); /** @todo false negatives: this may be too conservative */ @@ -1458,9 +1289,7 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() if (sizeOfType > 0) size /= static_cast(sizeOfType); } - } - else - { + } else { continue; } @@ -1492,37 +1321,31 @@ void CheckBufferOverrun::checkStructVariable() std::list::const_iterator scope; // find every class and struct - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures if (!scope->isClassOrStruct()) continue; // check all variables to see if they are arrays std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { // find all array variables - if (var->isArray()) - { + if (var->isArray()) { // create ArrayInfo from the array variable ArrayInfo arrayInfo(&*var, _tokenizer); std::list::const_iterator func_scope; // find every function - for (func_scope = symbolDatabase->scopeList.begin(); func_scope != symbolDatabase->scopeList.end(); ++func_scope) - { + for (func_scope = symbolDatabase->scopeList.begin(); func_scope != symbolDatabase->scopeList.end(); ++func_scope) { // only check functions if (func_scope->type != Scope::eFunction) continue; // check for member variables - if (func_scope->functionOf == &*scope) - { + if (func_scope->functionOf == &*scope) { // only check non-empty function - if (func_scope->function->start->next() != func_scope->function->start->link()) - { + if (func_scope->function->start->next() != func_scope->function->start->link()) { // start checking after the { const Token *tok = func_scope->function->start->next(); checkScope(tok, arrayInfo); @@ -1539,8 +1362,7 @@ void CheckBufferOverrun::checkStructVariable() varname.push_back(arrayInfo.varname()); // search the function and it's parameters - for (const Token *tok3 = func_scope->classDef; tok3 && tok3 != func_scope->classEnd; tok3 = tok3->next()) - { + for (const Token *tok3 = func_scope->classDef; tok3 && tok3 != func_scope->classEnd; tok3 = tok3->next()) { // search for the class/struct name if (tok3->str() != scope->className) continue; @@ -1557,21 +1379,17 @@ void CheckBufferOverrun::checkStructVariable() continue; // check for variable sized structure - if (scope->type == Scope::eStruct && var->isPublic()) - { + if (scope->type == Scope::eStruct && var->isPublic()) { // last member of a struct with array size of 0 or 1 could be a variable sized structure if (var->dimensions().size() == 1 && var->dimension(0) < 2 && - var->index() == (scope->varlist.size() - 1)) - { + var->index() == (scope->varlist.size() - 1)) { // dynamically allocated so could be variable sized structure - if (tok3->next()->str() == "*") - { + if (tok3->next()->str() == "*") { // check for allocation if ((Token::Match(tok3->tokAt(3), "; %var% = malloc ( %num% ) ;") || (Token::Match(tok3->tokAt(3), "; %var% = (") && Token::Match(tok3->tokAt(6)->link(), ") malloc ( %num% ) ;"))) && - (tok3->strAt(4) == tok3->strAt(2))) - { + (tok3->strAt(4) == tok3->strAt(2))) { MathLib::bigint size; // find size of allocation @@ -1589,8 +1407,7 @@ void CheckBufferOverrun::checkStructVariable() // Either way, this is just a guess and could be wrong. The // information to make the right decision has been simplified // away by the time we get here. - if (size != 100) // magic number for size of struct - { + if (size != 100) { // magic number for size of struct // check if a real size was specified and give up // malloc(10) rather than malloc(sizeof(struct)) if (size < 100) @@ -1611,11 +1428,9 @@ void CheckBufferOverrun::checkStructVariable() // Goto end of statement. const Token *CheckTok = NULL; - while (tok3 && tok3 != func_scope->classEnd) - { + while (tok3 && tok3 != func_scope->classEnd) { // End of statement. - if (tok3->str() == ";") - { + if (tok3->str() == ";") { CheckTok = tok3; break; } @@ -1625,8 +1440,7 @@ void CheckBufferOverrun::checkStructVariable() break; // Function implementation.. - if (Token::simpleMatch(tok3, ") {")) - { + if (Token::simpleMatch(tok3, ") {")) { CheckTok = tok3->tokAt(2); break; } @@ -1675,10 +1489,8 @@ MathLib::bigint CheckBufferOverrun::countSprintfLength(const std::string &input_ bool i_d_x_f_found = false; std::list::const_iterator paramIter = parameters.begin(); std::size_t parameterLength = 0; - for (std::string::size_type i = 0; i < input_string.length(); ++i) - { - if (input_string[i] == '\\') - { + for (std::string::size_type i = 0; i < input_string.length(); ++i) { + if (input_string[i] == '\\') { if (input_string[i+1] == '0') break; @@ -1687,10 +1499,8 @@ MathLib::bigint CheckBufferOverrun::countSprintfLength(const std::string &input_ continue; } - if (percentCharFound) - { - switch (input_string[i]) - { + if (percentCharFound) { + switch (input_string[i]) { case 'f': case 'x': case 'X': @@ -1724,34 +1534,28 @@ MathLib::bigint CheckBufferOverrun::countSprintfLength(const std::string &input_ if (input_string[i] == '%') percentCharFound = !percentCharFound; - else if (percentCharFound) - { + else if (percentCharFound) { digits_string.append(1, input_string[i]); } if (!percentCharFound) input_string_size++; - if (handleNextParameter) - { + if (handleNextParameter) { unsigned int tempDigits = static_cast(std::abs(std::atoi(digits_string.c_str()))); if (i_d_x_f_found) tempDigits = std::max(static_cast(tempDigits), 1U); - if (digits_string.find('.') != std::string::npos) - { + if (digits_string.find('.') != std::string::npos) { const std::string endStr = digits_string.substr(digits_string.find('.') + 1); unsigned int maxLen = std::max(static_cast(std::abs(std::atoi(endStr.c_str()))), 1U); - if (input_string[i] == 's') - { + if (input_string[i] == 's') { // For strings, the length after the dot "%.2s" will limit // the length of the string. if (parameterLength > maxLen) parameterLength = maxLen; - } - else - { + } else { // For integers, the length after the dot "%.2d" can // increase required length if (tempDigits < maxLen) @@ -1786,20 +1590,16 @@ void CheckBufferOverrun::checkSprintfCall(const Token *tok, const MathLib::bigin // Count the number of tokens in the buffer variable's name int varc = 0; - for (const Token *tok1 = tok->tokAt(3); tok1 != end; tok1 = tok1->next()) - { + for (const Token *tok1 = tok->tokAt(3); tok1 != end; tok1 = tok1->next()) { if (tok1->str() == ",") break; ++ varc; } std::list parameters; - if (tok->tokAt(5 + varc)->str() == ",") - { - for (const Token *tok2 = tok->tokAt(5 + varc); tok2 && tok2 != end; tok2 = tok2->next()) - { - if (Token::Match(tok2, ", %any% [,)]")) - { + if (tok->tokAt(5 + varc)->str() == ",") { + for (const Token *tok2 = tok->tokAt(5 + varc); tok2 && tok2 != end; tok2 = tok2->next()) { + if (Token::Match(tok2, ", %any% [,)]")) { if (Token::Match(tok2->next(), "%str%")) parameters.push_back(tok2->next()); @@ -1808,29 +1608,24 @@ void CheckBufferOverrun::checkSprintfCall(const Token *tok, const MathLib::bigin else parameters.push_back(0); - } - else - { + } else { // Parameter is more complex, than just a value or variable. Ignore it for now // and skip to next token. parameters.push_back(0); // count parentheses for tok3 int ind = 0; - for (const Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) { if (tok3->str() == "(") ++ind; - else if (tok3->str() == ")") - { + else if (tok3->str() == ")") { --ind; if (ind < 0) break; } - else if (ind == 0 && tok3->str() == ",") - { + else if (ind == 0 && tok3->str() == ",") { tok2 = tok3->previous(); break; } @@ -1843,8 +1638,7 @@ void CheckBufferOverrun::checkSprintfCall(const Token *tok, const MathLib::bigin } MathLib::bigint len = countSprintfLength(tok->tokAt(4 + varc)->strValue(), parameters); - if (len > size) - { + if (len > size) { bufferOverrunError(tok); } } @@ -1862,46 +1656,36 @@ void CheckBufferOverrun::checkSprintfCall(const Token *tok, const MathLib::bigin void CheckBufferOverrun::checkBufferAllocatedWithStrlen() { const char pattern[] = "%var% = new|malloc|g_malloc|g_try_malloc|realloc|g_realloc|g_try_realloc"; - for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) - { + for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) { unsigned int dstVarId; unsigned int srcVarId; // Look for allocation of a buffer based on the size of a string - if (Token::Match(tok, "%var% = malloc|g_malloc|g_try_malloc ( strlen ( %var% ) )")) - { + if (Token::Match(tok, "%var% = malloc|g_malloc|g_try_malloc ( strlen ( %var% ) )")) { dstVarId = tok->varId(); srcVarId = tok->tokAt(6)->varId(); tok = tok->tokAt(8); - } - else if (Token::Match(tok, "%var% = new char [ strlen ( %var% ) ]")) - { + } else if (Token::Match(tok, "%var% = new char [ strlen ( %var% ) ]")) { dstVarId = tok->varId(); srcVarId = tok->tokAt(7)->varId(); tok = tok->tokAt(9); - } - else if (Token::Match(tok, "%var% = realloc|g_realloc|g_try_realloc ( %var% , strlen ( %var% ) )")) - { + } else if (Token::Match(tok, "%var% = realloc|g_realloc|g_try_realloc ( %var% , strlen ( %var% ) )")) { dstVarId = tok->varId(); srcVarId = tok->tokAt(8)->varId(); tok = tok->tokAt(10); - } - else + } else continue; // count { and } for tok int indentlevel = 0; - for (; tok && tok->next(); tok = tok->next()) - { + for (; tok && tok->next(); tok = tok->next()) { // To avoid false positives and added complexity, we will only look for // improper usage of the buffer within the block that it was allocated - if (tok->str() == "{") - { + if (tok->str() == "{") { ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { --indentlevel; if (indentlevel < 0) return; @@ -1912,14 +1696,11 @@ void CheckBufferOverrun::checkBufferAllocatedWithStrlen() break; if (Token::Match(tok, "strcpy ( %varid% , %var% )", dstVarId) && - tok->tokAt(4)->varId() == srcVarId) - { + tok->tokAt(4)->varId() == srcVarId) { bufferOverrunError(tok); - } - else if (Token::Match(tok, "sprintf ( %varid% , %str% , %var% )", dstVarId) && - tok->tokAt(6)->varId() == srcVarId && - tok->tokAt(4)->str().find("%s") != std::string::npos) - { + } else if (Token::Match(tok, "sprintf ( %varid% , %str% , %var% )", dstVarId) && + tok->tokAt(6)->varId() == srcVarId && + tok->tokAt(4)->str().find("%s") != std::string::npos) { bufferOverrunError(tok); } @@ -1942,17 +1723,13 @@ void CheckBufferOverrun::checkBufferAllocatedWithStrlen() void CheckBufferOverrun::checkInsecureCmdLineArgs() { const char pattern[] = "main ( int %var% , char *"; - for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) - { + for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) { // Get the name of the argv variable unsigned int varid = 0; - if (Token::Match(tok, "main ( int %var% , char * %var% [ ] ,|)")) - { + if (Token::Match(tok, "main ( int %var% , char * %var% [ ] ,|)")) { varid = tok->tokAt(7)->varId(); - } - else if (Token::Match(tok, "main ( int %var% , char * * %var% ,|)")) - { + } else if (Token::Match(tok, "main ( int %var% , char * * %var% ,|)")) { varid = tok->tokAt(8)->varId(); } if (varid == 0) @@ -1966,15 +1743,12 @@ void CheckBufferOverrun::checkInsecureCmdLineArgs() // Search within main() for possible buffer overruns involving argv int indentlevel = -1; - for (; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (; tok; tok = tok->next()) { + if (tok->str() == "{") { ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { --indentlevel; if (indentlevel < 0) return; @@ -1987,18 +1761,13 @@ void CheckBufferOverrun::checkInsecureCmdLineArgs() // Match common patterns that can result in a buffer overrun // e.g. strcpy(buffer, argv[0]) if (Token::Match(tok, "strcpy|strcat ( %var% , * %varid%", varid) || - Token::Match(tok, "strcpy|strcat ( %var% , %varid% [", varid)) - { + Token::Match(tok, "strcpy|strcat ( %var% , %varid% [", varid)) { cmdLineArgsError(tok); - } - else if (Token::Match(tok, "sprintf ( %var% , %str% , %varid% [", varid) && - tok->tokAt(4)->str().find("%s") != std::string::npos) - { + } else if (Token::Match(tok, "sprintf ( %var% , %str% , %varid% [", varid) && + tok->tokAt(4)->str().find("%s") != std::string::npos) { cmdLineArgsError(tok); - } - else if (Token::Match(tok, "sprintf ( %var% , %str% , * %varid%", varid) && - tok->tokAt(4)->str().find("%s") != std::string::npos) - { + } else if (Token::Match(tok, "sprintf ( %var% , %str% , * %varid%", varid) && + tok->tokAt(4)->str().find("%s") != std::string::npos) { cmdLineArgsError(tok); } @@ -2019,18 +1788,15 @@ void CheckBufferOverrun::negativeIndexError(const Token *tok, MathLib::bigint in void CheckBufferOverrun::negativeIndex() { const char pattern[] = "[ %num% ]"; - for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) - { + for (const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); tok; tok = Token::findmatch(tok->next(),pattern)) { const MathLib::bigint index = MathLib::toLongNumber(tok->next()->str()); - if (index < 0) - { + if (index < 0) { // Negative index. Check if it's an array. const Token *tok2 = tok; while (Token::simpleMatch(tok2->previous(), "]")) tok2 = tok2->previous()->link(); - if (tok2->previous() && tok2->previous()->varId()) - { + if (tok2->previous() && tok2->previous()->varId()) { const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(tok2->previous()->varId()); if (var && var->isArray()) negativeIndexError(tok, index); @@ -2076,8 +1842,7 @@ CheckBufferOverrun::ArrayInfo::ArrayInfo(const Variable *var, const Tokenizer *t CheckBufferOverrun::ArrayInfo & CheckBufferOverrun::ArrayInfo::operator=(const CheckBufferOverrun::ArrayInfo &ai) { - if (&ai != this) - { + if (&ai != this) { _element_size = ai._element_size; _num = ai._num; _varid = ai._varid; @@ -2142,17 +1907,12 @@ bool CheckBufferOverrun::ArrayInfo::declare(const Token *tok, const Tokenizer &t // Goto variable name token, get element size.. const Token *vartok = tok->tokAt(ivar); - if (vartok->str() == "*") - { + if (vartok->str() == "*") { _element_size = tokenizer.sizeOfType(vartok); vartok = vartok->next(); - } - else if (tok->str() == "struct") - { + } else if (tok->str() == "struct") { _element_size = 100; - } - else - { + } else { _element_size = tokenizer.sizeOfType(tok); } @@ -2166,8 +1926,7 @@ bool CheckBufferOverrun::ArrayInfo::declare(const Token *tok, const Tokenizer &t if (!Token::Match(atok, "%num% ] ;|=|[")) return false; - while (Token::Match(atok, "%num% ] ;|=|[")) - { + while (Token::Match(atok, "%num% ] ;|=|[")) { _num.push_back(MathLib::toLongNumber(atok->str())); atok = atok->next(); if (Token::simpleMatch(atok, "] [")) @@ -2186,25 +1945,21 @@ bool CheckBufferOverrun::ArrayInfo::declare(const Token *tok, const Tokenizer &t * @brief %Check for buffer overruns (using ExecutionPath) */ -class ExecutionPathBufferOverrun : public ExecutionPath -{ +class ExecutionPathBufferOverrun : public ExecutionPath { public: /** Startup constructor */ ExecutionPathBufferOverrun(Check *c, const std::map &arrayinfo) - : ExecutionPath(c, 0), arrayInfo(arrayinfo), value(0) - { + : ExecutionPath(c, 0), arrayInfo(arrayinfo), value(0) { } private: /** @brief Copy this check. Called from the ExecutionPath baseclass. */ - ExecutionPath *copy() - { + ExecutionPath *copy() { return new ExecutionPathBufferOverrun(*this); } /** @brief is other execution path equal? */ - bool is_equal(const ExecutionPath *e) const - { + bool is_equal(const ExecutionPath *e) const { const ExecutionPathBufferOverrun *c = static_cast(e); return (value == c->value); } @@ -2218,8 +1973,7 @@ private: /** internal constructor for creating extra checks */ ExecutionPathBufferOverrun(Check *c, const std::map &arrayinfo, unsigned int varid_) : ExecutionPath(c, varid_), - arrayInfo(arrayinfo) - { + arrayInfo(arrayinfo) { // Pretend that variables are initialized to 0 // This checking is not about uninitialized variables value = 0; @@ -2234,14 +1988,12 @@ private: * @param varid the variable id * @param value the assigned value */ - static void assign_value(std::list &checks, unsigned int varid, const std::string &value) - { + static void assign_value(std::list &checks, unsigned int varid, const std::string &value) { if (varid == 0) return; std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { ExecutionPathBufferOverrun *c = dynamic_cast(*it); if (c && c->varId == varid) c->value = MathLib::toLongNumber(value); @@ -2255,8 +2007,7 @@ private: * @param varid1 variable id for the array * @param varid2 variable id for the index */ - static void array_index(const Token *tok, std::list &checks, unsigned int varid1, unsigned int varid2) - { + static void array_index(const Token *tok, std::list &checks, unsigned int varid1, unsigned int varid2) { if (checks.empty() || varid1 == 0 || varid2 == 0) return; @@ -2273,15 +2024,12 @@ private: // Check if varid2 variable has a value that is out-of-bounds std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { ExecutionPathBufferOverrun *c = dynamic_cast(*it); - if (c && c->varId == varid2 && c->value >= ai.num(0)) - { + if (c && c->varId == varid2 && c->value >= ai.num(0)) { // variable value is out of bounds, report error CheckBufferOverrun *checkBufferOverrun = dynamic_cast(c->owner); - if (checkBufferOverrun) - { + if (checkBufferOverrun) { std::vector index; index.push_back(c->value); checkBufferOverrun->arrayIndexOutOfBoundsError(tok, ai, index); @@ -2291,42 +2039,35 @@ private: } } - const Token *parse(const Token &tok, std::list &checks) const - { - if (Token::Match(tok.previous(), "[;{}]")) - { + const Token *parse(const Token &tok, std::list &checks) const { + if (Token::Match(tok.previous(), "[;{}]")) { // Declaring variable.. - if (Token::Match(&tok, "%type% %var% ;") && tok.isStandardType()) - { + if (Token::Match(&tok, "%type% %var% ;") && tok.isStandardType()) { checks.push_back(new ExecutionPathBufferOverrun(owner, arrayInfo, tok.next()->varId())); return tok.tokAt(2); } // Assign variable.. - if (Token::Match(&tok, "%var% = %num% ;")) - { + if (Token::Match(&tok, "%var% = %num% ;")) { assign_value(checks, tok.varId(), tok.strAt(2)); return tok.tokAt(3); } } // Assign variable (unknown value = 0).. - if (Token::Match(&tok, "%var% =")) - { + if (Token::Match(&tok, "%var% =")) { assign_value(checks, tok.varId(), "0"); return &tok; } // Assign variable (unknown value = 0).. - if (Token::Match(tok.tokAt(-2), "(|, & %var% ,|)")) - { + if (Token::Match(tok.tokAt(-2), "(|, & %var% ,|)")) { assign_value(checks, tok.varId(), "0"); return &tok; } // Array index.. - if (Token::Match(&tok, "%var% [ %var% ]")) - { + if (Token::Match(&tok, "%var% [ %var% ]")) { array_index(&tok, checks, tok.varId(), tok.tokAt(2)->varId()); return tok.tokAt(3); } @@ -2342,8 +2083,7 @@ void CheckBufferOverrun::executionPaths() { // Parse all variables and extract array info.. std::map arrayInfo; - for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) - { + for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) { const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(i); if (var && var->isArray() && var->dimension(0) > 0) arrayInfo[i] = ArrayInfo(var, _tokenizer); @@ -2361,10 +2101,8 @@ void CheckBufferOverrun::arrayIndexThenCheck() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "%var% [ %var% ]")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "%var% [ %var% ]")) { const std::string arrayName(tok->str()); const std::string indexName(tok->strAt(2)); diff --git a/lib/checkbufferoverrun.h b/lib/checkbufferoverrun.h index 9bc1e69f6..b841f5047 100644 --- a/lib/checkbufferoverrun.h +++ b/lib/checkbufferoverrun.h @@ -46,8 +46,7 @@ class Variable; * I generally use 'buffer overrun' if you for example call a strcpy or * other function and pass a buffer and reads or writes too much data. */ -class CheckBufferOverrun : public Check -{ +class CheckBufferOverrun : public Check { public: /** This constructor is used when registering the CheckClass */ @@ -59,8 +58,7 @@ public: : Check(myName(), tokenizer, settings, errorLogger) { } - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckBufferOverrun checkBufferOverrun(tokenizer, settings, errorLogger); checkBufferOverrun.bufferOverrun(); checkBufferOverrun.negativeIndex(); @@ -111,8 +109,7 @@ public: void negativeIndex(); /** Information about N-dimensional array */ - class ArrayInfo - { + class ArrayInfo { private: /** number of elements of array */ std::vector _num; @@ -152,44 +149,36 @@ public: bool declare(const Token *tok, const Tokenizer &tokenizer); /** array sizes */ - const std::vector &num() const - { + const std::vector &num() const { return _num; } /** array size */ - MathLib::bigint num(size_t index) const - { + MathLib::bigint num(size_t index) const { return _num[index]; } - void num(size_t index, MathLib::bigint number) - { + void num(size_t index, MathLib::bigint number) { _num[index] = number; } /** size of each element */ - MathLib::bigint element_size() const - { + MathLib::bigint element_size() const { return _element_size; } /** Variable name */ - unsigned int varid() const - { + unsigned int varid() const { return _varid; } - void varid(unsigned int id) - { + void varid(unsigned int id) { _varid = id; } /** Variable name */ - const std::string &varname() const - { + const std::string &varname() const { return _varname; } - void varname(const std::string &name) - { + void varname(const std::string &name) { _varname = name; } }; @@ -235,8 +224,7 @@ public: void arrayIndexThenCheckError(const Token *tok, const std::string &indexName); void possibleBufferOverrunError(const Token *tok, const std::string &src, const std::string &dst, bool cat); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckBufferOverrun c(0, settings, errorLogger); std::vector indexes; indexes.push_back(2); @@ -254,13 +242,11 @@ public: c.possibleBufferOverrunError(0, "source", "destination", false); } - std::string myName() const - { + std::string myName() const { return "Bounds checking"; } - std::string classInfo() const - { + std::string classInfo() const { return "out of bounds checking"; } }; diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 4ca8585cf..7b1720241 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -34,9 +34,8 @@ //--------------------------------------------------------------------------- // Register CheckClass.. -namespace -{ -CheckClass instance; +namespace { + CheckClass instance; } //--------------------------------------------------------------------------- @@ -70,21 +69,17 @@ void CheckClass::constructors() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures if (!scope->isClassOrStruct()) continue; // There are no constructors. - if (scope->numConstructors == 0) - { + if (scope->numConstructors == 0) { // If there is a private variable, there should be a constructor.. std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { - if (var->isPrivate() && !var->isClass() && !var->isStatic()) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { + if (var->isPrivate() && !var->isClass() && !var->isStatic()) { noConstructorError(scope->classDef, scope->className, scope->classDef->str() == "struct"); break; } @@ -94,8 +89,7 @@ void CheckClass::constructors() std::list::const_iterator func; std::vector usage(scope->varlist.size()); - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { if (!func->hasBody || !(func->type == Function::eConstructor || func->type == Function::eCopyConstructor || func->type == Function::eOperatorEqual)) @@ -110,8 +104,7 @@ void CheckClass::constructors() // Check if any variables are uninitialized std::list::const_iterator var; unsigned int count = 0; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) { if (usage[count].assign || usage[count].init || var->isStatic()) continue; @@ -119,8 +112,7 @@ void CheckClass::constructors() continue; // Check if this is a class constructor - if (var->isClass() && func->type == Function::eConstructor) - { + if (var->isClass() && func->type == Function::eConstructor) { // Unknown type so assume it is initialized if (!var->type()) continue; @@ -136,15 +128,12 @@ void CheckClass::constructors() continue; // It's non-static and it's not initialized => error - if (func->type == Function::eOperatorEqual) - { + if (func->type == Function::eOperatorEqual) { const Token *operStart = func->token->tokAt(1); bool classNameUsed = false; - for (const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) - { - if (operTok->str() == scope->className) - { + for (const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) { + if (operTok->str() == scope->className) { classNameUsed = true; break; } @@ -152,8 +141,7 @@ void CheckClass::constructors() if (classNameUsed) operatorEqVarError(func->token, scope->className, var->name()); - } - else if (func->access != Private) + } else if (func->access != Private) uninitVarError(func->token, scope->className, var->name()); } } @@ -166,8 +154,7 @@ bool CheckClass::canNotCopy(const Scope *scope) const bool privateAssign = false; bool privateCopy = false; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { if (func->type == Function::eCopyConstructor && func->access == Private) privateCopy = true; else if (func->type == Function::eOperatorEqual && func->access == Private) @@ -182,10 +169,8 @@ void CheckClass::assignVar(const std::string &varname, const Scope *scope, std:: std::list::const_iterator var; unsigned int count = 0; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) - { - if (var->name() == varname) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) { + if (var->name() == varname) { usage[count].assign = true; return; } @@ -197,10 +182,8 @@ void CheckClass::initVar(const std::string &varname, const Scope *scope, std::ve std::list::const_iterator var; unsigned int count = 0; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) - { - if (var->name() == varname) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) { + if (var->name() == varname) { usage[count].init = true; return; } @@ -215,8 +198,7 @@ void CheckClass::assignAllVar(std::vector &usage) void CheckClass::clearAllVar(std::vector &usage) { - for (size_t i = 0; i < usage.size(); ++i) - { + for (size_t i = 0; i < usage.size(); ++i) { usage[i].assign = false; usage[i].init = false; } @@ -225,17 +207,14 @@ void CheckClass::clearAllVar(std::vector &usage) bool CheckClass::isBaseClassFunc(const Token *tok, const Scope *scope) { // Iterate through each base class... - for (size_t i = 0; i < scope->derivedFrom.size(); ++i) - { + for (size_t i = 0; i < scope->derivedFrom.size(); ++i) { const Scope *derivedFrom = scope->derivedFrom[i].scope; // Check if base class exists in database - if (derivedFrom) - { + if (derivedFrom) { std::list::const_iterator func; - for (func = derivedFrom->functionList.begin(); func != derivedFrom->functionList.end(); ++func) - { + for (func = derivedFrom->functionList.begin(); func != derivedFrom->functionList.end(); ++func) { if (func->tokenDef->str() == tok->str()) return true; } @@ -255,17 +234,14 @@ void CheckClass::initializeVarList(const Function &func, std::list unsigned int indentlevel = 0; const Token *ftok = func.token; - for (; ftok; ftok = ftok->next()) - { + for (; ftok; ftok = ftok->next()) { if (!ftok->next()) break; // Class constructor.. initializing variables like this // clKalle::clKalle() : var(value) { } - if (indentlevel == 0) - { - if (Assign && Token::Match(ftok, "%var% (")) - { + if (indentlevel == 0) { + if (Assign && Token::Match(ftok, "%var% (")) { initVar(ftok->str(), scope, usage); // assignment in the initializer.. @@ -278,14 +254,12 @@ void CheckClass::initializeVarList(const Function &func, std::list } - if (ftok->str() == "{") - { + if (ftok->str() == "{") { ++indentlevel; Assign = false; } - else if (ftok->str() == "}") - { + else if (ftok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; @@ -295,8 +269,7 @@ void CheckClass::initializeVarList(const Function &func, std::list continue; // Variable getting value from stream? - if (Token::Match(ftok, ">> %var%")) - { + if (Token::Match(ftok, ">> %var%")) { assignVar(ftok->strAt(1), scope, usage); } @@ -308,20 +281,16 @@ void CheckClass::initializeVarList(const Function &func, std::list ftok = ftok->next(); // Using the operator= function to initialize all variables.. - if (Token::Match(ftok->next(), "return| * this =")) - { + if (Token::Match(ftok->next(), "return| * this =")) { assignAllVar(usage); break; } // Calling member variable function? - if (Token::Match(ftok->next(), "%var% . %var% (")) - { + if (Token::Match(ftok->next(), "%var% . %var% (")) { std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { - if (var->varId() == ftok->next()->varId()) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { + if (var->varId() == ftok->next()->varId()) { /** @todo false negative: we assume function changes variable state */ assignVar(ftok->next()->str(), scope, usage); continue; @@ -345,8 +314,7 @@ void CheckClass::initializeVarList(const Function &func, std::list ftok = ftok->next(); // Skip "( * this )" - if (Token::simpleMatch(ftok, "( * this ) .")) - { + if (Token::simpleMatch(ftok, "( * this ) .")) { ftok = ftok->tokAt(5); } @@ -359,15 +327,13 @@ void CheckClass::initializeVarList(const Function &func, std::list ftok = ftok->tokAt(2); // Clearing all variables.. - if (Token::Match(ftok, "::| memset ( this ,")) - { + if (Token::Match(ftok, "::| memset ( this ,")) { assignAllVar(usage); return; } // Clearing array.. - else if (Token::Match(ftok, "::| memset ( %var% ,")) - { + else if (Token::Match(ftok, "::| memset ( %var% ,")) { const int offset = ftok->str() == "::" ? 1 : 0; assignVar(ftok->strAt(2 + offset), scope, usage); ftok = ftok->tokAt(1 + offset)->link(); @@ -376,12 +342,10 @@ void CheckClass::initializeVarList(const Function &func, std::list // Calling member function? else if (Token::simpleMatch(ftok, "operator= (") && - ftok->previous()->str() != "::") - { + ftok->previous()->str() != "::") { // recursive call / calling overloaded function // assume that all variables are initialized - if (std::find(callstack.begin(), callstack.end(), ftok->str()) != callstack.end()) - { + if (std::find(callstack.begin(), callstack.end(), ftok->str()) != callstack.end()) { /** @todo false negative: just bail */ assignAllVar(usage); return; @@ -390,18 +354,15 @@ void CheckClass::initializeVarList(const Function &func, std::list /** @todo check function parameters for overloaded function so we check the right one */ // check if member function exists std::list::const_iterator it; - for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) - { + for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) { if (ftok->str() == it->tokenDef->str() && it->type != Function::eConstructor) break; } // member function found - if (it != scope->functionList.end()) - { + if (it != scope->functionList.end()) { // member function has implementation - if (it->hasBody) - { + if (it->hasBody) { // initialize variable use list using member function callstack.push_back(ftok->str()); initializeVarList(*it, callstack, scope, usage); @@ -409,25 +370,19 @@ void CheckClass::initializeVarList(const Function &func, std::list } // there is a called member function, but it has no implementation, so we assume it initializes everything - else - { + else { assignAllVar(usage); } } // using default operator =, assume everything initialized - else - { + else { assignAllVar(usage); } - } - else if (Token::Match(ftok, "%var% (") && ftok->str() != "if") - { + } else if (Token::Match(ftok, "%var% (") && ftok->str() != "if") { // Passing "this" => assume that everything is initialized - for (const Token *tok2 = ftok->next()->link(); tok2 && tok2 != ftok; tok2 = tok2->previous()) - { - if (tok2->str() == "this") - { + for (const Token *tok2 = ftok->next()->link(); tok2 && tok2 != ftok; tok2 = tok2->previous()) { + if (tok2->str() == "this") { assignAllVar(usage); return; } @@ -435,26 +390,22 @@ void CheckClass::initializeVarList(const Function &func, std::list // recursive call / calling overloaded function // assume that all variables are initialized - if (std::find(callstack.begin(), callstack.end(), ftok->str()) != callstack.end()) - { + if (std::find(callstack.begin(), callstack.end(), ftok->str()) != callstack.end()) { assignAllVar(usage); return; } // check if member function std::list::const_iterator it; - for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) - { + for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) { if (ftok->str() == it->tokenDef->str() && it->type != Function::eConstructor) break; } // member function found - if (it != scope->functionList.end()) - { + if (it != scope->functionList.end()) { // member function has implementation - if (it->hasBody) - { + if (it->hasBody) { // initialize variable use list using member function callstack.push_back(ftok->str()); initializeVarList(*it, callstack, scope, usage); @@ -462,18 +413,15 @@ void CheckClass::initializeVarList(const Function &func, std::list } // there is a called member function, but it has no implementation, so we assume it initializes everything - else - { + else { assignAllVar(usage); } } // not member function - else - { + else { // could be a base class virtual function, so we assume it initializes everything - if (func.type != Function::eConstructor && isBaseClassFunc(ftok, scope)) - { + if (func.type != Function::eConstructor && isBaseClassFunc(ftok, scope)) { /** @todo False Negative: we should look at the base class functions to see if they * call any derived class virtual functions that change the derived class state */ @@ -486,21 +434,17 @@ void CheckClass::initializeVarList(const Function &func, std::list // the function is external and it's neither friend nor inherited virtual function. // assume all variables that are passed to it are initialized.. - else - { + else { unsigned int indentlevel2 = 0; - for (const Token *tok = ftok->tokAt(2); tok; tok = tok->next()) - { + for (const Token *tok = ftok->tokAt(2); tok; tok = tok->next()) { if (tok->str() == "(") ++indentlevel2; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (indentlevel2 == 0) break; --indentlevel2; } - if (tok->isName()) - { + if (tok->isName()) { assignVar(tok->str(), scope, usage); } } @@ -509,49 +453,42 @@ void CheckClass::initializeVarList(const Function &func, std::list } // Assignment of member variable? - else if (Token::Match(ftok, "%var% =")) - { + else if (Token::Match(ftok, "%var% =")) { assignVar(ftok->str(), scope, usage); } // Assignment of array item of member variable? else if (Token::Match(ftok, "%var% [") && - Token::simpleMatch(ftok->next()->link(), "] =")) - { + Token::simpleMatch(ftok->next()->link(), "] =")) { assignVar(ftok->str(), scope, usage); } // Assignment of member of array item of member variable? else if (Token::Match(ftok, "%var% [ ") && (Token::Match(ftok->next()->link(), "] . %var% =") || - Token::Match(ftok->next()->link(), "] . %var% . %var% ="))) - { + Token::Match(ftok->next()->link(), "] . %var% . %var% ="))) { assignVar(ftok->str(), scope, usage); } // Assignment of array item of member variable? else if (Token::Match(ftok, "%var% [") && Token::simpleMatch(ftok->next()->link(), "] [") && - Token::simpleMatch(ftok->next()->link()->next()->link(), "] =")) - { + Token::simpleMatch(ftok->next()->link()->next()->link(), "] =")) { assignVar(ftok->str(), scope, usage); } // Assignment of array item of member variable? - else if (Token::Match(ftok, "* %var% =")) - { + else if (Token::Match(ftok, "* %var% =")) { assignVar(ftok->next()->str(), scope, usage); } // Assignment of struct member of member variable? - else if (Token::Match(ftok, "%var% . %any% =")) - { + else if (Token::Match(ftok, "%var% . %any% =")) { assignVar(ftok->str(), scope, usage); } // The functions 'clear' and 'Clear' are supposed to initialize variable. - if (Token::Match(ftok, "%var% . clear|Clear (")) - { + if (Token::Match(ftok, "%var% . clear|Clear (")) { assignVar(ftok->str(), scope, usage); } } @@ -600,8 +537,7 @@ void CheckClass::privateFunctions() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures if (!scope->isClassOrStruct()) continue; @@ -620,10 +556,8 @@ void CheckClass::privateFunctions() // check that the whole class implementation is seen bool whole = true; std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { - if (!func->hasBody) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { + if (!func->hasBody) { // empty private copy constructors and assignment operators are OK if ((func->type == Function::eCopyConstructor || func->type == Function::eOperatorEqual) && @@ -642,10 +576,8 @@ void CheckClass::privateFunctions() std::list FuncList; /** @todo embedded class have access to private functions */ - if (!scope->getNestedNonFunctions()) - { - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + if (!scope->getNestedNonFunctions()) { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { // Get private functions.. if (func->type == Function::eFunction && func->access == Private) FuncList.push_back(func->tokenDef); @@ -653,21 +585,16 @@ void CheckClass::privateFunctions() } // Check that all private functions are used.. - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { const Token *ftok = func->start; - if (ftok) - { + if (ftok) { const Token *etok = ftok->link(); - for (; ftok != etok; ftok = ftok->next()) - { - if (Token::Match(ftok, "%var% (")) - { + for (; ftok != etok; ftok = ftok->next()) { + if (Token::Match(ftok, "%var% (")) { // Remove function from FuncList std::list::iterator it = FuncList.begin(); - while (it != FuncList.end()) - { + while (it != FuncList.end()) { if (ftok->str() == (*it)->str()) FuncList.erase(it++); else @@ -678,8 +605,7 @@ void CheckClass::privateFunctions() } } - while (!FuncList.empty()) - { + while (!FuncList.empty()) { // Final check; check if the function pointer is used somewhere.. const std::string _pattern("return|(|)|,|= &|" + FuncList.front()->str()); @@ -690,8 +616,7 @@ void CheckClass::privateFunctions() if (!Token::findmatch(_tokenizer->tokens(), _pattern.c_str()) && !Token::findmatch(_tokenizer->tokens(), _pattern2.c_str()) && !Token::findmatch(_tokenizer->tokens(), methodAsArgument.c_str()) - ) - { + ) { unusedPrivateFunctionError(FuncList.front(), classname, FuncList.front()->str()); } FuncList.pop_front(); @@ -714,20 +639,17 @@ void CheckClass::noMemset() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { // only check functions with bodies if (!func->hasBody) continue; // Locate all 'memset' tokens.. const Token *end = func->start->link(); - for (const Token *tok = func->start; tok && tok != end; tok = tok->next()) - { + for (const Token *tok = func->start; tok && tok != end; tok = tok->next()) { if (!Token::Match(tok, "memset|memcpy|memmove")) continue; @@ -744,8 +666,7 @@ void CheckClass::noMemset() typeTok = tok->tokAt(10); else if (Token::Match(tok, "%type% ( %var% , %var% , sizeof ( %type% ) )")) typeTok = tok->tokAt(8); - else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( %var% ) )")) - { + else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( %var% ) )")) { unsigned int varid = tok->tokAt(3)->varId(); const Variable *var = symbolDatabase->getVariableFromVarId(varid); if (var && (var->typeStartToken() == var->typeEndToken() || @@ -769,8 +690,7 @@ void CheckClass::noMemset() void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Scope *type) { // recursively check all parent classes - for (size_t i = 0; i < type->derivedFrom.size(); i++) - { + for (size_t i = 0; i < type->derivedFrom.size(); i++) { if (type->derivedFrom[i].scope) checkMemsetType(start, tok, type->derivedFrom[i].scope); } @@ -778,8 +698,7 @@ void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Sco // Warn if type is a class that contains any virtual functions std::list::const_iterator func; - for (func = type->functionList.begin(); func != type->functionList.end(); ++func) - { + for (func = type->functionList.begin(); func != type->functionList.end(); ++func) { if (func->isVirtual) memsetError(tok, tok->str(), "virtual method", type->classDef->str()); } @@ -787,11 +706,9 @@ void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Sco // Warn if type is a class or struct that contains any std::* variables std::list::const_iterator var; - for (var = type->varlist.begin(); var != type->varlist.end(); ++var) - { + for (var = type->varlist.begin(); var != type->varlist.end(); ++var) { // don't warn if variable static or const - if (!var->isStatic() && !var->isConst()) - { + if (!var->isStatic() && !var->isConst()) { const Token *tok1 = var->typeStartToken(); // check for std:: type that is not a pointer or reference @@ -823,24 +740,19 @@ void CheckClass::operatorEq() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { if (!scope->isClassOrStruct()) continue; std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { - if (func->type == Function::eOperatorEqual && func->access != Private) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { + if (func->type == Function::eOperatorEqual && func->access != Private) { // use definition for check so we don't have to deal with qualification if (!(Token::Match(func->tokenDef->tokAt(-3), ";|}|{|public:|protected:|private: %type% &") && - func->tokenDef->strAt(-2) == scope->className)) - { + func->tokenDef->strAt(-2) == scope->className)) { // make sure we really have a copy assignment operator - if (Token::Match(func->tokenDef->tokAt(2), "const| %var% &")) - { + if (Token::Match(func->tokenDef->tokAt(2), "const| %var% &")) { if (func->tokenDef->strAt(2) == "const" && func->tokenDef->strAt(3) == scope->className) operatorEqReturnError(func->tokenDef->tokAt(-1), scope->className); @@ -872,21 +784,16 @@ void CheckClass::operatorEqRetRefThis() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures - if (scope->isClassOrStruct()) - { + if (scope->isClassOrStruct()) { std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { - if (func->type == Function::eOperatorEqual && func->hasBody) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { + if (func->type == Function::eOperatorEqual && func->hasBody) { // make sure return signature is correct if (Token::Match(func->tokenDef->tokAt(-3), ";|}|{|public:|protected:|private: %type% &") && - func->tokenDef->strAt(-2) == scope->className) - { + func->tokenDef->strAt(-2) == scope->className) { // find the ')' const Token *tok = func->token->next()->link(); @@ -902,11 +809,9 @@ void CheckClass::checkReturnPtrThis(const Scope *scope, const Function *func, co { bool foundReturn = false; - for (; tok && tok != last; tok = tok->next()) - { + for (; tok && tok != last; tok = tok->next()) { // check for return of reference to this - if (tok->str() == "return") - { + if (tok->str() == "return") { foundReturn = true; std::string cast("( " + scope->className + " & )"); if (Token::Match(tok->next(), cast.c_str())) @@ -914,24 +819,19 @@ void CheckClass::checkReturnPtrThis(const Scope *scope, const Function *func, co // check if a function is called if (Token::Match(tok->tokAt(1), "%any% (") && - tok->tokAt(2)->link()->next()->str() == ";") - { + tok->tokAt(2)->link()->next()->str() == ";") { std::list::const_iterator it; // check if it is a member function - for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) - { + for (it = scope->functionList.begin(); it != scope->functionList.end(); ++it) { // check for a regular function with the same name and a body if (it->type == Function::eFunction && it->hasBody && - it->token->str() == tok->next()->str()) - { + it->token->str() == tok->next()->str()) { // check for the proper return type if (it->tokenDef->previous()->str() == "&" && - it->tokenDef->strAt(-2) == scope->className) - { + it->tokenDef->strAt(-2) == scope->className) { // make sure it's not a const function - if (it->arg->link()->next()->str() != "const") - { + if (it->arg->link()->next()->str() != "const") { /** @todo make sure argument types match */ // make sure it's not the same function if (&*it != func) @@ -988,8 +888,7 @@ void CheckClass::operatorEqToSelf() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { if (!scope->isClassOrStruct()) continue; @@ -999,19 +898,15 @@ void CheckClass::operatorEqToSelf() if (scope->derivedFrom.size() > 1) continue; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { - if (func->type == Function::eOperatorEqual && func->hasBody) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { + if (func->type == Function::eOperatorEqual && func->hasBody) { // make sure return signature is correct if (Token::Match(func->tokenDef->tokAt(-3), ";|}|{|public:|protected:|private: %type% &") && - func->tokenDef->strAt(-2) == scope->className) - { + func->tokenDef->strAt(-2) == scope->className) { // find the parameter name const Token *rhs = func->argumentList.begin()->nameToken(); - if (!hasAssignSelf(&(*func), rhs)) - { + if (!hasAssignSelf(&(*func), rhs)) { if (hasDeallocation(&(*func))) operatorEqToSelfError(func->token); } @@ -1031,59 +926,47 @@ bool CheckClass::hasDeallocation(const Function *func) // This check needs to do careful analysis someday to get this // correct with a high degree of certainty. const Token *last = func->start->link(); - for (const Token *tok = func->start; tok && (tok != last); tok = tok->next()) - { + for (const Token *tok = func->start; tok && (tok != last); tok = tok->next()) { // check for deallocating memory - if (Token::Match(tok, "{|;|, free ( %var%")) - { + if (Token::Match(tok, "{|;|, free ( %var%")) { const Token *var = tok->tokAt(3); // we should probably check that var is a pointer in this class const Token *tok1 = tok->tokAt(4); - while (tok1 && (tok1 != last)) - { - if (Token::Match(tok1, "%var% =")) - { + while (tok1 && (tok1 != last)) { + if (Token::Match(tok1, "%var% =")) { if (tok1->str() == var->str()) return true; } tok1 = tok1->next(); } - } - else if (Token::Match(tok, "{|;|, delete [ ] %var%")) - { + } else if (Token::Match(tok, "{|;|, delete [ ] %var%")) { const Token *var = tok->tokAt(4); // we should probably check that var is a pointer in this class const Token *tok1 = tok->tokAt(5); - while (tok1 && (tok1 != last)) - { - if (Token::Match(tok1, "%var% = new %type% [")) - { + while (tok1 && (tok1 != last)) { + if (Token::Match(tok1, "%var% = new %type% [")) { if (tok1->str() == var->str()) return true; } tok1 = tok1->next(); } - } - else if (Token::Match(tok, "{|;|, delete %var%")) - { + } else if (Token::Match(tok, "{|;|, delete %var%")) { const Token *var = tok->tokAt(2); // we should probably check that var is a pointer in this class const Token *tok1 = tok->tokAt(3); - while (tok1 && (tok1 != last)) - { - if (Token::Match(tok1, "%var% = new")) - { + while (tok1 && (tok1 != last)) { + if (Token::Match(tok1, "%var% = new")) { if (tok1->str() == var->str()) return true; } @@ -1099,24 +982,17 @@ bool CheckClass::hasDeallocation(const Function *func) bool CheckClass::hasAssignSelf(const Function *func, const Token *rhs) { const Token *last = func->start->link(); - for (const Token *tok = func->start; tok && tok != last; tok = tok->next()) - { - if (Token::simpleMatch(tok, "if (")) - { + for (const Token *tok = func->start; tok && tok != last; tok = tok->next()) { + if (Token::simpleMatch(tok, "if (")) { const Token *tok1 = tok->tokAt(2); const Token *tok2 = tok->tokAt(1)->link(); - if (tok1 && tok2) - { - for (; tok1 && tok1 != tok2; tok1 = tok1->next()) - { - if (Token::Match(tok1, "this ==|!= & %var%")) - { + if (tok1 && tok2) { + for (; tok1 && tok1 != tok2; tok1 = tok1->next()) { + if (Token::Match(tok1, "this ==|!= & %var%")) { if (tok1->tokAt(3)->str() == rhs->str()) return true; - } - else if (Token::Match(tok1, "& %var% ==|!= this")) - { + } else if (Token::Match(tok1, "& %var% ==|!= this")) { if (tok1->tokAt(1)->str() == rhs->str()) return true; } @@ -1148,8 +1024,7 @@ void CheckClass::virtualDestructor() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // Skip base classes and namespaces if (scope->derivedFrom.empty()) continue; @@ -1169,11 +1044,9 @@ void CheckClass::virtualDestructor() const Token *derivedClass = derived->tokAt(1); // Iterate through each base class... - for (unsigned int j = 0; j < scope->derivedFrom.size(); ++j) - { + for (unsigned int j = 0; j < scope->derivedFrom.size(); ++j) { // Check if base class is public and exists in database - if (scope->derivedFrom[j].access != Private && scope->derivedFrom[j].scope) - { + if (scope->derivedFrom[j].access != Private && scope->derivedFrom[j].scope) { const Scope *derivedFrom = scope->derivedFrom[j].scope; // Name of base class.. @@ -1194,11 +1067,9 @@ void CheckClass::virtualDestructor() // No deletion of derived class instance through base class pointer found => the code is ok bool ok = true; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring base class pointer - if (Token::simpleMatch(tok, baseName.c_str())) - { + if (Token::simpleMatch(tok, baseName.c_str())) { if (Token::Match(tok->previous(), ("[;{}] " + baseName + " * %var% ;").c_str())) basepointer.insert(tok->tokAt(2)->varId()); } @@ -1206,11 +1077,9 @@ void CheckClass::virtualDestructor() // Assign base class pointer with pointer to derived class instance if (Token::Match(tok, "[;{}] %var% =") && tok->next()->varId() > 0 && - basepointer.find(tok->next()->varId()) != basepointer.end()) - { + basepointer.find(tok->next()->varId()) != basepointer.end()) { // new derived class.. - if (Token::simpleMatch(tok->tokAt(3), ("new " + derivedClass->str()).c_str())) - { + if (Token::simpleMatch(tok->tokAt(3), ("new " + derivedClass->str()).c_str())) { dontDelete.insert(tok->next()->varId()); } } @@ -1218,8 +1087,7 @@ void CheckClass::virtualDestructor() // Delete base class pointer that might point at derived class if (Token::Match(tok, "delete %var% ;") && tok->next()->varId() && - dontDelete.find(tok->next()->varId()) != dontDelete.end()) - { + dontDelete.find(tok->next()->varId()) != dontDelete.end()) { ok = false; break; } @@ -1237,21 +1105,17 @@ void CheckClass::virtualDestructor() base = base_destructor->token; // Check that there is a destructor.. - if (!base_destructor) - { + if (!base_destructor) { if (derivedFrom->derivedFrom.empty()) virtualDestructorError(derivedFrom->classDef, baseName, derivedClass->str()); - } - else if (!base_destructor->isVirtual) - { + } else if (!base_destructor->isVirtual) { // TODO: This is just a temporary fix, better solution is needed. // Skip situations where base class has base classes of its own, because // some of the base classes might have virtual destructor. // Proper solution is to check all of the base classes. If base class is not // found or if one of the base classes has virtual destructor, error should not // be printed. See TODO test case "virtualDestructorInherited" - if (derivedFrom->derivedFrom.empty()) - { + if (derivedFrom->derivedFrom.empty()) { // Make sure that the destructor is public (protected or private // would not compile if inheritance is used in a way that would // cause the bug we are trying to find here.) @@ -1279,8 +1143,7 @@ void CheckClass::thisSubtraction() return; const Token *tok = _tokenizer->tokens(); - for (;;) - { + for (;;) { tok = Token::findmatch(tok, "this - %var%"); if (!tok) break; @@ -1307,8 +1170,7 @@ void CheckClass::checkConst() return; // Don't check C# and JAVA classes - if (_tokenizer->isJavaOrCSharp()) - { + if (_tokenizer->isJavaOrCSharp()) { return; } @@ -1316,27 +1178,23 @@ void CheckClass::checkConst() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures if (!scope->isClassOrStruct()) continue; std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { // does the function have a body? - if (func->type == Function::eFunction && func->hasBody && !func->isFriend && !func->isStatic && !func->isConst && !func->isVirtual) - { + if (func->type == Function::eFunction && func->hasBody && !func->isFriend && !func->isStatic && !func->isConst && !func->isVirtual) { // get last token of return type const Token *previous = func->tokenDef->isName() ? func->token->previous() : func->token->tokAt(-2); while (previous && previous->str() == "::") previous = previous->tokAt(-2); // does the function return a pointer or reference? - if (Token::Match(previous, "*|&")) - { + if (Token::Match(previous, "*|&")) { const Token *temp = func->token->previous(); while (!Token::Match(temp->previous(), ";|}|{|public:|protected:|private:")) @@ -1344,13 +1202,10 @@ void CheckClass::checkConst() if (temp->str() != "const") continue; - } - else if (Token::Match(previous->previous(), "*|& >")) - { + } else if (Token::Match(previous->previous(), "*|& >")) { const Token *temp = func->token->previous(); - while (!Token::Match(temp->previous(), ";|}|{|public:|protected:|private:")) - { + while (!Token::Match(temp->previous(), ";|}|{|public:|protected:|private:")) { temp = temp->previous(); if (temp->str() == "const") break; @@ -1358,20 +1213,15 @@ void CheckClass::checkConst() if (temp->str() != "const") continue; - } - else - { + } else { // don't warn for unknown types.. // LPVOID, HDC, etc - if (previous->isName()) - { + if (previous->isName()) { bool allupper = true; const std::string s(previous->str()); - for (std::string::size_type pos = 0; pos < s.size(); ++pos) - { + for (std::string::size_type pos = 0; pos < s.size(); ++pos) { const char ch = s[pos]; - if (!(ch == '_' || (ch >= 'A' && ch <= 'Z'))) - { + if (!(ch == '_' || (ch >= 'A' && ch <= 'Z'))) { allupper = false; break; } @@ -1385,19 +1235,16 @@ void CheckClass::checkConst() const Token *paramEnd = func->arg->link(); // check if base class function is virtual - if (!scope->derivedFrom.empty()) - { + if (!scope->derivedFrom.empty()) { if (isVirtualFunc(&(*scope), func->tokenDef)) continue; } // if nothing non-const was found. write error.. - if (checkConstFunc(&(*scope), paramEnd)) - { + if (checkConstFunc(&(*scope), paramEnd)) { std::string classname = scope->className; const Scope *nest = scope->nestedIn; - while (nest && nest->type != Scope::eGlobal) - { + while (nest && nest->type != Scope::eGlobal) { classname = std::string(nest->className + "::" + classname); nest = nest->nestedIn; } @@ -1425,41 +1272,28 @@ bool CheckClass::isMemberVar(const Scope *scope, const Token *tok) bool again = false; // try to find the member variable - do - { + do { again = false; - if (tok->str() == "this") - { + if (tok->str() == "this") { return true; - } - else if (Token::Match(tok->tokAt(-3), "( * this )")) - { + } else if (Token::Match(tok->tokAt(-3), "( * this )")) { return true; - } - else if (Token::Match(tok->tokAt(-2), "%var% . %var%")) - { + } else if (Token::Match(tok->tokAt(-2), "%var% . %var%")) { tok = tok->tokAt(-2); again = true; - } - else if (Token::Match(tok->tokAt(-2), "] . %var%")) - { + } else if (Token::Match(tok->tokAt(-2), "] . %var%")) { tok = tok->tokAt(-2)->link()->previous(); again = true; - } - else if (tok->str() == "]") - { + } else if (tok->str() == "]") { tok = tok->link()->previous(); again = true; } - } - while (again); + } while (again); std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { - if (var->name() == tok->str()) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { + if (var->name() == tok->str()) { if (tok->varId() == 0) symbolDatabase->debugMessage(tok, "CheckClass::isMemberVar found used member variable \'" + tok->str() + "\' with varid 0"); @@ -1468,17 +1302,14 @@ bool CheckClass::isMemberVar(const Scope *scope, const Token *tok) } // not found in this class - if (!scope->derivedFrom.empty()) - { + if (!scope->derivedFrom.empty()) { // check each base class - for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) - { + for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) { // find the base class const Scope *derivedFrom = scope->derivedFrom[i].scope; // find the function in the base class - if (derivedFrom) - { + if (derivedFrom) { if (isMemberVar(derivedFrom, tok)) return true; } @@ -1495,20 +1326,17 @@ static int countParameters(const Token *tok) int numpar = 1; int parlevel = 0; - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (tok->str() == "(") ++parlevel; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (parlevel <= 1) break; --parlevel; } - else if (parlevel == 1 && tok->str() == ",") - { + else if (parlevel == 1 && tok->str() == ",") { ++numpar; } } @@ -1524,12 +1352,10 @@ bool CheckClass::isConstMemberFunc(const Scope *scope, const Token *tok) unsigned int matches = 0; unsigned int consts = 0; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { /** @todo we need to look at the argument types when there are overloaded functions * with the same number of arguments */ - if (func->tokenDef->str() == tok->str() && func->argCount() == args) - { + if (func->tokenDef->str() == tok->str() && func->argCount() == args) { matches++; if (func->isConst) consts++; @@ -1541,17 +1367,14 @@ bool CheckClass::isConstMemberFunc(const Scope *scope, const Token *tok) return true; // not found in this class - if (!scope->derivedFrom.empty()) - { + if (!scope->derivedFrom.empty()) { // check each base class - for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) - { + for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) { // find the base class const Scope *derivedFrom = scope->derivedFrom[i].scope; // find the function in the base class - if (derivedFrom) - { + if (derivedFrom) { if (isConstMemberFunc(derivedFrom, tok)) return true; } @@ -1567,81 +1390,64 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) // it can be a const function.. unsigned int indentlevel = 0; bool isconst = true; - for (const Token *tok1 = tok; tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = tok; tok1; tok1 = tok1->next()) { if (tok1->str() == "{") ++indentlevel; - else if (tok1->str() == "}") - { + else if (tok1->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // assignment.. = += |= .. - else if (tok1->isAssignmentOp()) - { - if (tok1->next()->str() == "this") - { + else if (tok1->isAssignmentOp()) { + if (tok1->next()->str() == "this") { isconst = false; break; - } - else if (isMemberVar(scope, tok1->previous())) - { + } else if (isMemberVar(scope, tok1->previous())) { isconst = false; break; } } // streaming: << - else if (tok1->str() == "<<" && isMemberVar(scope, tok1->previous())) - { + else if (tok1->str() == "<<" && isMemberVar(scope, tok1->previous())) { isconst = false; break; - } - else if (Token::simpleMatch(tok1->previous(), ") <<") && - isMemberVar(scope, tok1->tokAt(-2))) - { + } else if (Token::simpleMatch(tok1->previous(), ") <<") && + isMemberVar(scope, tok1->tokAt(-2))) { isconst = false; break; } // streaming: >> - else if (tok1->str() == ">>" && isMemberVar(scope, tok1->next())) - { + else if (tok1->str() == ">>" && isMemberVar(scope, tok1->next())) { isconst = false; break; } // increment/decrement (member variable?).. - else if (Token::Match(tok1, "++|--")) - { + else if (Token::Match(tok1, "++|--")) { // var++ and var-- if (Token::Match(tok1->previous(), "%var%") && - tok1->previous()->str() != "return") - { - if (isMemberVar(scope, tok1->previous())) - { + tok1->previous()->str() != "return") { + if (isMemberVar(scope, tok1->previous())) { isconst = false; break; } } // var[...]++ and var[...]-- - else if (tok1->previous()->str() == "]") - { - if (isMemberVar(scope, tok1->previous()->link()->previous())) - { + else if (tok1->previous()->str() == "]") { + if (isMemberVar(scope, tok1->previous()->link()->previous())) { isconst = false; break; } } // ++var and --var - else if (Token::Match(tok1->next(), "%var%")) - { - if (isMemberVar(scope, tok1->next())) - { + else if (Token::Match(tok1->next(), "%var%")) { + if (isMemberVar(scope, tok1->next())) { isconst = false; break; } @@ -1649,13 +1455,11 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) } // std::map variable member - else if (Token::Match(tok1, "%var% [") && isMemberVar(scope, tok1)) - { + else if (Token::Match(tok1, "%var% [") && isMemberVar(scope, tok1)) { const Variable *var = symbolDatabase->getVariableFromVarId(tok1->varId()); if (var && (var->typeStartToken()->str() == "map" || - Token::simpleMatch(var->typeStartToken(), "std :: map"))) - { + Token::simpleMatch(var->typeStartToken(), "std :: map"))) { isconst = false; break; } @@ -1663,21 +1467,15 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) // function call.. else if (Token::Match(tok1, "%var% (") && - !(Token::Match(tok1, "return|c_str|if|string|switch|while|catch|for") || tok1->isStandardType())) - { - if (!isConstMemberFunc(scope, tok1)) - { + !(Token::Match(tok1, "return|c_str|if|string|switch|while|catch|for") || tok1->isStandardType())) { + if (!isConstMemberFunc(scope, tok1)) { isconst = false; break; } - } - else if (Token::Match(tok1, "%var% < %any% > (")) - { + } else if (Token::Match(tok1, "%var% < %any% > (")) { isconst = false; break; - } - else if (Token::Match(tok1, "%var% . size|empty ( )") && tok1->varId()) - { + } else if (Token::Match(tok1, "%var% . size|empty ( )") && tok1->varId()) { // assume all std::*::size() and std::*::empty() are const const Variable *var = symbolDatabase->getVariableFromVarId(tok1->varId()); @@ -1686,8 +1484,7 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) } // delete.. - else if (tok1->str() == "delete") - { + else if (tok1->str() == "delete") { isconst = false; break; } @@ -1700,33 +1497,26 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) bool CheckClass::isVirtualFunc(const Scope *scope, const Token *functionToken) const { // check each base class - for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) - { + for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) { // check if base class exists in database - if (scope->derivedFrom[i].scope) - { + if (scope->derivedFrom[i].scope) { const Scope *derivedFrom = scope->derivedFrom[i].scope; std::list::const_iterator func; // check if function defined in base class - for (func = derivedFrom->functionList.begin(); func != derivedFrom->functionList.end(); ++func) - { - if (func->isVirtual) - { + for (func = derivedFrom->functionList.begin(); func != derivedFrom->functionList.end(); ++func) { + if (func->isVirtual) { const Token *tok = func->tokenDef; - if (tok->str() == functionToken->str()) - { + if (tok->str() == functionToken->str()) { const Token *temp1 = tok->previous(); const Token *temp2 = functionToken->previous(); bool returnMatch = true; // check for matching return parameters - while (temp1->str() != "virtual") - { - if (temp1->str() != temp2->str()) - { + while (temp1->str() != "virtual") { + if (temp1->str() != temp2->str()) { returnMatch = false; break; } @@ -1736,22 +1526,18 @@ bool CheckClass::isVirtualFunc(const Scope *scope, const Token *functionToken) c } // check for matching function parameters - if (returnMatch && symbolDatabase->argsMatch(scope, tok->tokAt(2), functionToken->tokAt(2), std::string(""), 0)) - { + if (returnMatch && symbolDatabase->argsMatch(scope, tok->tokAt(2), functionToken->tokAt(2), std::string(""), 0)) { return true; } } } } - if (!derivedFrom->derivedFrom.empty()) - { + if (!derivedFrom->derivedFrom.empty()) { if (isVirtualFunc(derivedFrom, functionToken)) return true; } - } - else - { + } else { // unable to find base class so assume it has a virtual function return true; } @@ -1789,8 +1575,7 @@ void CheckClass::checkConstError2(const Token *tok1, const Token *tok2, const st // ClassCheck: Check that initializer list is in declared order. //--------------------------------------------------------------------------- -struct VarInfo -{ +struct VarInfo { VarInfo(const Variable *_var, const Token *_tok) : var(_var), tok(_tok) { } @@ -1815,38 +1600,31 @@ void CheckClass::initializerList() std::list::const_iterator info; // iterate through all scopes looking for classes and structures - for (info = symbolDatabase->scopeList.begin(); info != symbolDatabase->scopeList.end(); ++info) - { + for (info = symbolDatabase->scopeList.begin(); info != symbolDatabase->scopeList.end(); ++info) { if (!info->isClassOrStruct()) continue; std::list::const_iterator func; // iterate through all member functions looking for constructors - for (func = info->functionList.begin(); func != info->functionList.end(); ++func) - { - if (func->type == Function::eConstructor && func->hasBody) - { + for (func = info->functionList.begin(); func != info->functionList.end(); ++func) { + if (func->type == Function::eConstructor && func->hasBody) { // check for initializer list const Token *tok = func->arg->link()->next(); - if (tok->str() == ":") - { + if (tok->str() == ":") { std::vector vars; tok = tok->next(); // find all variable initializations in list - while (tok && tok->str() != "{") - { - if (Token::Match(tok, "%var% (")) - { + while (tok && tok->str() != "{") { + if (Token::Match(tok, "%var% (")) { const Variable *var = info->getVariable(tok->str()); if (var) vars.push_back(VarInfo(var, tok)); - if (Token::Match(tok->tokAt(2), "%var% =")) - { + if (Token::Match(tok->tokAt(2), "%var% =")) { var = info->getVariable(tok->strAt(2)); if (var) @@ -1857,10 +1635,8 @@ void CheckClass::initializerList() } // need at least 2 members to have out of order initialization - if (vars.size() > 1) - { - for (unsigned int i = 1; i < vars.size(); i++) - { + if (vars.size() > 1) { + for (unsigned int i = 1; i < vars.size(); i++) { // check for out of order initialization if (vars[i].var->index() < vars[i - 1].var->index()) initializerListError(vars[i].tok,vars[i].var->nameToken(), info->className, vars[i].var->name()); diff --git a/lib/checkclass.h b/lib/checkclass.h index 93a24c0f0..a5d4b7ae1 100644 --- a/lib/checkclass.h +++ b/lib/checkclass.h @@ -32,8 +32,7 @@ class Token; /** @brief %Check classes. Uninitialized member variables, non-conforming operators, missing virtual destructor, etc */ -class CheckClass : public Check -{ +class CheckClass : public Check { public: /** @brief This constructor is used when registering the CheckClass */ CheckClass() : Check(myName()), symbolDatabase(NULL) @@ -43,8 +42,7 @@ public: CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger); /** @brief Run checks on the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckClass checkClass(tokenizer, settings, errorLogger); // can't be a simplified check .. the 'sizeof' is used. @@ -52,8 +50,7 @@ public: } /** @brief Run checks on the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckClass checkClass(tokenizer, settings, errorLogger); // Coding style checks @@ -132,8 +129,7 @@ private: void checkConstError2(const Token *tok1, const Token *tok2, const std::string &classname, const std::string &funcname); void initializerListError(const Token *tok1,const Token *tok2, const std::string & classname, const std::string &varname); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckClass c(0, settings, errorLogger); c.noConstructorError(0, "classname", false); c.uninitVarError(0, "classname", "varname"); @@ -149,13 +145,11 @@ private: c.initializerListError(0, 0, "class", "variable"); } - std::string myName() const - { + std::string myName() const { return "Class"; } - std::string classInfo() const - { + std::string classInfo() const { return "Check the code for each class.\n" "* Missing constructors\n" "* Are all variables initialized by the constructors?\n" @@ -183,8 +177,7 @@ private: // constructors helper function /** @brief Information about a member variable. Used when checking for uninitialized variables */ - struct Usage - { + struct Usage { Usage() : assign(false), init(false) { } /** @brief has this variable been assigned? */ diff --git a/lib/checkexceptionsafety.cpp b/lib/checkexceptionsafety.cpp index eb0d13386..c6212f0f2 100644 --- a/lib/checkexceptionsafety.cpp +++ b/lib/checkexceptionsafety.cpp @@ -24,9 +24,8 @@ //--------------------------------------------------------------------------- // Register CheckExceptionSafety.. -namespace -{ -CheckExceptionSafety instance; +namespace { + CheckExceptionSafety instance; } @@ -39,8 +38,7 @@ void CheckExceptionSafety::destructors() return; // Perform check.. - for (const Token * tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token * tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Skip executable scopes if (Token::simpleMatch(tok, ") {")) tok = tok->next()->link(); @@ -51,23 +49,19 @@ void CheckExceptionSafety::destructors() // Inspect this destructor.. unsigned int indentlevel = 0; - for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { ++indentlevel; } - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // throw found within a destructor - else if (tok2->str() == "throw") - { + else if (tok2->str() == "throw") { destructorsError(tok2); break; } @@ -82,8 +76,7 @@ void CheckExceptionSafety::deallocThrow() { // Deallocate a global/member pointer and then throw exception // the pointer will be a dead pointer - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // only looking for delete now if (tok->str() != "delete") continue; @@ -104,16 +97,13 @@ void CheckExceptionSafety::deallocThrow() { // TODO: Isn't it better to use symbol database instead? bool globalVar = false; - for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) - { - if (tok2->varId() == varid) - { + for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) { + if (tok2->varId() == varid) { globalVar = true; break; } - if (tok2->str() == "class") - { + if (tok2->str() == "class") { while (tok2 && tok2->str() != ";" && tok2->str() != "{") tok2 = tok2->next(); tok2 = tok2 ? tok2->next() : 0; @@ -121,8 +111,7 @@ void CheckExceptionSafety::deallocThrow() break; } - if (tok2->str() == "{") - { + if (tok2->str() == "{") { tok2 = tok2->link(); if (!tok2) break; @@ -141,12 +130,10 @@ void CheckExceptionSafety::deallocThrow() const Token *ThrowToken = 0; // is there a throw after the deallocation? - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel == 0) break; --indentlevel; @@ -157,8 +144,7 @@ void CheckExceptionSafety::deallocThrow() // if the variable is not assigned after the throw then it // is assumed that it is not the intention that it is a dead pointer. - else if (Token::Match(tok2, "%varid% =", varid)) - { + else if (Token::Match(tok2, "%varid% =", varid)) { if (ThrowToken) deallocThrowError(ThrowToken, tok->str()); break; @@ -180,15 +166,13 @@ void CheckExceptionSafety::checkRethrowCopy() const char catchPattern[] = "catch ( const| %type% &|*| %var% ) { %any%"; const Token *tok = Token::findmatch(_tokenizer->tokens(), catchPattern); - while (tok) - { + while (tok) { const Token *startBlockTok = tok->next()->link()->next(); const Token *endBlockTok = startBlockTok->link(); const unsigned int varid = startBlockTok->tokAt(-2)->varId(); const Token* rethrowTok = Token::findmatch(startBlockTok, "throw %varid%", endBlockTok, varid); - if (rethrowTok) - { + if (rethrowTok) { rethrowCopyError(rethrowTok, startBlockTok->tokAt(-2)->str()); } diff --git a/lib/checkexceptionsafety.h b/lib/checkexceptionsafety.h index a984bf5f3..eb3ef2b1a 100644 --- a/lib/checkexceptionsafety.h +++ b/lib/checkexceptionsafety.h @@ -39,8 +39,7 @@ class Token; * that certain variable values are corrupt. */ -class CheckExceptionSafety : public Check -{ +class CheckExceptionSafety : public Check { public: /** This constructor is used when registering the CheckClass */ CheckExceptionSafety() : Check(myName()) @@ -52,8 +51,7 @@ public: { } /** Checks that uses the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckExceptionSafety checkExceptionSafety(tokenizer, settings, errorLogger); checkExceptionSafety.destructors(); checkExceptionSafety.deallocThrow(); @@ -71,18 +69,15 @@ public: private: /** Don't throw exceptions in destructors */ - void destructorsError(const Token * const tok) - { + void destructorsError(const Token * const tok) { reportError(tok, Severity::error, "exceptThrowInDestructor", "Throwing exception in destructor"); } - void deallocThrowError(const Token * const tok, const std::string &varname) - { + void deallocThrowError(const Token * const tok, const std::string &varname) { reportError(tok, Severity::error, "exceptDeallocThrow", "Throwing exception in invalid state, " + varname + " points at deallocated memory"); } - void rethrowCopyError(const Token * const tok, const std::string &varname) - { + void rethrowCopyError(const Token * const tok, const std::string &varname) { reportError(tok, Severity::style, "exceptRethrowCopy", "Throwing a copy of the caught exception instead of rethrowing the original exception\n" "Rethrowing an exception with 'throw " + varname + ";' makes an unnecessary copy of '" + varname + "'.\n" @@ -90,8 +85,7 @@ private: } /** Generate all possible errors (for --errorlist) */ - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckExceptionSafety c(0, settings, errorLogger); c.destructorsError(0); c.deallocThrowError(0, "p"); @@ -99,14 +93,12 @@ private: } /** Short description of class (for --doc) */ - std::string myName() const - { + std::string myName() const { return "Exception Safety"; } /** wiki formatted description of the class (for --doc) */ - std::string classInfo() const - { + std::string classInfo() const { return "Checking exception safety\n" "* Throwing exceptions in destructors\n" "* Throwing exception during invalid state\n" diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 5efde9797..77757dca8 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -33,12 +33,11 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckMemoryLeakInFunction instance1; -CheckMemoryLeakInClass instance2; -CheckMemoryLeakStructMember instance3; -CheckMemoryLeakNoVar instance4; +namespace { + CheckMemoryLeakInFunction instance1; + CheckMemoryLeakInClass instance2; + CheckMemoryLeakStructMember instance3; + CheckMemoryLeakNoVar instance4; } /** List of functions that can be ignored when searching for memory leaks. @@ -47,8 +46,7 @@ CheckMemoryLeakNoVar instance4; * This list contains function names whith const parameters e.g.: atof(const char *) * Reference: http://www.aquaphoenix.com/ref/gnu_c_library/libc_492.html#SEC492 */ -static const char * const call_func_white_list[] = -{ +static const char * const call_func_white_list[] = { "_open", "_wopen", "access", "adjtime", "asctime", "asctime_r", "asprintf", "assert" , "atof", "atoi", "atol", "chdir", "chmod", "chown" , "clearerr", "creat", "ctime", "ctime_r", "delete", "execl", "execle" @@ -111,8 +109,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, // * var = new char[10]; // * var = strdup("hello"); // * var = strndup("hello", 3); - if (tok2 && tok2->str() == "(") - { + if (tok2 && tok2->str() == "(") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : NULL; } @@ -131,8 +128,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, "kcalloc", 0 }; - for (unsigned int i = 0; mallocfunc[i]; i++) - { + for (unsigned int i = 0; mallocfunc[i]; i++) { if (tok2->str() == mallocfunc[i]) return Malloc; } @@ -155,8 +151,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, "g_strdup_printf", 0 }; - for (unsigned int i = 0; gmallocfunc[i]; i++) - { + for (unsigned int i = 0; gmallocfunc[i]; i++) { if (tok2->str() == gmallocfunc[i]) return gMalloc; } @@ -174,8 +169,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, if (Token::Match(tok2, "fopen|tmpfile|g_fopen (")) return File; - if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp (")) - { + if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp (")) { // is there a user function with this name? if (tokenizer && Token::findmatch(tokenizer->tokens(), ("%type% *|&| " + tok2->str()).c_str())) return No; @@ -212,8 +206,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getReallocationType(const Token *tok { // What we may have... // * var = (char *)realloc(..; - if (tok2 && tok2->str() == "(") - { + if (tok2 && tok2->str() == "(") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : NULL; } @@ -343,8 +336,7 @@ void CheckMemoryLeak::reportErr(const std::list &callstack, Sever { std::list locations; - for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) - { + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { const Token * const tok = *it; ErrorLogger::ErrorMessage::FileLocation loc; @@ -406,13 +398,11 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok, return No; // Locate start of function - while (tok) - { + while (tok) { if (tok->str() == "{" || tok->str() == "}") return No; - if (tok->str() == "(") - { + if (tok->str() == "(") { tok = tok->link(); break; } @@ -430,25 +420,20 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok, // Get return pointer.. unsigned int varid = 0; unsigned int indentlevel = 0; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) return No; --indentlevel; } - if (Token::Match(tok2, "return %var% ;")) - { + if (Token::Match(tok2, "return %var% ;")) { if (indentlevel != 1) return No; varid = tok2->next()->varId(); break; - } - else if (tok2->str() == "return") - { + } else if (tok2->str() == "return") { AllocType allocType = getAllocationType(tok2->next(), 0, callstack); if (allocType != No) return allocType; @@ -461,22 +446,17 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok, // Check if return pointer is allocated.. AllocType allocType = No; - while (0 != (tok = tok->next())) - { - if (Token::Match(tok, "%varid% =", varid)) - { + while (0 != (tok = tok->next())) { + if (Token::Match(tok, "%varid% =", varid)) { allocType = getAllocationType(tok->tokAt(2), varid, callstack); } - if (Token::Match(tok, "= %varid% ;", varid)) - { + if (Token::Match(tok, "= %varid% ;", varid)) { return No; } - if (Token::Match(tok, "static %type% * %varid% [;{}=]", varid)) - { + if (Token::Match(tok, "static %type% * %varid% [;{}=]", varid)) { return No; } - if (Token::Match(tok, "[(,] %varid% [,)]", varid)) - { + if (Token::Match(tok, "[(,] %varid% [,)]", varid)) { return No; } if (tok->str() == "return") @@ -496,35 +476,30 @@ const char *CheckMemoryLeak::functionArgAlloc(const Token *tok, unsigned int tar allocType = No; - while (tok) - { + while (tok) { if (tok->str() == "{" || tok->str() == "}") return ""; - if (tok->str() == "(") - { + if (tok->str() == "(") { if (parlevel != 0) return ""; ++parlevel; ++par; } - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (parlevel != 1) return ""; break; } - else if (parlevel == 1 && tok->str() == ",") - { + else if (parlevel == 1 && tok->str() == ",") { ++par; } tok = tok->next(); - if (parlevel == 1 && par == targetpar && Token::Match(tok, "%type% * * %var%")) - { + if (parlevel == 1 && par == targetpar && Token::Match(tok, "%type% * * %var%")) { varid = tok->tokAt(3)->varId(); } } @@ -542,39 +517,28 @@ const char *CheckMemoryLeak::functionArgAlloc(const Token *tok, unsigned int tar // Check if pointer is allocated. unsigned int indentlevel = 0; int realloc = 0; - while (0 != (tok = tok->next())) - { + while (0 != (tok = tok->next())) { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; - } - else if (tok->varId() == varid) - { - if (Token::Match(tok->tokAt(-3), "free ( * %varid% )", varid)) - { + } else if (tok->varId() == varid) { + if (Token::Match(tok->tokAt(-3), "free ( * %varid% )", varid)) { realloc = 1; allocType = No; - } - else if (Token::Match(tok->previous(), "* %varid% =", varid)) - { + } else if (Token::Match(tok->previous(), "* %varid% =", varid)) { allocType = getAllocationType(tok->tokAt(2), varid); - if (allocType == No) - { + if (allocType == No) { allocType = getReallocationType(tok->tokAt(2), varid); } - if (allocType != No) - { + if (allocType != No) { if (realloc) return "realloc"; return "alloc"; } - } - else - { + } else { // unhandled variable usage: bailout return ""; } @@ -598,34 +562,29 @@ void CheckMemoryLeakInFunction::parse_noreturn() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // parse this function to check if it contains an "exit" call.. unsigned int indentlevel = 1; - for (const Token *tok2 = scope->classStart->next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = scope->classStart->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { --indentlevel; if (indentlevel == 0) break; } - if (Token::Match(tok2->previous(), "[;{}] exit (")) - { + if (Token::Match(tok2->previous(), "[;{}] exit (")) { noreturn.insert(scope->className); break; } } // This function is not a noreturn function - if (indentlevel == 0) - { + if (indentlevel == 0) { notnoreturn.insert(scope->className); } } @@ -649,20 +608,17 @@ static int countParameters(const Token *tok) int numpar = 1; int parlevel = 0; - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (tok->str() == "(") ++parlevel; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (parlevel <= 1) return numpar; --parlevel; } - else if (parlevel == 1 && tok->str() == ",") - { + else if (parlevel == 1 && tok->str() == ",") { ++numpar; } } @@ -679,8 +635,7 @@ bool CheckMemoryLeakInFunction::test_white_list(const std::string &funcname) const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz) { - if (test_white_list(tok->str())) - { + if (test_white_list(tok->str())) { if (tok->str() == "asprintf" || tok->str() == "delete" || tok->str() == "fclose" || @@ -690,18 +645,15 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::liststr() == "realloc" || tok->str() == "return" || tok->str() == "switch" || - tok->str() == "while") - { + tok->str() == "while") { return 0; } // is the varid a parameter? - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == ")") break; - if (tok2->varId() == varid) - { + if (tok2->varId() == varid) { if (tok->strAt(-1) == ".") return "use"; else if (tok2->strAt(1) == "=") @@ -724,16 +676,14 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::liststr()); - for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) - { + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { if ((*it) && (*it)->str() == funcname) return "recursive"; } callstack.push_back(tok); // lock/unlock.. - if (varid == 0) - { + if (varid == 0) { const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str()); while (ftok && (ftok->str() != "{")) ftok = ftok->next(); @@ -753,8 +703,7 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list it is not a noreturn function if (tok->strAt(-1) == "=") return NULL; @@ -772,25 +721,20 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::listprevious()->str() == "."); const bool eq(tok->previous()->str() == "="); - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (tok->str() == "(") ++parlevel; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { --parlevel; - if (parlevel < 1) - { + if (parlevel < 1) { return (eq || _settings->experimental) ? 0 : "callfunc"; } } - if (parlevel == 1) - { + if (parlevel == 1) { if (tok->str() == ",") ++par; - if (varid > 0 && Token::Match(tok, "[,()] %varid% [,()]", varid)) - { + if (varid > 0 && Token::Match(tok, "[,()] %varid% [,()]", varid)) { if (dot) return "use"; @@ -836,14 +780,12 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list 0 && Token::Match(tok, "[,()] & %varid% [,()]", varid)) - { + if (varid > 0 && Token::Match(tok, "[,()] & %varid% [,()]", varid)) { const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str()); AllocType a; const char *ret = functionArgAlloc(ftok, par, a); - if (a != No) - { + if (a != No) { if (alloctype == No) alloctype = a; else if (alloctype != a) @@ -886,15 +828,11 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()) - { - if (tok->str() == "{") - { + for (; tok; tok = tok->next()) { + if (tok->str() == "{") { addtoken(&rettail, tok, "{"); ++indentlevel; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { addtoken(&rettail, tok, "}"); if (indentlevel <= 0) break; @@ -910,8 +848,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0 && parlevel == 0) - { + if (Token::Match(tok, "[;{}]") && varid > 0 && parlevel == 0) { if (Token::Match(tok->next(), "[{};]")) continue; @@ -925,48 +862,38 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext(), "continue|break|return|throw|goto|do|else")) ; - else - { + else { const Token *skipToToken = 0; // scan statement for interesting keywords / varid - for (tok2 = tok->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == ";") - { + for (tok2 = tok->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == ";") { // nothing interesting found => skip this statement skipToToken = tok2->previous(); break; } if (tok2->varId() == varid || - tok2->str() == ":" || tok2->str() == "{" || tok2->str() == "}") - { + tok2->str() == ":" || tok2->str() == "{" || tok2->str() == "}") { break; } } - if (skipToToken) - { + if (skipToToken) { tok = skipToToken; continue; } } } - if (varid == 0) - { - if (!callstack.empty() && Token::Match(tok, "[;{}] __cppcheck_lock|__cppcheck_unlock ( ) ;")) - { + if (varid == 0) { + if (!callstack.empty() && Token::Match(tok, "[;{}] __cppcheck_lock|__cppcheck_unlock ( ) ;")) { // Type of leak = Resource leak alloctype = dealloctype = CheckMemoryLeak::File; - if (tok->next()->str() == "__cppcheck_lock") - { + if (tok->next()->str() == "__cppcheck_lock") { addtoken(&rettail, tok, "alloc"); - } - else - { + } else { addtoken(&rettail, tok, "dealloc"); } @@ -974,18 +901,14 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); continue; } - } - else - { + } else { - if (Token::Match(tok, "%varid% = close ( %varid% )", varid)) - { + if (Token::Match(tok, "%varid% = close ( %varid% )", varid)) { addtoken(&rettail, tok, "dealloc"); addtoken(&rettail, tok, ";"); addtoken(&rettail, tok, "assign"); @@ -995,46 +918,37 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(4)->link(); continue; } if (Token::Match(tok->previous(), "[(;{}] %varid% =", varid) || - Token::Match(tok, "asprintf ( & %varid% ,", varid)) - { + Token::Match(tok, "asprintf ( & %varid% ,", varid)) { CheckMemoryLeak::AllocType alloc; - if (Token::simpleMatch(tok, "asprintf (")) - { + if (Token::simpleMatch(tok, "asprintf (")) { // todo: check how the return value is used. - if (!Token::Match(tok->previous(), "[;{}]")) - { + if (!Token::Match(tok->previous(), "[;{}]")) { Tokenizer::deleteTokens(rethead); return 0; } alloc = Malloc; tok = tok->next()->link(); - } - else - { + } else { alloc = getAllocationType(tok->tokAt(2), varid); } bool realloc = false; if (sz > 1 && Token::Match(tok->tokAt(2), "malloc ( %num% )") && - (MathLib::toLongNumber(tok->strAt(4)) % long(sz)) != 0) - { + (MathLib::toLongNumber(tok->strAt(4)) % long(sz)) != 0) { mismatchSizeError(tok->tokAt(4), tok->strAt(4)); } - if (alloc == CheckMemoryLeak::No) - { + if (alloc == CheckMemoryLeak::No) { alloc = getReallocationType(tok->tokAt(2), varid); - if (alloc != CheckMemoryLeak::No) - { + if (alloc != CheckMemoryLeak::No) { addtoken(&rettail, tok, "realloc"); addtoken(&rettail, tok, ";"); realloc = true; @@ -1046,29 +960,20 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(2), "new struct| %type% [(;]")) - { + if (alloc == CheckMemoryLeak::New) { + if (Token::Match(tok->tokAt(2), "new struct| %type% [(;]")) { const int offset = tok->strAt(3) == "struct" ? 1 : 0; - if (isclass(_tokenizer, tok->tokAt(3 + offset), varid)) - { + if (isclass(_tokenizer, tok->tokAt(3 + offset), varid)) { alloc = No; } - } - else if (Token::Match(tok->tokAt(2), "new ( nothrow ) struct| %type%")) - { + } else if (Token::Match(tok->tokAt(2), "new ( nothrow ) struct| %type%")) { const int offset = tok->strAt(6) == "struct" ? 1 : 0; - if (isclass(_tokenizer, tok->tokAt(6 + offset), varid)) - { + if (isclass(_tokenizer, tok->tokAt(6 + offset), varid)) { alloc = No; } - } - else if (Token::Match(tok->tokAt(2), "new ( std :: nothrow ) struct| %type%")) - { + } else if (Token::Match(tok->tokAt(2), "new ( std :: nothrow ) struct| %type%")) { const int offset = tok->strAt(8) == "struct" ? 1 : 0; - if (isclass(_tokenizer, tok->tokAt(8 + offset), varid)) - { + if (isclass(_tokenizer, tok->tokAt(8 + offset), varid)) { alloc = No; } } @@ -1077,16 +982,14 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokens(), "%varid%", varid)->str()); callstack.pop_back(); @@ -1094,31 +997,25 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(3)->link(); continue; } } // assignment.. - else - { + else { // is the pointer in rhs? bool rhs = false; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == ";") - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == ";") { if (rhs) tok = tok2; break; } - if (Token::Match(tok2, "[=+(,] %varid%", varid)) - { - if (!rhs && Token::Match(tok2, "[(,]")) - { + if (Token::Match(tok2, "[=+(,] %varid%", varid)) { + if (!rhs && Token::Match(tok2, "[(,]")) { addtoken(&rettail, tok, "use"); addtoken(&rettail, tok, ";"); } @@ -1132,22 +1029,19 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listprevious(), "[;{})=|] %var%")) - { + if (Token::Match(tok->previous(), "[;{})=|] %var%")) { AllocType dealloc = getDeallocationType(tok, varid); if (dealloc != No && tok->str() == "fcloseall" && alloctype != dealloc) dealloc = No; - else if (dealloc != No) - { + else if (dealloc != No) { addtoken(&rettail, tok, "dealloc"); if (dealloctype != No && dealloctype != dealloc) dealloc = Many; - if (dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) - { + if (dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, Token::findmatch(_tokenizer->tokens(), "%varid%", varid)->str()); callstack.pop_back(); @@ -1161,42 +1055,33 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); continue; - } - else if (Token::Match(tok, "if ( %varid% == -1 )", varid) || - Token::Match(tok, "if ( %varid% < 0 )", varid)) - { + } else if (Token::Match(tok, "if ( %varid% == -1 )", varid) || + Token::Match(tok, "if ( %varid% < 0 )", varid)) { addtoken(&rettail, tok, "if(!var)"); tok = tok->next()->link(); continue; } } - if (Token::Match(tok, "if ( %varid% )", varid)) - { + if (Token::Match(tok, "if ( %varid% )", varid)) { addtoken(&rettail, tok, "if(var)"); // Make sure the "use" will not be added tok = tok->next()->link(); continue; - } - else if (Token::simpleMatch(tok, "if (") && notvar(tok->tokAt(2), varid, true)) - { + } else if (Token::simpleMatch(tok, "if (") && notvar(tok->tokAt(2), varid, true)) { addtoken(&rettail, tok, "if(!var)"); // parse the if-body. // if a variable is assigned then add variable to "extravar". - for (const Token *tok2 = tok->next()->link()->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->next()->link()->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") tok2 = tok2->link(); else if (tok2->str() == "}") @@ -1207,78 +1092,61 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); continue; - } - else - { + } else { // Check if the condition depends on var or extravar somehow.. bool dep = false; int innerParlevel = 0; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++innerParlevel; - if (tok2->str() == ")") - { + if (tok2->str() == ")") { --innerParlevel; if (innerParlevel <= 0) break; } - if (Token::Match(tok2, "close|pclose|fclose|closedir ( %varid% )", varid)) - { + if (Token::Match(tok2, "close|pclose|fclose|closedir ( %varid% )", varid)) { addtoken(&rettail, tok, "dealloc"); addtoken(&rettail, tok, ";"); dep = true; break; } - if (alloctype == Fd && Token::Match(tok2, "%varid% !=|>=", varid)) - { + if (alloctype == Fd && Token::Match(tok2, "%varid% !=|>=", varid)) { dep = true; } - if (innerParlevel > 0 && Token::Match(tok2, "! %varid%", varid)) - { + if (innerParlevel > 0 && Token::Match(tok2, "! %varid%", varid)) { dep = true; } - if (innerParlevel > 0 && Token::Match(tok2, "%var% (") && !test_white_list(tok2->str())) - { + if (innerParlevel > 0 && Token::Match(tok2, "%var% (") && !test_white_list(tok2->str())) { bool use = false; - for (const Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) { if (tok3->str() == "(") tok3 = tok3->link(); else if (tok3->str() == ")") break; - else if (Token::Match(tok3->previous(), "(|, &| %varid% ,|)", varid)) - { + else if (Token::Match(tok3->previous(), "(|, &| %varid% ,|)", varid)) { use = true; break; } } - if (use) - { + if (use) { addtoken(&rettail, tok, "use"); addtoken(&rettail, tok, ";"); dep = false; break; } } - if (tok2->varId() && extravar.find(tok2->varId()) != extravar.end()) - { + if (tok2->varId() && extravar.find(tok2->varId()) != extravar.end()) { dep = true; } } - if (Token::Match(tok, "if ( ! %varid% &&", varid)) - { + if (Token::Match(tok, "if ( ! %varid% &&", varid)) { addtoken(&rettail, tok, "if(!var)"); - } - else if (tok->next() && - tok->next()->link() && - Token::Match(tok->next()->link()->tokAt(-3), "&& ! %varid%", varid)) - { + } else if (tok->next() && + tok->next()->link() && + Token::Match(tok->next()->link()->tokAt(-3), "&& ! %varid%", varid)) { addtoken(&rettail, tok, "if(!var)"); - } - else - { + } else { addtoken(&rettail, tok, (dep ? "ifv" : "if")); } @@ -1288,16 +1156,14 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "else") || (tok->str() == "switch")) - { + if ((tok->str() == "else") || (tok->str() == "switch")) { addtoken(&rettail, tok, tok->str()); if (Token::simpleMatch(tok, "switch (")) tok = tok->next()->link(); continue; } - if ((tok->str() == "case")) - { + if ((tok->str() == "case")) { addtoken(&rettail, tok, "case"); addtoken(&rettail, tok, ";"); if (Token::Match(tok, "case %any% :")) @@ -1305,56 +1171,45 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "default")) - { + if ((tok->str() == "default")) { addtoken(&rettail, tok, "default"); addtoken(&rettail, tok, ";"); continue; } // Loops.. - else if ((tok->str() == "for") || (tok->str() == "while")) - { + else if ((tok->str() == "for") || (tok->str() == "while")) { if (Token::simpleMatch(tok, "while ( true )") || - Token::simpleMatch(tok, "for ( ; ; )")) - { + Token::simpleMatch(tok, "for ( ; ; )")) { addtoken(&rettail, tok, "while1"); tok = tok->next()->link(); continue; } - else if (varid && getDeallocationType(tok->tokAt(2), varid) != No) - { + else if (varid && getDeallocationType(tok->tokAt(2), varid) != No) { addtoken(&rettail, tok, "dealloc"); addtoken(&rettail, tok, ";"); } - else if (alloctype == Fd && varid) - { + else if (alloctype == Fd && varid) { if (Token::Match(tok, "while ( 0 <= %varid% )", varid) || - Token::Match(tok, "while ( %varid% != -1 )", varid)) - { + Token::Match(tok, "while ( %varid% != -1 )", varid)) { addtoken(&rettail, tok, "while(var)"); tok = tok->next()->link(); continue; - } - else if (Token::Match(tok, "while ( %varid% == -1 )", varid) || - Token::Match(tok, "while ( %varid% < 0 )", varid)) - { + } else if (Token::Match(tok, "while ( %varid% == -1 )", varid) || + Token::Match(tok, "while ( %varid% < 0 )", varid)) { addtoken(&rettail, tok, "while(!var)"); tok = tok->next()->link(); continue; } } - else if (varid && Token::Match(tok, "while ( %varid% )", varid)) - { + else if (varid && Token::Match(tok, "while ( %varid% )", varid)) { addtoken(&rettail, tok, "while(var)"); tok = tok->next()->link(); continue; - } - else if (varid && Token::simpleMatch(tok, "while (") && notvar(tok->tokAt(2), varid, true)) - { + } else if (varid && Token::simpleMatch(tok, "while (") && notvar(tok->tokAt(2), varid, true)) { addtoken(&rettail, tok, "while(!var)"); tok = tok->next()->link(); continue; @@ -1362,22 +1217,18 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0) - { + if (varid > 0) { unsigned int parlevel2 = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel2; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel2 > 0) --parlevel2; else break; } - if (notvar(tok2, varid)) - { + if (notvar(tok2, varid)) { addtoken(&rettail, tok2, "!var"); break; } @@ -1386,32 +1237,24 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "do")) - { + if ((tok->str() == "do")) { addtoken(&rettail, tok, "do"); continue; } // continue / break.. - if (tok->str() == "continue") - { + if (tok->str() == "continue") { addtoken(&rettail, tok, "continue"); - } - else if (tok->str() == "break") - { + } else if (tok->str() == "break") { addtoken(&rettail, tok, "break"); - } - else if (tok->str() == "goto") - { + } else if (tok->str() == "goto") { addtoken(&rettail, tok, "goto"); } // Return.. - else if (tok->str() == "return") - { + else if (tok->str() == "return") { addtoken(&rettail, tok, "return"); - if (varid == 0) - { + if (varid == 0) { addtoken(&rettail, tok, ";"); while (tok && tok->str() != ";") tok = tok->next(); @@ -1421,34 +1264,28 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext(), "std :: auto_ptr <")) - { + if (Token::simpleMatch(tok->next(), "std :: auto_ptr <")) { const Token *tok2 = tok->tokAt(5); while (tok2 && tok2->str() != ">") tok2 = tok2->next(); - if (Token::Match(tok2, "> ( %varid% )", varid)) - { + if (Token::Match(tok2, "> ( %varid% )", varid)) { addtoken(&rettail, tok, "use"); tok = tok2->tokAt(3); } } - else if (varid && Token::Match(tok, "return strcpy|strncpy|memcpy ( %varid%", varid)) - { + else if (varid && Token::Match(tok, "return strcpy|strncpy|memcpy ( %varid%", varid)) { addtoken(&rettail, tok, "use"); tok = tok->tokAt(2); } - else - { + else { bool use = false; std::stack f; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == ";") - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == ";") { tok = tok2; break; } @@ -1458,17 +1295,13 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == ")") f.pop(); - if (tok2->varId() == varid) - { + if (tok2->varId() == varid) { // Read data.. if (!Token::Match(tok2->previous(), "&|(") && - Token::simpleMatch(tok2->next(), "[")) - { - } - else if (f.empty() || - !test_white_list(f.top()->str()) || - getDeallocationType(f.top(),varid)) - { + Token::simpleMatch(tok2->next(), "[")) { + } else if (f.empty() || + !test_white_list(f.top()->str()) || + getDeallocationType(f.top(),varid)) { use = true; } } @@ -1484,31 +1317,24 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr()); // Assignment.. - if (varid) - { - if (Token::simpleMatch(tok, "= {")) - { + if (varid) { + if (Token::simpleMatch(tok, "= {")) { unsigned int indentlevel2 = 0; bool use = false; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel2; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel2 <= 1) break; --indentlevel2; - } - else if (tok2->varId() == varid) - { + } else if (tok2->varId() == varid) { use = true; break; } } - if (use) - { + if (use) { addtoken(&rettail, tok, "use"); addtoken(&rettail, tok, ";"); tok = tok->next()->link(); @@ -1521,12 +1347,9 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listprevious(), ";|{|}|=|(|,|%op% %varid% [", varid)) - { + } else if (Token::Match(tok->previous(), ";|{|}|=|(|,|%op% %varid% [", varid)) { // warning is written for "dealloc ; use_ ;". // but this use doesn't affect the leak-checking addtoken(&rettail, tok, "use_"); @@ -1534,13 +1357,10 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(), ") {")) - { - if (!Token::Match(tok, "if|for|while|switch")) - { + if (Token::simpleMatch(tok->next()->link(), ") {")) { + if (!Token::Match(tok, "if|for|while|switch")) { addtoken(&rettail, tok, "exit"); addtoken(&rettail, tok, ";"); tok = tok->next()->link(); @@ -1549,8 +1369,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list bail out - else if (Token::Match(tok, "setjmp|longjmp")) - { + else if (Token::Match(tok, "setjmp|longjmp")) { while (rethead->next()) rethead->deleteNext(); return rethead; @@ -1559,26 +1378,21 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr()) != noreturn.end()) addtoken(&rettail, tok, "exit"); - else if (!test_white_list(tok->str())) - { + else if (!test_white_list(tok->str())) { int innerParlevel = 1; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++innerParlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { --innerParlevel; if (innerParlevel <= 0) break; } - if (tok2->varId() == varid) - { + if (tok2->varId() == varid) { addtoken(&rettail, tok, "::use"); break; } @@ -1586,10 +1400,8 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0 && Token::Match(tok, "%var% ( close|fclose|pclose ( %varid% ) ) ;", varid)) - { + else { + if (varid > 0 && Token::Match(tok, "%var% ( close|fclose|pclose ( %varid% ) ) ;", varid)) { addtoken(&rettail, tok, "dealloc"); tok = tok->next()->link(); continue; @@ -1597,26 +1409,18 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); - } - else if (varid == 0 || str != std::string("alloc")) - { + } else if (varid == 0 || str != std::string("alloc")) { + addtoken(&rettail, tok, str); + } else if (Token::Match(tok->tokAt(-2), "%varid% =", varid)) { addtoken(&rettail, tok, str); } - else if (Token::Match(tok->tokAt(-2), "%varid% =", varid)) - { - addtoken(&rettail, tok, str); - } - } - else if (varid > 0 && - getReallocationType(tok, varid) != No && - tok->tokAt(2)->varId() == varid) - { + } else if (varid > 0 && + getReallocationType(tok, varid) != No && + tok->tokAt(2)->varId() == varid) { addtoken(&rettail, tok, "if"); addtoken(&rettail, tok, "{"); addtoken(&rettail, tok, "dealloc"); @@ -1629,8 +1433,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listlink(),") (")) - { + if (Token::Match(tok, "( *| %var%") && Token::simpleMatch(tok->link(),") (")) { const Token *tok2 = tok->next(); if (tok2->str() == "*") tok2 = tok2->next(); @@ -1639,14 +1442,11 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(2); - if (Token::simpleMatch(tok2, ") (")) - { - for (; tok2; tok2 = tok2->next()) - { + if (Token::simpleMatch(tok2, ") (")) { + for (; tok2; tok2 = tok2->next()) { if (Token::Match(tok2, "[;{]")) break; - else if (tok2->varId() == varid) - { + else if (tok2->varId() == varid) { addtoken(&rettail, tok, "use"); break; } @@ -1655,16 +1455,13 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0 && Token::Match(tok, "[=(,] & %varid% [.[,)]", varid)) - { + if (varid > 0 && Token::Match(tok, "[=(,] & %varid% [.[,)]", varid)) { addtoken(&rettail, tok, "&use"); } } - for (Token *tok1 = rethead; tok1; tok1 = tok1->next()) - { - if (Token::simpleMatch(tok1, "callfunc alloc ;")) - { + for (Token *tok1 = rethead; tok1; tok1 = tok1->next()) { + if (Token::simpleMatch(tok1, "callfunc alloc ;")) { tok1->deleteThis(); tok1->insertToken("use"); tok1->insertToken(";"); @@ -1685,17 +1482,14 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) // Replace "throw" that is not in a try block with "return" int indentlevel = 0; int trylevel = -1; - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { --indentlevel; if (indentlevel <= trylevel) trylevel = -1; - } - else if (trylevel == -1 && tok2->str() == "try") + } else if (trylevel == -1 && tok2->str() == "try") trylevel = indentlevel; else if (trylevel == -1 && tok2->str() == "throw") tok2->str("return"); @@ -1703,35 +1497,26 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Insert extra ";" - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (!tok2->previous() || Token::Match(tok2->previous(), "[;{}]")) - { - if (Token::Match(tok2, "assign|callfunc|use assign|callfunc|use")) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (!tok2->previous() || Token::Match(tok2->previous(), "[;{}]")) { + if (Token::Match(tok2, "assign|callfunc|use assign|callfunc|use")) { tok2->insertToken(";"); } } } // remove redundant braces.. - for (Token *start = tok; start; start = start->next()) - { - if (Token::simpleMatch(start, "; {")) - { + for (Token *start = tok; start; start = start->next()) { + if (Token::simpleMatch(start, "; {")) { // the "link" doesn't work here. Find the end brace.. unsigned int indent = 0; - for (Token *end = start; end; end = end->next()) - { + for (Token *end = start; end; end = end->next()) { if (end->str() == "{") ++indent; - else if (end->str() == "}") - { - if (indent <= 1) - { + else if (end->str() == "}") { + if (indent <= 1) { // If the start/end braces are redundant, delete them - if (indent == 1 && Token::Match(end->previous(), "[;{}] } %any%")) - { + if (indent == 1 && Token::Match(end->previous(), "[;{}] } %any%")) { start->deleteNext(); end->deleteThis(); } @@ -1747,24 +1532,20 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) // it will be reduced in N passes. When a pass completes without any // simplifications the loop is done. bool done = false; - while (! done) - { + while (! done) { //tok->printOut("simplifycode loop.."); done = true; // reduce callfunc - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "callfunc") - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "callfunc") { if (!Token::Match(tok2->previous(), "[;{}] callfunc ; }")) tok2->deleteThis(); } } // If the code starts with "if return ;" then remove it - if (Token::Match(tok, ";| if return ;")) - { + if (Token::Match(tok, ";| if return ;")) { tok->deleteThis(); tok->deleteThis(); if (tok->str() == "return") @@ -1774,31 +1555,25 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // simplify "while1" contents.. - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (Token::simpleMatch(tok2, "while1 {")) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (Token::simpleMatch(tok2, "while1 {")) { unsigned int innerIndentlevel = 0; - for (Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) - { + for (Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++innerIndentlevel; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (innerIndentlevel == 0) break; --innerIndentlevel; } - while (innerIndentlevel == 0 && Token::Match(tok3, "[{};] if|ifv|else { continue ; }")) - { + while (innerIndentlevel == 0 && Token::Match(tok3, "[{};] if|ifv|else { continue ; }")) { Token::eraseTokens(tok3, tok3->tokAt(6)); if (Token::simpleMatch(tok3->next(), "else")) tok3->deleteNext(); } } - if (Token::simpleMatch(tok2, "while1 { if { dealloc ; return ; } }")) - { + if (Token::simpleMatch(tok2, "while1 { if { dealloc ; return ; } }")) { tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(4)); Token::eraseTokens(tok2->tokAt(4), tok2->tokAt(7)); @@ -1807,129 +1582,110 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Main inner simplification loop - for (Token *tok2 = tok; tok2; tok2 = tok2 ? tok2->next() : NULL) - { + for (Token *tok2 = tok; tok2; tok2 = tok2 ? tok2->next() : NULL) { // Delete extra ";" - while (Token::Match(tok2, "[;{}] ;")) - { + while (Token::Match(tok2, "[;{}] ;")) { tok2->deleteNext(); done = false; } // Replace "{ }" with ";" - if (Token::simpleMatch(tok2->next(), "{ }")) - { + if (Token::simpleMatch(tok2->next(), "{ }")) { tok2->eraseTokens(tok2, tok2->tokAt(3)); tok2->insertToken(";"); done = false; } // Delete braces around a single instruction.. - if (Token::Match(tok2->next(), "{ %var% ; }")) - { + if (Token::Match(tok2->next(), "{ %var% ; }")) { tok2->deleteNext(); Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(4)); done = false; } - if (Token::Match(tok2->next(), "{ %var% %var% ; }")) - { + if (Token::Match(tok2->next(), "{ %var% %var% ; }")) { tok2->deleteNext(); Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(5)); done = false; } // Reduce "if if|callfunc" => "if" - else if (Token::Match(tok2, "if if|callfunc")) - { + else if (Token::Match(tok2, "if if|callfunc")) { tok2->deleteNext(); done = false; } // outer/inner if blocks. Remove outer condition.. - else if (Token::Match(tok2->next(), "if|if(var) { if return use ; }")) - { + else if (Token::Match(tok2->next(), "if|if(var) { if return use ; }")) { tok2->tokAt(6)->deleteNext(); Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } - else if (tok2->next() && tok2->next()->str() == "if") - { + else if (tok2->next() && tok2->next()->str() == "if") { // Delete empty if that is not followed by an else - if (Token::Match(tok2->next(), "if ; !!else")) - { + if (Token::Match(tok2->next(), "if ; !!else")) { tok2->deleteNext(); done = false; } // Reduce "if X ; else X ;" => "X ;" else if (Token::Match(tok2->next(), "if %var% ; else %var% ;") && - std::string(tok2->strAt(2)) == std::string(tok2->strAt(5))) - { + std::string(tok2->strAt(2)) == std::string(tok2->strAt(5))) { Token::eraseTokens(tok2, tok2->tokAt(5)); done = false; } // Reduce "if continue ; if continue ;" => "if continue ;" - else if (Token::simpleMatch(tok2->next(), "if continue ; if continue ;")) - { + else if (Token::simpleMatch(tok2->next(), "if continue ; if continue ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "if return ; alloc ;" => "alloc ;" - else if (Token::Match(tok2, "[;{}] if return ; alloc|return ;")) - { + else if (Token::Match(tok2, "[;{}] if return ; alloc|return ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // "[;{}] if alloc ; else return ;" => "[;{}] alloc ;" - else if (Token::Match(tok2, "[;{}] if alloc ; else return ;")) - { + else if (Token::Match(tok2, "[;{}] if alloc ; else return ;")) { tok2->deleteNext(); // Remove "if" Token::eraseTokens(tok2->next(), tok2->tokAt(5)); // Remove "; else return" done = false; } // Reduce "if ; else %var% ;" => "if %var% ;" - else if (Token::Match(tok2->next(), "if ; else %var% ;")) - { + else if (Token::Match(tok2->next(), "if ; else %var% ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(4)); done = false; } // Reduce "if ; else" => "if" - else if (Token::simpleMatch(tok2->next(), "if ; else")) - { + else if (Token::simpleMatch(tok2->next(), "if ; else")) { Token::eraseTokens(tok2->next(), tok2->tokAt(4)); done = false; } // Reduce "if return ; else|if return|continue ;" => "if return ;" - else if (Token::Match(tok2->next(), "if return ; else|if return|continue|break ;")) - { + else if (Token::Match(tok2->next(), "if return ; else|if return|continue|break ;")) { Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(6)); done = false; } // Reduce "if continue|break ; else|if return ;" => "if return ;" - else if (Token::Match(tok2->next(), "if continue|break ; if|else return ;")) - { + else if (Token::Match(tok2->next(), "if continue|break ; if|else return ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(5)); done = false; } // Remove "else" after "if continue|break|return" - else if (Token::Match(tok2->next(), "if continue|break|return ; else")) - { + else if (Token::Match(tok2->next(), "if continue|break|return ; else")) { tok2->tokAt(4)->deleteThis(); done = false; } // Delete "if { dealloc|assign|use ; return ; }" - else if (Token::Match(tok2, "[;{}] if { dealloc|assign|use ; return ; }")) - { + else if (Token::Match(tok2, "[;{}] if { dealloc|assign|use ; return ; }")) { Token::eraseTokens(tok2, tok2->tokAt(8)); if (Token::simpleMatch(tok2->next(), "else")) tok2->deleteNext(); @@ -1938,8 +1694,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) // Remove "if { dealloc ; callfunc ; } !!else|return" else if (Token::Match(tok2->next(), "if { dealloc|assign ; callfunc ; }") && - !Token::Match(tok2->tokAt(8), "else|return")) - { + !Token::Match(tok2->tokAt(8), "else|return")) { Token::eraseTokens(tok2, tok2->tokAt(8)); done = false; } @@ -1948,30 +1703,26 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Reduce "alloc while(!var) alloc ;" => "alloc ;" - if (Token::Match(tok2, "[;{}] alloc ; while(!var) alloc ;")) - { + if (Token::Match(tok2, "[;{}] alloc ; while(!var) alloc ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "ifv return;" => "if return use;" - if (Token::simpleMatch(tok2, "ifv return ;")) - { + if (Token::simpleMatch(tok2, "ifv return ;")) { tok2->str("if"); tok2->next()->insertToken("use"); done = false; } // Reduce "if(var) dealloc ;" and "if(var) use ;" that is not followed by an else.. - if (Token::Match(tok2, "[;{}] if(var) assign|dealloc|use ; !!else")) - { + if (Token::Match(tok2, "[;{}] if(var) assign|dealloc|use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "; if(!var) alloc ; !!else" => "; dealloc ; alloc ;" - if (Token::Match(tok2, "; if(!var) alloc ; !!else")) - { + if (Token::Match(tok2, "; if(!var) alloc ; !!else")) { // Remove the "if(!var)" Token::eraseTokens(tok2, tok2->tokAt(2)); @@ -1983,18 +1734,15 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Reduce "; if(!var) exit ;" => ";" - if (Token::Match(tok2, "; if(!var) exit ;")) - { + if (Token::Match(tok2, "; if(!var) exit ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Reduce "if* ;".. - if (Token::Match(tok2->next(), "if(var)|if(!var)|ifv ;")) - { + if (Token::Match(tok2->next(), "if(var)|if(!var)|ifv ;")) { // Followed by else.. - if (Token::simpleMatch(tok2->tokAt(3), "else")) - { + if (Token::simpleMatch(tok2->tokAt(3), "else")) { tok2 = tok2->next(); if (tok2->str() == "if(var)") tok2->str("if(!var)"); @@ -2003,9 +1751,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) // remove the "; else" Token::eraseTokens(tok2, tok2->tokAt(3)); - } - else - { + } else { // remove the "if*" Token::eraseTokens(tok2, tok2->tokAt(2)); } @@ -2013,15 +1759,13 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Reduce "else ;" => ";" - if (Token::simpleMatch(tok2->next(), "else ;")) - { + if (Token::simpleMatch(tok2->next(), "else ;")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "while1 continue| ;" => "use ;" - if (Token::Match(tok2, "while1 if| continue| ;")) - { + if (Token::Match(tok2, "while1 if| continue| ;")) { tok2->str("use"); while (tok2->strAt(1) != ";") tok2->deleteNext(); @@ -2029,125 +1773,108 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Reduce "while1 if break ;" => ";" - if (Token::simpleMatch(tok2, "while1 if break ;")) - { + if (Token::simpleMatch(tok2, "while1 if break ;")) { tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Delete if block: "alloc; if return use ;" - if (Token::Match(tok2, "alloc ; if return use ; !!else")) - { + if (Token::Match(tok2, "alloc ; if return use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(5)); done = false; } // Reduce "alloc|dealloc|use|callfunc ; exit ;" => "; exit ;" - if (Token::Match(tok2, "[;{}] alloc|dealloc|use|callfunc ; exit ;")) - { + if (Token::Match(tok2, "[;{}] alloc|dealloc|use|callfunc ; exit ;")) { tok2->deleteNext(); done = false; } // Reduce "alloc|dealloc|use ; if(var) exit ;" - if (Token::Match(tok2, "alloc|dealloc|use ; if(var) exit ;")) - { + if (Token::Match(tok2, "alloc|dealloc|use ; if(var) exit ;")) { tok2->deleteThis(); done = false; } // Remove "if exit ;" - if (Token::simpleMatch(tok2, "if exit ;")) - { + if (Token::simpleMatch(tok2, "if exit ;")) { tok2->deleteThis(); tok2->deleteThis(); done = false; } // Remove the "if break|continue ;" that follows "dealloc ; alloc ;" - if (! _settings->experimental && Token::Match(tok2, "dealloc ; alloc ; if break|continue ;")) - { + if (! _settings->experimental && Token::Match(tok2, "dealloc ; alloc ; if break|continue ;")) { tok2 = tok2->tokAt(3); Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // if break ; break ; => break ; - if (Token::Match(tok2->previous(), "[;{}] if break ; break ;")) - { + if (Token::Match(tok2->previous(), "[;{}] if break ; break ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "do { dealloc ; alloc ; } while(var) ;" => ";" - if (Token::simpleMatch(tok2->next(), "do { dealloc ; alloc ; } while(var) ;")) - { + if (Token::simpleMatch(tok2->next(), "do { dealloc ; alloc ; } while(var) ;")) { Token::eraseTokens(tok2, tok2->tokAt(9)); done = false; } // Reduce "do { alloc ; } " => "alloc ;" /** @todo If the loop "do { alloc ; }" can be executed twice, reduce it to "loop alloc ;" */ - if (Token::simpleMatch(tok2->next(), "do { alloc ; }")) - { + if (Token::simpleMatch(tok2->next(), "do { alloc ; }")) { Token::eraseTokens(tok2, tok2->tokAt(3)); Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(4)); done = false; } // Reduce "loop break ; => ";" - if (Token::Match(tok2->next(), "loop break|continue ;")) - { + if (Token::Match(tok2->next(), "loop break|continue ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Reduce "loop|do ;" => ";" - if (Token::Match(tok2, "loop|do ;")) - { + if (Token::Match(tok2, "loop|do ;")) { tok2->deleteThis(); done = false; } // Reduce "loop if break|continue ; !!else" => ";" - if (Token::Match(tok2->next(), "loop if break|continue ; !!else")) - { + if (Token::Match(tok2->next(), "loop if break|continue ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "loop { if break|continue ; !!else" => "loop {" - if (Token::Match(tok2, "loop { if break|continue ; !!else")) - { + if (Token::Match(tok2, "loop { if break|continue ; !!else")) { Token::eraseTokens(tok2->next(), tok2->tokAt(5)); done = false; } // Replace "do ; loop ;" with ";" - if (Token::simpleMatch(tok2, "; loop ;")) - { + if (Token::simpleMatch(tok2, "; loop ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Replace "loop loop .." with "loop .." - if (Token::simpleMatch(tok2, "loop loop")) - { + if (Token::simpleMatch(tok2, "loop loop")) { tok2->deleteThis(); done = false; } // Replace "loop if return ;" with "if return ;" - if (Token::simpleMatch(tok2->next(), "loop if return")) - { + if (Token::simpleMatch(tok2->next(), "loop if return")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "loop|while1 { dealloc ; alloc ; }" - if (Token::Match(tok2, "loop|while1 { dealloc ; alloc ; }")) - { + if (Token::Match(tok2, "loop|while1 { dealloc ; alloc ; }")) { // delete "loop|while1" tok2->deleteThis(); // delete "{" @@ -2161,8 +1888,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) // loop { use ; callfunc ; } => use ; // assume that the "callfunc" is not noreturn - if (Token::simpleMatch(tok2, "loop { use ; callfunc ; }")) - { + if (Token::simpleMatch(tok2, "loop { use ; callfunc ; }")) { Token::eraseTokens(tok2, tok2->tokAt(7)); tok2->str("use"); tok2->insertToken(";"); @@ -2170,51 +1896,44 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Delete if block in "alloc ; if(!var) return ;" - if (Token::Match(tok2, "alloc ; if(!var) return ;")) - { + if (Token::Match(tok2, "alloc ; if(!var) return ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "[;{}] return use ; %var%" => "[;{}] return use ;" - if (Token::Match(tok2, "[;{}] return use ; %var%")) - { + if (Token::Match(tok2, "[;{}] return use ; %var%")) { Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(5)); done = false; } // Reduce "if(var) return use ;" => "return use ;" - if (Token::Match(tok2->next(), "if(var) return use ; !!else")) - { + if (Token::Match(tok2->next(), "if(var) return use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // malloc - realloc => alloc ; dealloc ; alloc ; // Reduce "[;{}] alloc ; dealloc ; alloc ;" => "[;{}] alloc ;" - if (Token::Match(tok2, "[;{}] alloc ; dealloc ; alloc ;")) - { + if (Token::Match(tok2, "[;{}] alloc ; dealloc ; alloc ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(6)); done = false; } // use; dealloc; => dealloc; - if (Token::Match(tok2, "[;{}] use ; dealloc ;")) - { + if (Token::Match(tok2, "[;{}] use ; dealloc ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // use use => use - if (Token::simpleMatch(tok2, "use use")) - { + if (Token::simpleMatch(tok2, "use use")) { tok2->deleteThis(); done = false; } // use; if| use; => use; - while (Token::Match(tok2, "[;{}] use ; if| use ;")) - { + while (Token::Match(tok2, "[;{}] use ; if| use ;")) { Token *t = tok2->tokAt(2); t->deleteNext(); t->deleteNext(); @@ -2224,40 +1943,34 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // Delete first part in "use ; return use ;" - if (Token::Match(tok2, "[;{}] use ; return use ;")) - { + if (Token::Match(tok2, "[;{}] use ; return use ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // try/catch - if (Token::simpleMatch(tok2, "try ; catch exit ;")) - { + if (Token::simpleMatch(tok2, "try ; catch exit ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); tok2->deleteThis(); done = false; } // Delete second case in "case ; case ;" - while (Token::simpleMatch(tok2, "case ; case ;")) - { + while (Token::simpleMatch(tok2, "case ; case ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Replace switch with if (if not complicated) - if (Token::simpleMatch(tok2, "switch {")) - { + if (Token::simpleMatch(tok2, "switch {")) { // Right now, I just handle if there are a few case and perhaps a default. bool valid = false; bool incase = false; - for (const Token * _tok = tok2->tokAt(2); _tok; _tok = _tok->next()) - { + for (const Token * _tok = tok2->tokAt(2); _tok; _tok = _tok->next()) { if (_tok->str() == "{") break; - else if (_tok->str() == "}") - { + else if (_tok->str() == "}") { valid = true; break; } @@ -2281,24 +1994,19 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) incase &= (_tok->str() != "break" && _tok->str() != "return"); } - if (!incase && valid) - { + if (!incase && valid) { done = false; tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(2)); tok2 = tok2->next(); bool first = true; - while (Token::Match(tok2, "case|default")) - { + while (Token::Match(tok2, "case|default")) { const bool def(tok2->str() == "default"); tok2->str(first ? "if" : "}"); - if (first) - { + if (first) { first = false; tok2->insertToken("{"); - } - else - { + } else { // Insert "else [if] { tok2->insertToken("{"); if (! def) @@ -2306,8 +2014,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) tok2->insertToken("else"); tok2 = tok2->next(); } - while (tok2) - { + while (tok2) { if (tok2->str() == "}") break; if (Token::Match(tok2, "break|return ;")) @@ -2317,13 +2024,10 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) else tok2 = tok2->next(); } - if (Token::simpleMatch(tok2, "break ;")) - { + if (Token::simpleMatch(tok2, "break ;")) { tok2->str(";"); tok2 = tok2->tokAt(2); - } - else if (tok2 && tok2->str() == "return") - { + } else if (tok2 && tok2->str() == "return") { tok2 = tok2->tokAt(2); } } @@ -2332,12 +2036,9 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) } // If "--all" is given, remove all "callfunc".. - if (done && _settings->experimental) - { - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "callfunc") - { + if (done && _settings->experimental) { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "callfunc") { tok2->deleteThis(); done = false; } @@ -2354,46 +2055,38 @@ const Token *CheckMemoryLeakInFunction::findleak(const Token *tokens) { const Token *result; - if ((result = Token::findmatch(tokens, "loop alloc ;")) != NULL) - { + if ((result = Token::findmatch(tokens, "loop alloc ;")) != NULL) { return result; } - if (Token::Match(tokens, "alloc ; if|if(var)|ifv break|continue|return ;")) - { + if (Token::Match(tokens, "alloc ; if|if(var)|ifv break|continue|return ;")) { return tokens->tokAt(3); } - if ((result = Token::findmatch(tokens, "alloc ; if|if(var)|ifv return ;")) != NULL) - { + if ((result = Token::findmatch(tokens, "alloc ; if|if(var)|ifv return ;")) != NULL) { return result->tokAt(3); } - if ((result = Token::findmatch(tokens, "alloc ; alloc|assign|return callfunc| ;")) != NULL) - { + if ((result = Token::findmatch(tokens, "alloc ; alloc|assign|return callfunc| ;")) != NULL) { return result->tokAt(2); } - if ((result = Token::findmatch(tokens, "; alloc ; if assign ;")) != NULL) - { + if ((result = Token::findmatch(tokens, "; alloc ; if assign ;")) != NULL) { return result->tokAt(4); } if (((result = Token::findmatch(tokens, "; alloc ; if dealloc ; }")) != NULL) && - !result->tokAt(7)) - { + !result->tokAt(7)) { return result->tokAt(6); } - if ((result = Token::findmatch(tokens, "alloc ; }")) != NULL) - { + if ((result = Token::findmatch(tokens, "alloc ; }")) != NULL) { if (result->tokAt(3) == NULL) return result->tokAt(2); } // No deallocation / usage => report leak at the last token - if (!Token::findmatch(tokens, "dealloc|use")) - { + if (!Token::findmatch(tokens, "dealloc|use")) { const Token *last = tokens; while (last->next()) last = last->next(); @@ -2425,19 +2118,16 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string //tok->printOut((std::string("Checkmemoryleak: getcode result for: ") + varname).c_str()); // Simplify the code and check if freed memory is used.. - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { while (Token::Match(tok2, "[;{}] ;")) Token::eraseTokens(tok2, tok2->tokAt(2)); } - if ((result = Token::findmatch(tok, "[;{}] dealloc ; use_ ;")) != NULL) - { + if ((result = Token::findmatch(tok, "[;{}] dealloc ; use_ ;")) != NULL) { deallocuseError(result->tokAt(3), varname); } // Replace "&use" with "use". Replace "use_" with ";" - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "&use") tok2->str("use"); else if (tok2->str() == "use_") @@ -2450,8 +2140,7 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string tok2->str("use"); else if (tok2->str() == "dealloc_") tok2->str("dealloc"); - else if (tok2->str() == "realloc") - { + else if (tok2->str() == "realloc") { tok2->str("dealloc"); tok2->insertToken("alloc"); tok2->insertToken(";"); @@ -2459,46 +2148,39 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string } // If the variable is not allocated at all => no memory leak - if (Token::findmatch(tok, "alloc") == 0) - { + if (Token::findmatch(tok, "alloc") == 0) { Tokenizer::deleteTokens(tok); return; } simplifycode(tok); - if (_settings->debug && _settings->_verbose) - { + if (_settings->debug && _settings->_verbose) { tok->printOut(("Checkmemoryleak: simplifycode result for: " + varname).c_str()); } // If the variable is not allocated at all => no memory leak - if (Token::findmatch(tok, "alloc") == 0) - { + if (Token::findmatch(tok, "alloc") == 0) { Tokenizer::deleteTokens(tok); return; } /** @todo handle "goto" */ - if (Token::findmatch(tok, "goto")) - { + if (Token::findmatch(tok, "goto")) { Tokenizer::deleteTokens(tok); return; } - if ((result = findleak(tok)) != NULL) - { + if ((result = findleak(tok)) != NULL) { memoryLeak(result, varname, alloctype); } - else if ((result = Token::findmatch(tok, "dealloc ; dealloc ;")) != NULL) - { + else if ((result = Token::findmatch(tok, "dealloc ; dealloc ;")) != NULL) { deallocDeallocError(result->tokAt(2), varname); } // detect cases that "simplifycode" don't handle well.. - else if (_settings->debugwarnings) - { + else if (_settings->debugwarnings) { Token *first = tok; while (first && first->str() == ";") first = first->next(); @@ -2517,8 +2199,7 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string noerr |= Token::simpleMatch(first, "alloc ; if return ; dealloc; }"); // Unhandled case.. - if (! noerr) - { + if (! noerr) { std::ostringstream errmsg; errmsg << "inconclusive leak of " << varname << ": "; for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) @@ -2545,16 +2226,14 @@ void CheckMemoryLeakInFunction::checkReallocUsage() { std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // Record the varid's of the function parameters std::set parameterVarIds; - for (const Token *tok2 = scope->classDef->next(); tok2 && tok2->str() != ")"; tok2 = tok2->next()) - { + for (const Token *tok2 = scope->classDef->next(); tok2 && tok2->str() != ")"; tok2 = tok2->next()) { if (tok2->varId() != 0) parameterVarIds.insert(tok2->varId()); } @@ -2564,12 +2243,10 @@ void CheckMemoryLeakInFunction::checkReallocUsage() // Search for the "var = realloc(var, 100" pattern within this function unsigned int indentlevel = 1; - for (tok = tok->next(); tok; tok = tok->next()) - { + for (tok = tok->next(); tok; tok = tok->next()) { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { --indentlevel; if (indentlevel == 0) break; @@ -2578,8 +2255,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage() if (tok->varId() > 0 && Token::Match(tok, "%var% = realloc|g_try_realloc ( %var% , %any%") && tok->varId() == tok->tokAt(4)->varId() && - parameterVarIds.find(tok->varId()) == parameterVarIds.end()) - { + parameterVarIds.find(tok->varId()) == parameterVarIds.end()) { // Check that another copy of the pointer wasn't saved earlier in the function if (Token::findmatch(startOfFunction, "%var% = %varid% ;", tok->varId()) || Token::findmatch(startOfFunction, "[{};] %varid% = %var% [;=]", tok->varId())) @@ -2587,8 +2263,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage() const Token* tokEndRealloc = tok->tokAt(3)->link(); // Check that the allocation isn't followed immediately by an 'if (!var) { error(); }' that might handle failure - if (Token::Match(tokEndRealloc->tokAt(1), "; if ( ! %varid% ) {", tok->varId())) - { + if (Token::Match(tokEndRealloc->tokAt(1), "; if ( ! %varid% ) {", tok->varId())) { const Token* tokEndBrace = tokEndRealloc->tokAt(7)->link(); if (tokEndBrace && Token::simpleMatch(tokEndBrace->tokAt(-2), ") ;") && Token::Match(tokEndBrace->tokAt(-2)->link()->tokAt(-2), "{|}|; %var% (")) @@ -2596,12 +2271,10 @@ void CheckMemoryLeakInFunction::checkReallocUsage() } memleakUponReallocFailureError(tok, tok->str()); - } - else if (tok->tokAt(1)->varId() > 0 && - (Token::Match(tok, "* %var% = realloc|g_try_realloc ( * %var% , %any%") && - tok->tokAt(1)->varId() == tok->tokAt(6)->varId())&& - parameterVarIds.find(tok->tokAt(1)->varId()) == parameterVarIds.end()) - { + } else if (tok->tokAt(1)->varId() > 0 && + (Token::Match(tok, "* %var% = realloc|g_try_realloc ( * %var% , %any%") && + tok->tokAt(1)->varId() == tok->tokAt(6)->varId())&& + parameterVarIds.find(tok->tokAt(1)->varId()) == parameterVarIds.end()) { // Check that another copy of the pointer wasn't saved earlier in the function if (Token::findmatch(startOfFunction, "%var% = * %varid% ;", tok->tokAt(1)->varId()) || Token::findmatch(startOfFunction, "[{};] * %varid% = %var% [;=]", tok->tokAt(1)->varId())) @@ -2609,8 +2282,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage() const Token* tokEndRealloc = tok->tokAt(4)->link(); // Check that the allocation isn't followed immediately by an 'if (!var) { error(); }' that might handle failure - if (Token::Match(tokEndRealloc->tokAt(1), "; if ( ! * %varid% ) {", tok->tokAt(1)->varId())) - { + if (Token::Match(tokEndRealloc->tokAt(1), "; if ( ! * %varid% ) {", tok->tokAt(1)->varId())) { const Token* tokEndBrace = tokEndRealloc->tokAt(8)->link(); if (tokEndBrace && Token::simpleMatch(tokEndBrace->tokAt(-2), ") ;") && Token::Match(tokEndBrace->tokAt(-2)->link()->tokAt(-2), "{|}|; %var% (")) @@ -2638,14 +2310,12 @@ void CheckMemoryLeakInFunction::parseFunctionScope(const Token *tok, const Token checkScope(tok->next(), "", 0, classmember, 1); // Locate parameters and check their usage.. - for (const Token *tok2 = tok1; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok1; tok2; tok2 = tok2->next()) { if (tok2 == tok) break; if (tok2->str() == ")") break; - if (Token::Match(tok2, "[(,] %type% * %var% [,)]") && tok2->next()->isStandardType()) - { + if (Token::Match(tok2, "[(,] %type% * %var% [,)]") && tok2->next()->isStandardType()) { const std::string varname(tok2->strAt(3)); const unsigned int varid = tok2->tokAt(3)->varId(); const unsigned int sz = _tokenizer->sizeOfType(tok2->next()); @@ -2655,20 +2325,17 @@ void CheckMemoryLeakInFunction::parseFunctionScope(const Token *tok, const Token // Locate variable declarations and check their usage.. unsigned int indentlevel = 0; - do - { + do { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } // Skip these weird blocks... "( { ... } )" - if (Token::simpleMatch(tok, "( {")) - { + if (Token::simpleMatch(tok, "( {")) { tok = tok->link(); if (!tok) break; @@ -2690,25 +2357,21 @@ void CheckMemoryLeakInFunction::parseFunctionScope(const Token *tok, const Token if (sz < 1) sz = 1; - if (Token::Match(tok, "[{};] %type% * const| %var% [;=]")) - { + if (Token::Match(tok, "[{};] %type% * const| %var% [;=]")) { const Token *vartok = tok->tokAt(tok->tokAt(3)->str() != "const" ? 3 : 4); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } - else if (Token::Match(tok, "[{};] %type% %type% * const| %var% [;=]")) - { + else if (Token::Match(tok, "[{};] %type% %type% * const| %var% [;=]")) { const Token *vartok = tok->tokAt(tok->tokAt(4)->str() != "const" ? 4 : 5); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } - else if (Token::Match(tok, "[{};] int %var% [;=]")) - { + else if (Token::Match(tok, "[{};] int %var% [;=]")) { const Token *vartok = tok->tokAt(2); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } - } - while (0 != (tok = tok->next())); + } while (0 != (tok = tok->next())); } void CheckMemoryLeakInFunction::check() @@ -2718,8 +2381,7 @@ void CheckMemoryLeakInFunction::check() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -2773,19 +2435,14 @@ void CheckMemoryLeakInClass::check() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check classes and structures - if (scope->isClassOrStruct()) - { + if (scope->isClassOrStruct()) { std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { - if (!var->isStatic() && var->nameToken()->previous()->str() == "*") - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { + if (!var->isStatic() && var->nameToken()->previous()->str() == "*") { // allocation but no deallocation of private variables in public function.. - if (var->nameToken()->tokAt(-2)->isStandardType()) - { + if (var->nameToken()->tokAt(-2)->isStandardType()) { if (var->isPrivate()) checkPublicFunctions(&(*scope), var->nameToken()); @@ -2793,11 +2450,9 @@ void CheckMemoryLeakInClass::check() } // known class? - else if (var->type()) - { + else if (var->type()) { // not derived? - if (var->type()->derivedFrom.empty()) - { + if (var->type()->derivedFrom.empty()) { if (var->isPrivate()) checkPublicFunctions(&(*scope), var->nameToken()); @@ -2825,36 +2480,29 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam // Inspect member functions std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { const Token *functionToken = func->token; const bool constructor = func->type == Function::eConstructor; const bool destructor = func->type == Function::eDestructor; unsigned int indent = 0; bool initlist = false; - for (const Token *tok = functionToken; tok; tok = tok->next()) - { + for (const Token *tok = functionToken; tok; tok = tok->next()) { if (tok->str() == "{") ++indent; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indent <= 1) break; --indent; - } - else if (indent == 0 && Token::simpleMatch(tok, ") :")) + } else if (indent == 0 && Token::simpleMatch(tok, ") :")) initlist = true; - else if (initlist || indent > 0) - { - if (indent == 0) - { + else if (initlist || indent > 0) { + if (indent == 0) { if (!Token::Match(tok, (":|, " + varname + " (").c_str())) continue; } // Allocate.. - if (indent == 0 || Token::Match(tok, (varname + " =").c_str())) - { + if (indent == 0 || Token::Match(tok, (varname + " =").c_str())) { // var1 = var2 = ... // bail out if (Token::simpleMatch(tok->previous(), "=")) @@ -2867,8 +2515,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam return; AllocType alloc = getAllocationType(tok->tokAt((indent > 0) ? 2 : 3), 0); - if (alloc != CheckMemoryLeak::No) - { + if (alloc != CheckMemoryLeak::No) { if (constructor) allocInConstructor = true; @@ -2876,8 +2523,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam alloc = CheckMemoryLeak::Many; std::list callstack; - if (alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) - { + if (alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, classname + "::" + varname); callstack.pop_back(); @@ -2892,18 +2538,15 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam // Deallocate.. AllocType dealloc = getDeallocationType(tok, varname); - if (dealloc == No) - { + if (dealloc == No) { std::string temp = scope->className + " :: " + varname; dealloc = getDeallocationType(tok, temp); } - if (dealloc == No) - { + if (dealloc == No) { std::string temp = "this . " + varname; dealloc = getDeallocationType(tok, temp); } - if (dealloc != CheckMemoryLeak::No) - { + if (dealloc != CheckMemoryLeak::No) { if (destructor) deallocInDestructor = true; @@ -2912,8 +2555,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam dealloc = CheckMemoryLeak::Many; std::list callstack; - if (dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) - { + if (dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, classname + "::" + varname); callstack.pop_back(); @@ -2923,10 +2565,8 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam } // Function call .. possible deallocation - else if (Token::Match(tok->previous(), "[{};] %var% (")) - { - if (!CheckMemoryLeakInFunction::test_white_list(tok->str().c_str())) - { + else if (Token::Match(tok->previous(), "[{};] %var% (")) { + if (!CheckMemoryLeakInFunction::test_white_list(tok->str().c_str())) { return; } } @@ -2934,12 +2574,9 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam } } - if (allocInConstructor && !deallocInDestructor) - { + if (allocInConstructor && !deallocInDestructor) { memoryLeak(tokVarname, (classname + "::" + varname).c_str(), Alloc); - } - else if (Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) - { + } else if (Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) { memoryLeak(tokVarname, (classname + "::" + varname).c_str(), Alloc); } } @@ -2959,23 +2596,18 @@ void CheckMemoryLeakInClass::checkPublicFunctions(const Scope *scope, const Toke // If they allocate member variables, they should also deallocate std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { if (func->type != Function::eConstructor && - func->access == Public && func->hasBody) - { + func->access == Public && func->hasBody) { const Token *tok2 = func->token; while (tok2->str() != "{") tok2 = tok2->next(); - if (Token::Match(tok2, "{|}|; %varid% =", varid)) - { + if (Token::Match(tok2, "{|}|; %varid% =", varid)) { const CheckMemoryLeak::AllocType alloc = getAllocationType(tok2->tokAt(3), varid); if (alloc != CheckMemoryLeak::No) publicAllocationError(tok2, tok2->strAt(1)); - } - else if (Token::Match(tok2, "{|}|; %type% :: %varid% =", varid) && - tok2->next()->str() == scope->className) - { + } else if (Token::Match(tok2, "{|}|; %type% :: %varid% =", varid) && + tok2->next()->str() == scope->className) { const CheckMemoryLeak::AllocType alloc = getAllocationType(tok2->tokAt(5), varid); if (alloc != CheckMemoryLeak::No) publicAllocationError(tok2, tok2->strAt(3)); @@ -2993,8 +2625,7 @@ void CheckMemoryLeakInClass::publicAllocationError(const Token *tok, const std:: void CheckMemoryLeakStructMember::check() { unsigned int indentlevel1 = 0; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() == "{") ++indentlevel1; else if (tok->str() == "}") @@ -3004,12 +2635,9 @@ void CheckMemoryLeakStructMember::check() continue; // check struct variables.. - if (Token::Match(tok, "struct|;|{|} %type% * %var% [=;]")) - { + if (Token::Match(tok, "struct|;|{|} %type% * %var% [=;]")) { checkStructVariable(tok->tokAt(3)); - } - else if (Token::Match(tok, "struct|;|{|} %type% %var% ;")) - { + } else if (Token::Match(tok, "struct|;|{|} %type% %var% ;")) { checkStructVariable(tok->tokAt(2)); } } @@ -3020,22 +2648,16 @@ bool CheckMemoryLeakStructMember::isMalloc(const Token *vartok) const unsigned int varid(vartok->varId()); bool alloc = false; unsigned int indentlevel2 = 0; - for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel2; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel2 == 0) break; --indentlevel2; - } - else if (Token::Match(tok2, "= %varid% [;=]", varid)) - { + } else if (Token::Match(tok2, "= %varid% [;=]", varid)) { return false; - } - else if (Token::Match(tok2, "%varid% = malloc|kmalloc (", varid)) - { + } else if (Token::Match(tok2, "%varid% = malloc|kmalloc (", varid)) { alloc = true; } } @@ -3056,14 +2678,11 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok return; // Is struct variable a pointer? - if (vartok->strAt(-1) == "*") - { + if (vartok->strAt(-1) == "*") { // Check that variable is allocated with malloc if (!isMalloc(vartok)) return; - } - else - { + } else { // If file extension is not .c then a destructor might cleanup // members const std::string &fname = _tokenizer->getFiles()->at(0); @@ -3073,13 +2692,11 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok // Check struct.. unsigned int indentlevel2 = 0; - for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel2; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel2 == 0) break; --indentlevel2; @@ -3091,22 +2708,18 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok break; // Struct member is allocated => check if it is also properly deallocated.. - else if (Token::Match(tok2->previous(), "[;{}] %varid% . %var% = malloc|strdup|kmalloc (", vartok->varId())) - { + else if (Token::Match(tok2->previous(), "[;{}] %varid% . %var% = malloc|strdup|kmalloc (", vartok->varId())) { const unsigned int structid(vartok->varId()); const unsigned int structmemberid(tok2->tokAt(2)->varId()); // This struct member is allocated.. check that it is deallocated unsigned int indentlevel3 = indentlevel2; - for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel3; - else if (tok3->str() == "}") - { - if (indentlevel3 == 0) - { + else if (tok3->str() == "}") { + if (indentlevel3 == 0) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc); break; } @@ -3114,8 +2727,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok } // Deallocating the struct member.. - else if (Token::Match(tok3, "free|kfree ( %var% . %varid% )", structmemberid)) - { + else if (Token::Match(tok3, "free|kfree ( %var% . %varid% )", structmemberid)) { // If the deallocation happens at the base level, don't check this member anymore if (indentlevel3 == 0) break; @@ -3123,8 +2735,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok // deallocating and then returning from function in a conditional block => // skip ahead out of the block bool ret = false; - while (tok3) - { + while (tok3) { // debug info const std::string tok3str_(tok3->str()); if (tok3->str() == "return") @@ -3140,15 +2751,13 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok } // Deallocating the struct.. - else if (indentlevel2 == 0 && Token::Match(tok3, "free|kfree ( %varid% )", structid)) - { + else if (indentlevel2 == 0 && Token::Match(tok3, "free|kfree ( %varid% )", structid)) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc); break; } // failed allocation => skip code.. - else if (Token::Match(tok3, "if ( ! %var% . %varid% )", structmemberid)) - { + else if (Token::Match(tok3, "if ( ! %var% . %varid% )", structmemberid)) { // Goto the ")" tok3 = tok3->next()->link(); @@ -3161,25 +2770,20 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok } // succeeded allocation - else if (Token::Match(tok3, "if ( %var% . %varid% ) {", structmemberid)) - { + else if (Token::Match(tok3, "if ( %var% . %varid% ) {", structmemberid)) { // goto the ")" tok3 = tok3->next()->link(); // check if the variable is deallocated or returned.. unsigned int indentlevel4 = 0; - for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) - { + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { if (tok4->str() == "{") ++indentlevel4; - else if (tok4->str() == "}") - { + else if (tok4->str() == "}") { --indentlevel4; if (indentlevel4 == 0) break; - } - else if (Token::Match(tok4, "free|kfree ( %var% . %varid% )", structmemberid)) - { + } else if (Token::Match(tok4, "free|kfree ( %var% . %varid% )", structmemberid)) { break; } } @@ -3190,20 +2794,17 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok } // Returning from function.. - else if (tok3->str() == "return") - { + else if (tok3->str() == "return") { // Returning from function without deallocating struct member? if (!Token::Match(tok3, "return %varid% ;", structid) && - !Token::Match(tok3, "return & %varid% .", structid)) - { + !Token::Match(tok3, "return & %varid% .", structid)) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc); } break; } // struct assignment.. - else if (Token::Match(tok3, "= %varid% ;", structid)) - { + else if (Token::Match(tok3, "= %varid% ;", structid)) { break; } @@ -3212,8 +2813,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok break; // using struct in a function call.. - else if (Token::Match(tok3, "%var% (")) - { + else if (Token::Match(tok3, "%var% (")) { // Calling non-function / function that doesn't deallocate? if (ignoredFunctions.find(tok3->str()) != ignoredFunctions.end()) continue; @@ -3221,27 +2821,23 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Token * const vartok // Check if the struct is used.. bool deallocated = false; unsigned int parlevel = 0; - for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) - { + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { if (tok4->str() == "(") ++parlevel; - else if (tok4->str() == ")") - { + else if (tok4->str() == ")") { if (parlevel <= 1) break; --parlevel; } - if (Token::Match(tok4, "[(,] &| %varid% [,)]", structid)) - { + if (Token::Match(tok4, "[(,] &| %varid% [,)]", structid)) { /** @todo check if the function deallocates the memory */ deallocated = true; break; } - if (Token::Match(tok4, "[(,] &| %varid% . %var% [,)]", structid)) - { + if (Token::Match(tok4, "[(,] &| %varid% . %var% [,)]", structid)) { /** @todo check if the function deallocates the memory */ deallocated = true; break; @@ -3272,8 +2868,7 @@ void CheckMemoryLeakNoVar::check() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -3282,42 +2877,33 @@ void CheckMemoryLeakNoVar::check() const Token *tok = scope->classEnd; // parse the executable scope until tok is reached... - for (const Token *tok2 = tok->link(); tok2 && tok2 != tok; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->link(); tok2 && tok2 != tok; tok2 = tok2->next()) { // allocating memory in parameter for function call.. - if (Token::Match(tok2, "[(,] %var% (") && Token::Match(tok2->tokAt(2)->link(), ") [,)]")) - { + if (Token::Match(tok2, "[(,] %var% (") && Token::Match(tok2->tokAt(2)->link(), ") [,)]")) { const AllocType allocType = getAllocationType(tok2->next(), 0); - if (allocType != No) - { + if (allocType != No) { // locate outer function call.. - for (const Token *tok3 = tok2; tok3; tok3 = tok3->previous()) - { - if (tok3->str() == "(") - { + for (const Token *tok3 = tok2; tok3; tok3 = tok3->previous()) { + if (tok3->str() == "(") { // Is it a function call.. - if (Token::Match(tok3->tokAt(-2), "[(,;{}] %var% (")) - { + if (Token::Match(tok3->tokAt(-2), "[(,;{}] %var% (")) { const std::string functionName = tok3->strAt(-1); if (functionName == "delete" || functionName == "free" || functionName == "fclose" || functionName == "realloc") break; - if (CheckMemoryLeakInFunction::test_white_list(functionName)) - { + if (CheckMemoryLeakInFunction::test_white_list(functionName)) { functionCallLeak(tok2, tok2->strAt(1), functionName); break; } - if (uvarFunctions.find(functionName) != uvarFunctions.end()) - { + if (uvarFunctions.find(functionName) != uvarFunctions.end()) { functionCallLeak(tok2, tok2->strAt(1), functionName); break; } } break; - } - else if (tok3->str() == ")") + } else if (tok3->str() == ")") tok3 = tok3->link(); else if (Token::Match(tok3, "[;{}]")) break; diff --git a/lib/checkmemoryleak.h b/lib/checkmemoryleak.h index 6ab4cb925..69f666454 100644 --- a/lib/checkmemoryleak.h +++ b/lib/checkmemoryleak.h @@ -47,8 +47,7 @@ class Token; /// @{ /** @brief Base class for memory leaks checking */ -class CheckMemoryLeak -{ +class CheckMemoryLeak { private: /** For access to the tokens */ const Tokenizer * const tokenizer; @@ -85,8 +84,7 @@ private: public: CheckMemoryLeak(const Tokenizer *t, ErrorLogger *e) - : tokenizer(t), errorLogger(e) - { + : tokenizer(t), errorLogger(e) { } @@ -180,8 +178,7 @@ public: * -# finally, check if the simplified token list contain any leaks. */ -class CheckMemoryLeakInFunction : private Check, public CheckMemoryLeak -{ +class CheckMemoryLeakInFunction : private Check, public CheckMemoryLeak { public: /** @brief This constructor is used when registering this class */ CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(0, 0), symbolDatabase(NULL) @@ -189,8 +186,7 @@ public: /** @brief This constructor is used when running checks */ CheckMemoryLeakInFunction(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) - : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog) - { + : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog) { // get the symbol database if (tokenizr) symbolDatabase = tokenizr->getSymbolDatabase(); @@ -199,12 +195,10 @@ public: } /** @brief run all simplified checks */ - void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) - { + void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) { // Don't use these check for Java and C# programs.. if (tokenizr->getFiles()->at(0).find(".java") != std::string::npos || - tokenizr->getFiles()->at(0).find(".cs") != std::string::npos) - { + tokenizr->getFiles()->at(0).find(".cs") != std::string::npos) { return; } @@ -315,8 +309,7 @@ public: void checkScope(const Token *Tok1, const std::string &varname, unsigned int varid, bool classmember, unsigned int sz); /** Report all possible errors (for the --errorlist) */ - void getErrorMessages(ErrorLogger *e, const Settings *settings) - { + void getErrorMessages(ErrorLogger *e, const Settings *settings) { CheckMemoryLeakInFunction c(0, settings, e); c.memleakError(0, "varname"); @@ -334,8 +327,7 @@ public: * Get name of class (--doc) * @return name of class */ - std::string myName() const - { + std::string myName() const { return "Memory leaks (function variables)"; } @@ -343,8 +335,7 @@ public: * Get class information (--doc) * @return Wiki formatted information about this class */ - std::string classInfo() const - { + std::string classInfo() const { return "Is there any allocated memory when a function goes out of scope"; } @@ -366,8 +357,7 @@ public: * @brief %Check class variables, variables that are allocated in the constructor should be deallocated in the destructor */ -class CheckMemoryLeakInClass : private Check, private CheckMemoryLeak -{ +class CheckMemoryLeakInClass : private Check, private CheckMemoryLeak { public: CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(0, 0) { } @@ -376,12 +366,10 @@ public: : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog) { } - void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) - { + void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) { // Don't use these check for Java and C# programs.. if (tokenizr->getFiles()->at(0).find(".java") != std::string::npos || - tokenizr->getFiles()->at(0).find(".cs") != std::string::npos) - { + tokenizr->getFiles()->at(0).find(".cs") != std::string::npos) { return; } @@ -401,13 +389,11 @@ private: void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) { } - std::string myName() const - { + std::string myName() const { return "Memory leaks (class variables)"; } - std::string classInfo() const - { + std::string classInfo() const { return "If the constructor allocate memory then the destructor must deallocate it."; } }; @@ -416,8 +402,7 @@ private: /** @brief detect simple memory leaks for struct members */ -class CheckMemoryLeakStructMember : private Check, private CheckMemoryLeak -{ +class CheckMemoryLeakStructMember : private Check, private CheckMemoryLeak { public: CheckMemoryLeakStructMember() : Check(myName()), CheckMemoryLeak(0, 0) { } @@ -426,8 +411,7 @@ public: : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog) { } - void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) - { + void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) { CheckMemoryLeakStructMember checkMemoryLeak(tokenizr, settings, errLog); checkMemoryLeak.check(); } @@ -444,13 +428,11 @@ private: void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) { } - std::string myName() const - { + std::string myName() const { return "Memory leaks (struct members)"; } - std::string classInfo() const - { + std::string classInfo() const { return "Don't forget to deallocate struct members"; } }; @@ -459,8 +441,7 @@ private: /** @brief detect simple memory leaks (address not taken) */ -class CheckMemoryLeakNoVar : private Check, private CheckMemoryLeak -{ +class CheckMemoryLeakNoVar : private Check, private CheckMemoryLeak { public: CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(0, 0) { } @@ -469,8 +450,7 @@ public: : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog) { } - void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) - { + void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) { CheckMemoryLeakNoVar checkMemoryLeak(tokenizr, settings, errLog); checkMemoryLeak.check(); } @@ -484,13 +464,11 @@ private: void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) { } - std::string myName() const - { + std::string myName() const { return "Memory leaks (address not taken)"; } - std::string classInfo() const - { + std::string classInfo() const { return "Not taking the address to allocated memory"; } }; diff --git a/lib/checknonreentrantfunctions.cpp b/lib/checknonreentrantfunctions.cpp index dc328e3b6..84171dfc6 100644 --- a/lib/checknonreentrantfunctions.cpp +++ b/lib/checknonreentrantfunctions.cpp @@ -26,9 +26,8 @@ // Register this check class (by creating a static instance of it) -namespace -{ -CheckNonReentrantFunctions instance; +namespace { + CheckNonReentrantFunctions instance; } void CheckNonReentrantFunctions::nonReentrantFunctions() @@ -40,13 +39,10 @@ void CheckNonReentrantFunctions::nonReentrantFunctions() if (_tokenizer->isJavaOrCSharp()) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { std::list< std::pair >::const_iterator it(_nonReentrantFunctions.begin()), itend(_nonReentrantFunctions.end()); - for (; it!=itend; ++it) - { - if (tok->strAt(1) == it->first && tok->strAt(2) == "(" && tok->tokAt(1)->varId() == 0 && !tok->tokAt(0)->isName() && !Token::Match(tok, ".|::|:|,")) - { + for (; it!=itend; ++it) { + if (tok->strAt(1) == it->first && tok->strAt(2) == "(" && tok->tokAt(1)->varId() == 0 && !tok->tokAt(0)->isName() && !Token::Match(tok, ".|::|:|,")) { // If checking code that is single threaded, this might be not interesing for all. // Therefore this is "portabiblity" reportError(tok->tokAt(1), Severity::portability, "nonreentrantFunctions"+it->first, it->second); diff --git a/lib/checknonreentrantfunctions.h b/lib/checknonreentrantfunctions.h index 8d4a185c5..74e20a4bd 100644 --- a/lib/checknonreentrantfunctions.h +++ b/lib/checknonreentrantfunctions.h @@ -34,24 +34,20 @@ * @brief Using non reentrant functions that can be replaced by their reentrant versions */ -class CheckNonReentrantFunctions : public Check -{ +class CheckNonReentrantFunctions : public Check { public: /** This constructor is used when registering the CheckNonReentrantFunctions */ - CheckNonReentrantFunctions() : Check(myName()) - { + CheckNonReentrantFunctions() : Check(myName()) { initNonReentrantFunctions(); } /** This constructor is used when running checks. */ CheckNonReentrantFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(myName(), tokenizer, settings, errorLogger) - { + : Check(myName(), tokenizer, settings, errorLogger) { initNonReentrantFunctions(); } - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckNonReentrantFunctions checkNonReentrantFunctions(tokenizer, settings, errorLogger); checkNonReentrantFunctions.nonReentrantFunctions(); } @@ -65,10 +61,8 @@ private: std::list< std::pair< const std::string, const std::string> > _nonReentrantFunctions; /** init nonreentrant functions list ' */ - void initNonReentrantFunctions() - { - static const char * const non_reentrant_functions_list[] = - { + void initNonReentrantFunctions() { + static const char * const non_reentrant_functions_list[] = { "ctime", "localtime", "gmtime", "asctime", "strtok", "gethostbyname", "gethostbyaddr", "getservbyname" , "getservbyport", "crypt", "ttyname", "rand", "gethostbyname2" , "getprotobyname", "getnetbyname", "getnetbyaddr", "getrpcbyname", "getrpcbynumber", "getrpcent" @@ -78,8 +72,7 @@ private: }; // generate messages - for (unsigned int i = 0; i < (sizeof(non_reentrant_functions_list) / sizeof(char *)); ++i) - { + for (unsigned int i = 0; i < (sizeof(non_reentrant_functions_list) / sizeof(char *)); ++i) { std::string strMsg("Found non reentrant function \'"); strMsg+=non_reentrant_functions_list[i]; strMsg+= "\'. For threadsafe applications it is recommended to use the reentrant replacement function \'"; @@ -89,28 +82,23 @@ private: } } - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckNonReentrantFunctions c(0, settings, errorLogger); std::list< std::pair >::const_iterator it(_nonReentrantFunctions.begin()), itend(_nonReentrantFunctions.end()); - for (; it!=itend; ++it) - { + for (; it!=itend; ++it) { c.reportError(0, Severity::portability, "nonreentrantFunctions"+it->first, it->second); } } - std::string myName() const - { + std::string myName() const { return "Non reentrant functions"; } - std::string classInfo() const - { + std::string classInfo() const { std::string info = "Warn if any of these non reentrant functions are used:\n"; std::list< std::pair >::const_iterator it(_nonReentrantFunctions.begin()), itend(_nonReentrantFunctions.end()); - for (; it!=itend; ++it) - { + for (; it!=itend; ++it) { info += "* " + it->first + "\n"; } return info; diff --git a/lib/checknullpointer.cpp b/lib/checknullpointer.cpp index b8ff1512b..61e99e7b0 100644 --- a/lib/checknullpointer.cpp +++ b/lib/checknullpointer.cpp @@ -26,9 +26,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckNullPointer instance; +namespace { + CheckNullPointer instance; } //--------------------------------------------------------------------------- @@ -37,8 +36,7 @@ CheckNullPointer instance; /** Is string uppercase? */ bool CheckNullPointer::isUpper(const std::string &str) { - for (unsigned int i = 0; i < str.length(); ++i) - { + for (unsigned int i = 0; i < str.length(); ++i) { if (str[i] >= 'a' && str[i] <= 'z') return false; } @@ -57,8 +55,7 @@ void CheckNullPointer::parseFunctionCall(const Token &tok, std::list functionNames1; - if (functionNames1.empty()) - { + if (functionNames1.empty()) { functionNames1.insert("memchr"); functionNames1.insert("memcmp"); functionNames1.insert("strcat"); @@ -87,8 +84,7 @@ void CheckNullPointer::parseFunctionCall(const Token &tok, std::list functionNames2; - if (functionNames2.empty()) - { + if (functionNames2.empty()) { functionNames2.insert("memcmp"); functionNames2.insert("memcpy"); functionNames2.insert("memmove"); @@ -107,8 +103,7 @@ void CheckNullPointer::parseFunctionCall(const Token &tok, std::listvarId() > 0) || - (value == 0 && Token::Match(&tok, "%var% ( 0 ,|)"))) - { + (value == 0 && Token::Match(&tok, "%var% ( 0 ,|)"))) { if (functionNames1.find(tok.str()) != functionNames1.end()) var.push_back(tok.tokAt(2)); else if (value == 0 && Token::Match(&tok, "memcpy|memmove|memset|strcpy|printf|sprintf|vsprintf|vprintf|fprintf|vfprintf")) @@ -121,55 +116,39 @@ void CheckNullPointer::parseFunctionCall(const Token &tok, std::listvarId() > 0) || - (value == 0 && Token::Match(&tok, "%var% ( %any% , 0 ,|)"))) - { + (value == 0 && Token::Match(&tok, "%var% ( %any% , 0 ,|)"))) { if (functionNames2.find(tok.str()) != functionNames2.end()) var.push_back(tok.tokAt(4)); } - if (Token::Match(&tok, "printf|sprintf|snprintf|fprintf|fnprintf|scanf|sscanf|fscanf")) - { + if (Token::Match(&tok, "printf|sprintf|snprintf|fprintf|fnprintf|scanf|sscanf|fscanf")) { const Token* argListTok = 0; // Points to first va_list argument std::string formatString; bool scan = Token::Match(&tok, "scanf|sscanf|fscanf"); - if (Token::Match(&tok, "printf|scanf ( %str% , %any%")) - { + if (Token::Match(&tok, "printf|scanf ( %str% , %any%")) { formatString = tok.strAt(2); argListTok = tok.tokAt(4); - } - else if (Token::Match(&tok, "sprintf|fprintf|sscanf|fscanf ( %var% , %str% , %any%")) - { + } else if (Token::Match(&tok, "sprintf|fprintf|sscanf|fscanf ( %var% , %str% , %any%")) { formatString = tok.strAt(4); argListTok = tok.tokAt(6); - } - else if (Token::Match(&tok, "snprintf|fnprintf ( %var% , %any% , %str% , %any%")) - { + } else if (Token::Match(&tok, "snprintf|fnprintf ( %var% , %any% , %str% , %any%")) { formatString = tok.strAt(6); argListTok = tok.tokAt(8); } - if (argListTok) - { + if (argListTok) { bool percent = false; - for (std::string::iterator i = formatString.begin(); i != formatString.end(); ++i) - { - if (*i == '%') - { + for (std::string::iterator i = formatString.begin(); i != formatString.end(); ++i) { + if (*i == '%') { percent = !percent; - } - else if (percent && std::isalpha(*i)) - { - if (*i == 'n' || *i == 's' || scan) - { - if ((value == 0 && argListTok->str() == "0") || (Token::Match(argListTok, "%var%") && argListTok->varId() > 0)) - { + } else if (percent && std::isalpha(*i)) { + if (*i == 'n' || *i == 's' || scan) { + if ((value == 0 && argListTok->str() == "0") || (Token::Match(argListTok, "%var%") && argListTok->varId() > 0)) { var.push_back(argListTok); } } - for (; argListTok; argListTok = argListTok->next()) // Find next argument - { - if (argListTok->str() == ",") - { + for (; argListTok; argListTok = argListTok->next()) { // Find next argument + if (argListTok->str() == ",") { argListTok = argListTok->next(); break; } @@ -244,8 +223,7 @@ bool CheckNullPointer::isPointer(const unsigned int varid) // it is a pointer if (!tok->previous() || Token::Match(tok->previous(), "[({};]") || - tok->previous()->isName()) - { + tok->previous()->isName()) { return true; } @@ -256,8 +234,7 @@ bool CheckNullPointer::isPointer(const unsigned int varid) void CheckNullPointer::nullPointerAfterLoop() { // Locate insufficient null-pointer handling after loop - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // only interested in while ( %var% ) // TODO: Aren't there false negatives. Shouldn't other loops be handled such as: // - while ( ! %var% ) @@ -284,19 +261,16 @@ void CheckNullPointer::nullPointerAfterLoop() bool inconclusive = false; // Check if the variable is dereferenced after the while loop - while (0 != (tok2 = tok2 ? tok2->next() : 0)) - { + while (0 != (tok2 = tok2 ? tok2->next() : 0)) { // inner and outer scopes - if (tok2->str() == "{" || tok2->str() == "}") - { + if (tok2->str() == "{" || tok2->str() == "}") { // Not inconclusive: bail out if (!_settings->inconclusive) break; inconclusive = true; - if (tok2->str() == "}") - { + if (tok2->str() == "}") { // "}" => leaving function? then break. const Token *tok3 = tok2->link()->previous(); if (!tok3 || !Token::Match(tok3, "[);]")) @@ -311,14 +285,12 @@ void CheckNullPointer::nullPointerAfterLoop() break; // loop variable is found.. - else if (tok2->varId() == varid) - { + else if (tok2->varId() == varid) { // dummy variable.. is it unknown if pointer is dereferenced or not? bool unknown = false; // Is the loop variable dereferenced? - if (CheckNullPointer::isPointerDeRef(tok2, unknown)) - { + if (CheckNullPointer::isPointerDeRef(tok2, unknown)) { nullPointerError(tok2, varname, tok->linenr(), inconclusive); } break; @@ -335,8 +307,7 @@ void CheckNullPointer::nullPointerLinkedList() // if (tok->str() == "hello") // tok = tok->next; // <- tok might become a null pointer! // } - for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { // search for a "for" token.. if (!Token::simpleMatch(tok1, "for (")) continue; @@ -344,21 +315,18 @@ void CheckNullPointer::nullPointerLinkedList() // is there any dereferencing occurring in the for statement // parlevel2 counts the parentheses when using tok2. unsigned int parlevel2 = 1; - for (const Token *tok2 = tok1->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok1->tokAt(2); tok2; tok2 = tok2->next()) { // Parentheses.. if (tok2->str() == "(") ++parlevel2; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel2 <= 1) break; --parlevel2; } // Dereferencing a variable inside the "for" parentheses.. - else if (Token::Match(tok2, "%var% . %var%")) - { + else if (Token::Match(tok2, "%var% . %var%")) { // Variable id for dereferenced variable const unsigned int varid(tok2->varId()); if (varid == 0) @@ -372,33 +340,27 @@ void CheckNullPointer::nullPointerLinkedList() // Check usage of dereferenced variable in the loop.. unsigned int indentlevel3 = 0; - for (const Token *tok3 = tok1->next()->link(); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok1->next()->link(); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel3; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indentlevel3 <= 1) break; --indentlevel3; } // TODO: are there false negatives for "while ( %varid% ||" - else if (Token::Match(tok3, "while ( %varid% &&|)", varid)) - { + else if (Token::Match(tok3, "while ( %varid% &&|)", varid)) { // Make sure there is a "break" or "return" inside the loop. // Without the "break" a null pointer could be dereferenced in the // for statement. // indentlevel4 is a counter for { and }. When scanning the code with tok4 unsigned int indentlevel4 = indentlevel3; - for (const Token *tok4 = tok3->next()->link(); tok4; tok4 = tok4->next()) - { + for (const Token *tok4 = tok3->next()->link(); tok4; tok4 = tok4->next()) { if (tok4->str() == "{") ++indentlevel4; - else if (tok4->str() == "}") - { - if (indentlevel4 <= 1) - { + else if (tok4->str() == "}") { + if (indentlevel4 <= 1) { // Is this variable a pointer? if (isPointer(varid)) nullPointerError(tok1, varname, tok3->linenr()); @@ -430,21 +392,17 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() skipvar.insert(0); // Scan through all tokens - for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { // Checking if some pointer is null. // then add the pointer to skipvar => is it known that it isn't NULL - if (Token::Match(tok1, "if|while ( !| %var% )")) - { + if (Token::Match(tok1, "if|while ( !| %var% )")) { tok1 = tok1->tokAt(2); if (tok1->str() == "!") tok1 = tok1->next(); skipvar.insert(tok1->varId()); continue; - } - else if (Token::Match(tok1, "( ! %var% ||") || - Token::Match(tok1, "( %var% &&")) - { + } else if (Token::Match(tok1, "( ! %var% ||") || + Token::Match(tok1, "( %var% &&")) { // TODO: there are false negatives caused by this. The // variable should be removed from skipvar after the // condition @@ -461,22 +419,19 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() */ // dereference in assignment - if (Token::Match(tok1, "[;{}] %var% . %var%")) - { + if (Token::Match(tok1, "[;{}] %var% . %var%")) { tok1 = tok1->next(); } // dereference in assignment - else if (Token::Match(tok1, "[{};] %var% = %var% . %var%")) - { + else if (Token::Match(tok1, "[{};] %var% = %var% . %var%")) { if (std::string(tok1->strAt(1)) == tok1->strAt(3)) continue; tok1 = tok1->tokAt(3); } // dereference in condition - else if (Token::Match(tok1, "if ( !| %var% .")) - { + else if (Token::Match(tok1, "if ( !| %var% .")) { tok1 = tok1->tokAt(2); if (tok1->str() == "!") tok1 = tok1->next(); @@ -484,18 +439,15 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() // dereference in function call (but not sizeof|decltype) else if ((Token::Match(tok1->tokAt(-2), "%var% ( %var% . %var%") && !Token::Match(tok1->tokAt(-2), "sizeof|decltype ( %var% . %var%")) || - Token::Match(tok1->previous(), ", %var% . %var%")) - { + Token::Match(tok1->previous(), ", %var% . %var%")) { // Is the function return value taken by the pointer? bool assignment = false; const unsigned int varid1(tok1->varId()); if (varid1 == 0) continue; const Token *tok2 = tok1->previous(); - while (tok2 && !Token::Match(tok2, "[;{}]")) - { - if (Token::Match(tok2, "%varid% =", varid1)) - { + while (tok2 && !Token::Match(tok2, "[;{}]")) { + if (Token::Match(tok2, "%varid% =", varid1)) { assignment = true; break; } @@ -506,8 +458,7 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() } // Goto next token - else - { + else { continue; } @@ -527,8 +478,7 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() isLocal = true; // member function may or may not nullify the pointer if it's global (#2647) - if (!isLocal) - { + if (!isLocal) { const Token *tok2 = tok1; while (Token::Match(tok2, "%var% .")) tok2 = tok2->tokAt(2); @@ -538,13 +488,11 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() // count { and } using tok2 unsigned int indentlevel2 = 0; - for (const Token *tok2 = tok1->tokAt(3); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok1->tokAt(3); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel2; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel2 == 0) break; --indentlevel2; @@ -555,10 +503,8 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() break; // Reassignment of the struct - else if (tok2->varId() == varid1) - { - if (tok2->next()->str() == "=") - { + else if (tok2->varId() == varid1) { + if (tok2->next()->str() == "=") { // Avoid false positives when there is 'else if' // TODO: can this be handled better? if (tok1->strAt(-2) == "if") @@ -581,15 +527,13 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec() // Function call: If the pointer is not a local variable it // might be changed by the call. else if (Token::Match(tok2, "[;{}] %var% (") && - Token::simpleMatch(tok2->tokAt(2)->link(), ") ;") && !isLocal) - { + Token::simpleMatch(tok2->tokAt(2)->link(), ") ;") && !isLocal) { break; } // Check if pointer is null. // TODO: false negatives for "if (!p || .." - else if (Token::Match(tok2, "if ( !| %varid% )|&&", varid1)) - { + else if (Token::Match(tok2, "if ( !| %varid% )|&&", varid1)) { // Is this variable a pointer? if (isPointer(varid1)) nullPointerError(tok1, varname, tok2->linenr()); @@ -606,13 +550,11 @@ void CheckNullPointer::nullPointerByDeRefAndChec() // Dereferencing a pointer and then checking if it's NULL.. // This check will first scan for the check. And then scan backwards // from the check, searching for dereferencing. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // TODO: false negatives. // - logical operators // - while - if (tok->str() == "if" && Token::Match(tok->previous(), "; if ( !| %var% )|%oror%|&&")) - { + if (tok->str() == "if" && Token::Match(tok->previous(), "; if ( !| %var% )|%oror%|&&")) { const Token * vartok = tok->tokAt(2); if (vartok->str() == "!") vartok = vartok->next(); @@ -636,10 +578,8 @@ void CheckNullPointer::nullPointerByDeRefAndChec() const Token * const decltok = var->nameToken(); - for (const Token *tok1 = tok->previous(); tok1 && tok1 != decltok; tok1 = tok1->previous()) - { - if (tok1->str() == ")" && Token::Match(tok1->link()->previous(), "%var% (")) - { + for (const Token *tok1 = tok->previous(); tok1 && tok1 != decltok; tok1 = tok1->previous()) { + if (tok1->str() == ")" && Token::Match(tok1->link()->previous(), "%var% (")) { const Token *tok2 = tok1->link(); while (tok2 && !Token::Match(tok2, "[;{}?:]")) tok2 = tok2->previous(); @@ -652,24 +592,20 @@ void CheckNullPointer::nullPointerByDeRefAndChec() break; if (Token::Match(tok1->link(), "( ! %varid% ||", varid) || - Token::Match(tok1->link(), "( %varid% &&", varid)) - { + Token::Match(tok1->link(), "( %varid% &&", varid)) { tok1 = tok1->link(); continue; } - if (Token::simpleMatch(tok1->link()->previous(), "sizeof (")) - { + if (Token::simpleMatch(tok1->link()->previous(), "sizeof (")) { tok1 = tok1->link()->previous(); continue; } - if (Token::Match(tok2, "[;{}] %var% ( %varid% ,", varid)) - { + if (Token::Match(tok2, "[;{}] %var% ( %varid% ,", varid)) { std::list varlist; parseFunctionCall(*(tok2->next()), varlist, 0); - if (!varlist.empty() && varlist.front() == tok2->tokAt(3)) - { + if (!varlist.empty() && varlist.front() == tok2->tokAt(3)) { nullPointerError(tok2->tokAt(3), varname, tok->linenr()); break; } @@ -683,15 +619,12 @@ void CheckNullPointer::nullPointerByDeRefAndChec() if (tok1->str() == "break") break; - if (tok1->varId() == varid) - { + if (tok1->varId() == varid) { // Don't write warning if the dereferencing is // guarded by ?: const Token *tok2 = tok1->previous(); - if (tok2 && (tok2->isArithmeticalOp() || tok2->str() == "(")) - { - while (tok2 && !Token::Match(tok2, "[;{}?:]")) - { + if (tok2 && (tok2->isArithmeticalOp() || tok2->str() == "(")) { + while (tok2 && !Token::Match(tok2, "[;{}?:]")) { if (tok2->str() == ")") tok2 = tok2->link(); tok2 = tok2->previous(); @@ -704,29 +637,18 @@ void CheckNullPointer::nullPointerByDeRefAndChec() // uncertain bool unknown = false; - if (Token::Match(tok1->tokAt(-2), "%varid% = %varid% .", varid)) - { + if (Token::Match(tok1->tokAt(-2), "%varid% = %varid% .", varid)) { break; - } - else if (Token::Match(tok1->previous(), "&&|%oror%")) - { + } else if (Token::Match(tok1->previous(), "&&|%oror%")) { break; - } - else if (Token::Match(tok1->tokAt(-2), "&&|%oror% !")) - { + } else if (Token::Match(tok1->tokAt(-2), "&&|%oror% !")) { break; - } - else if (CheckNullPointer::isPointerDeRef(tok1, unknown)) - { + } else if (CheckNullPointer::isPointerDeRef(tok1, unknown)) { nullPointerError(tok1, varname, tok->linenr()); break; - } - else if (Token::simpleMatch(tok1->previous(), "&")) - { + } else if (Token::simpleMatch(tok1->previous(), "&")) { break; - } - else if (Token::simpleMatch(tok1->next(), "=")) - { + } else if (Token::simpleMatch(tok1->next(), "=")) { break; } } @@ -751,13 +673,11 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() // TODO: Use isPointer? std::set pointerVariables; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "* %var% [;,)=]")) pointerVariables.insert(tok->next()->varId()); - else if (Token::simpleMatch(tok, "if (")) - { + else if (Token::simpleMatch(tok, "if (")) { // TODO: investigate false negatives: // - handle "while"? // - if there are logical operators @@ -808,8 +728,7 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() // indentlevel inside the if-body is 1 unsigned int indentlevel = 1; - if (Token::Match(tok, "if|while ( %var% )|&&")) - { + if (Token::Match(tok, "if|while ( %var% )|&&")) { // pointer might be null null = false; @@ -827,18 +746,15 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() const std::string &pointerName = vartok->str(); // Count { and } for tok2 - for (const Token *tok2 = tok1; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok1; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel == 0) break; --indentlevel; - if (null && indentlevel == 0) - { + if (null && indentlevel == 0) { // skip all "else" blocks because they are not executed in this execution path while (Token::simpleMatch(tok2, "} else {")) tok2 = tok2->tokAt(2)->link(); @@ -846,8 +762,7 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() } } - if (Token::Match(tok2, "goto|return|continue|break|throw|if|switch")) - { + if (Token::Match(tok2, "goto|return|continue|break|throw|if|switch")) { bool dummy = false; if (Token::Match(tok2, "return * %varid%", varid)) nullPointerError(tok2, pointerName, linenr); @@ -858,21 +773,17 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() } // parameters to sizeof are not dereferenced - if (Token::Match(tok2, "decltype|sizeof (")) - { + if (Token::Match(tok2, "decltype|sizeof (")) { tok2 = tok2->next()->link(); continue; } // function call, check if pointer is dereferenced - if (Token::Match(tok2, "%var% (")) - { + if (Token::Match(tok2, "%var% (")) { std::list var; parseFunctionCall(*tok2, var, 0); - for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) - { - if ((*it)->varId() == varid) - { + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) { + if ((*it)->varId() == varid) { nullPointerError(*it, pointerName, linenr); break; } @@ -882,8 +793,7 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() // calling unknown function (abort/init).. if (Token::simpleMatch(tok2, ") ;") && (Token::Match(tok2->link()->tokAt(-2), "[;{}.] %var% (") || - Token::Match(tok2->link()->tokAt(-5), "[;{}] ( * %var% ) ("))) - { + Token::Match(tok2->link()->tokAt(-5), "[;{}] ( * %var% ) ("))) { // noreturn function? if (tok2->strAt(2) == "}") break; @@ -895,8 +805,7 @@ void CheckNullPointer::nullPointerByCheckAndDeRef() break; } - if (tok2->varId() == varid) - { + if (tok2->varId() == varid) { // unknown: this is set to true by isPointerDeRef if // the function fails to determine if there // is a dereference or not @@ -932,19 +841,16 @@ void CheckNullPointer::nullConstantDereference() // this is kept at 0 for all scopes that are not executing unsigned int indentlevel = 0; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // start of executable scope.. if (indentlevel == 0 && Token::Match(tok, ") const| {")) indentlevel = 1; - else if (indentlevel >= 1) - { + else if (indentlevel >= 1) { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 2) indentlevel = 0; else @@ -954,11 +860,9 @@ void CheckNullPointer::nullConstantDereference() if (tok->str() == "(" && Token::Match(tok->previous(), "sizeof|decltype")) tok = tok->link(); - else if (Token::simpleMatch(tok, "exit ( )")) - { + else if (Token::simpleMatch(tok, "exit ( )")) { // Goto end of scope - while (tok && tok->str() != "}") - { + while (tok && tok->str() != "}") { if (tok->str() == "{") tok = tok->link(); tok = tok->next(); @@ -967,24 +871,19 @@ void CheckNullPointer::nullConstantDereference() break; } - else if (Token::simpleMatch(tok, "* 0")) - { - if (Token::Match(tok->previous(), "return|;|{|}|=|(|,|%op%")) - { + else if (Token::simpleMatch(tok, "* 0")) { + if (Token::Match(tok->previous(), "return|;|{|}|=|(|,|%op%")) { nullPointerError(tok); } } - else if (indentlevel > 0 && Token::Match(tok->previous(), "[={};] %var% (")) - { + else if (indentlevel > 0 && Token::Match(tok->previous(), "[={};] %var% (")) { std::list var; parseFunctionCall(*tok, var, 0); // is one of the var items a NULL pointer? - for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) - { - if ((*it)->str() == "0") - { + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) { + if ((*it)->str() == "0") { nullPointerError(*it); } } @@ -1002,12 +901,10 @@ void CheckNullPointer::nullConstantDereference() * @brief %Check for null pointer usage (using ExecutionPath) */ -class Nullpointer : public ExecutionPath -{ +class Nullpointer : public ExecutionPath { public: /** Startup constructor */ - Nullpointer(Check *c) : ExecutionPath(c, 0), null(false) - { + Nullpointer(Check *c) : ExecutionPath(c, 0), null(false) { } private: @@ -1015,13 +912,11 @@ private: Nullpointer(Check *c, const unsigned int id, const std::string &name) : ExecutionPath(c, id), varname(name), - null(false) - { + null(false) { } /** Copy this check */ - ExecutionPath *copy() - { + ExecutionPath *copy() { return new Nullpointer(*this); } @@ -1029,8 +924,7 @@ private: void operator=(const Nullpointer &); /** is other execution path equal? */ - bool is_equal(const ExecutionPath *e) const - { + bool is_equal(const ExecutionPath *e) const { const Nullpointer *c = static_cast(e); return (varname == c->varname && null == c->null); } @@ -1042,11 +936,9 @@ private: bool null; /** variable is set to null */ - static void setnull(std::list &checks, const unsigned int varid) - { + static void setnull(std::list &checks, const unsigned int varid) { std::list::iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { Nullpointer *c = dynamic_cast(*it); if (c && c->varId == varid) c->null = true; @@ -1058,19 +950,15 @@ private: * @param checks Checks * @param tok token where dereferencing happens */ - static void dereference(std::list &checks, const Token *tok) - { + static void dereference(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); std::list::iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { Nullpointer *c = dynamic_cast(*it); - if (c && c->varId == varid && c->null) - { + if (c && c->varId == varid && c->null) { CheckNullPointer *checkNullPointer = dynamic_cast(c->owner); - if (checkNullPointer) - { + if (checkNullPointer) { checkNullPointer->nullPointerError(tok, c->varname); return; } @@ -1079,10 +967,8 @@ private: } /** parse tokens */ - const Token *parse(const Token &tok, std::list &checks) const - { - if (Token::Match(tok.previous(), "[;{}] const| struct| %type% * %var% ;")) - { + const Token *parse(const Token &tok, std::list &checks) const { + if (Token::Match(tok.previous(), "[;{}] const| struct| %type% * %var% ;")) { const Token * vartok = tok.tokAt(2); if (tok.str() == "const") @@ -1097,21 +983,18 @@ private: } // Template pointer variable.. - if (Token::Match(tok.previous(), "[;{}] %type% ::|<")) - { + if (Token::Match(tok.previous(), "[;{}] %type% ::|<")) { const Token * vartok = &tok; while (Token::Match(vartok, "%type% ::")) vartok = vartok->tokAt(2); - if (Token::Match(vartok, "%type% < %type%")) - { + if (Token::Match(vartok, "%type% < %type%")) { vartok = vartok->tokAt(3); while (vartok && (vartok->str() == "*" || vartok->isName())) vartok = vartok->next(); } if (vartok && (vartok->str() == ">" || vartok->isName()) - && Token::Match(vartok->next(), "* %var% ;|=")) - { + && Token::Match(vartok->next(), "* %var% ;|=")) { vartok = vartok->tokAt(2); checks.push_back(new Nullpointer(owner, vartok->varId(), vartok->str())); if (Token::simpleMatch(vartok->next(), "= 0 ;")) @@ -1120,29 +1003,24 @@ private: } } - if (Token::simpleMatch(&tok, "try {")) - { + if (Token::simpleMatch(&tok, "try {")) { // Bail out all used variables unsigned int indentlevel = 0; - for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel == 0) break; if (indentlevel == 1 && !Token::simpleMatch(tok2,"} catch (")) return tok2; --indentlevel; - } - else if (tok2->varId()) + } else if (tok2->varId()) bailOutVar(checks,tok2->varId()); } } - if (Token::Match(&tok, "%var% (")) - { + if (Token::Match(&tok, "%var% (")) { if (tok.str() == "sizeof") return tok.next()->link(); @@ -1156,8 +1034,7 @@ private: else if (Token::simpleMatch(&tok, "( 0 &&")) return tok.link(); - if (tok.varId() != 0) - { + if (tok.varId() != 0) { // unknown : not really used. it is passed to isPointerDeRef. // if isPointerDeRef fails to determine if there // is a dereference the this will be set to true. @@ -1173,8 +1050,7 @@ private: bailOutVar(checks, tok.varId()); } - else if (tok.str() == "delete") - { + else if (tok.str() == "delete") { const Token *ret = tok.next(); if (Token::simpleMatch(ret, "[ ]")) ret = ret->tokAt(2); @@ -1182,14 +1058,12 @@ private: return ret->next(); } - else if (tok.str() == "return") - { + else if (tok.str() == "return") { bool unknown = false; const Token *vartok = tok.next(); if (vartok->str() == "*") vartok = vartok->next(); - if (vartok->varId() && CheckNullPointer::isPointerDeRef(vartok, unknown)) - { + if (vartok->varId() && CheckNullPointer::isPointerDeRef(vartok, unknown)) { dereference(checks, vartok); } } @@ -1198,18 +1072,15 @@ private: } /** parse condition. @sa ExecutionPath::parseCondition */ - bool parseCondition(const Token &tok, std::list &checks) - { - for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) - { + bool parseCondition(const Token &tok, std::list &checks) { + for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == ")") break; if (Token::Match(tok2, "[<>=] * %var%")) dereference(checks, tok2->tokAt(2)); } - if (Token::Match(&tok, "!| %var% (")) - { + if (Token::Match(&tok, "!| %var% (")) { std::list var; CheckNullPointer::parseFunctionCall(tok.str() == "!" ? *tok.next() : tok, var, 0); for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) @@ -1220,10 +1091,8 @@ private: } - void parseLoopBody(const Token *tok, std::list &checks) const - { - while (tok) - { + void parseLoopBody(const Token *tok, std::list &checks) const { + while (tok) { if (Token::Match(tok, "{|}|return|goto|break|if")) return; const Token *next = parse(*tok, checks); diff --git a/lib/checknullpointer.h b/lib/checknullpointer.h index e6ecf6d24..f747555e6 100644 --- a/lib/checknullpointer.h +++ b/lib/checknullpointer.h @@ -33,8 +33,7 @@ class Token; /** @brief check for null pointer dereferencing */ -class CheckNullPointer : public Check -{ +class CheckNullPointer : public Check { public: /** @brief This constructor is used when registering the CheckNullPointer */ CheckNullPointer() : Check(myName()) @@ -46,15 +45,13 @@ public: { } /** @brief Run checks against the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckNullPointer checkNullPointer(tokenizer, settings, errorLogger); checkNullPointer.nullPointer(); } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckNullPointer checkNullPointer(tokenizer, settings, errorLogger); checkNullPointer.nullConstantDereference(); checkNullPointer.executionPaths(); @@ -105,21 +102,18 @@ public: void nullPointerError(const Token *tok, const std::string &varname, const unsigned int line, bool inconclusive = false); /** Get error messages. Used by --errorlist */ - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckNullPointer c(0, settings, errorLogger); c.nullPointerError(0, "pointer"); } /** Name of check */ - std::string myName() const - { + std::string myName() const { return "Null pointer"; } /** class info in WIKI format. Used by --doc */ - std::string classInfo() const - { + std::string classInfo() const { return "Null pointers\n" "* null pointer dereferencing\n"; } diff --git a/lib/checkobsoletefunctions.cpp b/lib/checkobsoletefunctions.cpp index 14bf4b3a7..38a48ae05 100644 --- a/lib/checkobsoletefunctions.cpp +++ b/lib/checkobsoletefunctions.cpp @@ -27,9 +27,8 @@ // Register this check class (by creating a static instance of it) -namespace -{ -CheckObsoleteFunctions instance; +namespace { + CheckObsoleteFunctions instance; } void CheckObsoleteFunctions::obsoleteFunctions() @@ -43,45 +42,35 @@ void CheckObsoleteFunctions::obsoleteFunctions() const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->isName() && tok->varId()==0 && tok->strAt(1) == "(" && - (!Token::Match(tok->previous(), ".|::|:|,") || Token::simpleMatch(tok->previous()->previous(), "std :: gets"))) - { + (!Token::Match(tok->previous(), ".|::|:|,") || Token::simpleMatch(tok->previous()->previous(), "std :: gets"))) { // function declaration? if ((tok->previous() && (tok->previous()->str() == "*" || tok->previous()->isName())) - || symbolDatabase->findFunctionByToken(tok)) - { + || symbolDatabase->findFunctionByToken(tok)) { _obsoleteStandardFunctions.erase(tok->str()); _obsoletePosixFunctions.erase(tok->str()); continue; } std::map::const_iterator it = _obsoleteStandardFunctions.find(tok->str()); - if (it != _obsoleteStandardFunctions.end()) - { + if (it != _obsoleteStandardFunctions.end()) { // If checking an old code base it might be uninteresting to update obsolete functions. // Therefore this is "information" reportError(tok->tokAt(1), Severity::style, "obsoleteFunctions"+it->first, it->second); - } - else - { - if (_settings->posix) - { + } else { + if (_settings->posix) { it = _obsoletePosixFunctions.find(tok->str()); - if (it != _obsoletePosixFunctions.end()) - { + if (it != _obsoletePosixFunctions.end()) { // If checking an old code base it might be uninteresting to update obsolete functions. // Therefore this is "information" reportError(tok->tokAt(1), Severity::style, "obsoleteFunctions"+it->first, it->second); } } - if (_settings->c99) - { + if (_settings->c99) { it = _obsoleteC99Functions.find(tok->str()); - if (it != _obsoleteC99Functions.end()) - { + if (it != _obsoleteC99Functions.end()) { reportError(tok->tokAt(1), Severity::style, "obsoleteFunctions"+it->first, it->second); } } diff --git a/lib/checkobsoletefunctions.h b/lib/checkobsoletefunctions.h index d5b46bec4..24d19961d 100644 --- a/lib/checkobsoletefunctions.h +++ b/lib/checkobsoletefunctions.h @@ -34,24 +34,20 @@ * @brief Using obsolete functions that are always insecure to use. */ -class CheckObsoleteFunctions : public Check -{ +class CheckObsoleteFunctions : public Check { public: /** This constructor is used when registering the CheckObsoleteFunctions */ - CheckObsoleteFunctions() : Check(myName()) - { + CheckObsoleteFunctions() : Check(myName()) { initObsoleteFunctions(); } /** This constructor is used when running checks. */ CheckObsoleteFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(myName(), tokenizer, settings, errorLogger) - { + : Check(myName(), tokenizer, settings, errorLogger) { initObsoleteFunctions(); } - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckObsoleteFunctions checkObsoleteFunctions(tokenizer, settings, errorLogger); checkObsoleteFunctions.obsoleteFunctions(); } @@ -66,8 +62,7 @@ private: std::map _obsoleteC99Functions; /** init obsolete functions list ' */ - void initObsoleteFunctions() - { + void initObsoleteFunctions() { _obsoletePosixFunctions["bsd_signal"] = "Found obsolete function 'bsd_signal'. It is recommended that new applications use the 'sigaction' function"; _obsoletePosixFunctions["gethostbyaddr"] = "Found obsolete function 'gethostbyaddr'. It is recommended that new applications use the 'getnameinfo' function"; @@ -116,28 +111,23 @@ private: } - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckObsoleteFunctions c(0, settings, errorLogger); std::map::const_iterator it(_obsoletePosixFunctions.begin()), itend(_obsoletePosixFunctions.end()); - for (; it!=itend; ++it) - { + for (; it!=itend; ++it) { c.reportError(0, Severity::style, "obsoleteFunctions"+it->first, it->second); } } - std::string myName() const - { + std::string myName() const { return "Obsolete functions"; } - std::string classInfo() const - { + std::string classInfo() const { std::string info = "Warn if any of these obsolete functions are used:\n"; std::map::const_iterator it(_obsoletePosixFunctions.begin()), itend(_obsoletePosixFunctions.end()); - for (; it!=itend; ++it) - { + for (; it!=itend; ++it) { info += "* " + it->first + "\n"; } return info; diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 72e46b5ff..6d9c764bc 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -28,9 +28,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckOther instance; +namespace { + CheckOther instance; } //--------------------------------------------------------------------------- @@ -42,12 +41,9 @@ void CheckOther::checkIncrementBoolean() const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "%var% ++")) - { - if (tok->varId()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "%var% ++")) { + if (tok->varId()) { const Variable *var = symbolDatabase->getVariableFromVarId(tok->varId()); if (var && var->typeEndToken()->str() == "bool") @@ -74,10 +70,8 @@ void CheckOther::clarifyCalculation() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (tok->strAt(1) == "?") - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (tok->strAt(1) == "?") { // condition const Token *cond = tok; if (cond->isName() || cond->isNumber()) @@ -108,12 +102,9 @@ void CheckOther::clarifyCalculation() continue; // first multiplication operand - if (cond->str() == ")") - { + if (cond->str() == ")") { clarifyCalculationError(cond, op); - } - else if (cond->isName() || cond->isNumber()) - { + } else if (cond->isName() || cond->isNumber()) { if (Token::Match(cond->previous(),("return|=|+|-|,|(|"+op).c_str())) clarifyCalculationError(cond, op); } @@ -149,34 +140,27 @@ void CheckOther::clarifyCondition() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "( %var% [=&|^]")) - { - for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "( %var% [=&|^]")) { + for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "[") tok2 = tok2->link(); - else if (Token::Match(tok2, "<|<=|==|!=|>|>=")) - { + else if (Token::Match(tok2, "<|<=|==|!=|>|>=")) { // This might be a template if (!code_is_c() && Token::Match(tok2->previous(), "%var% <")) break; clarifyConditionError(tok, tok->strAt(2) == "=", false); break; - } - else if (!tok2->isName() && !tok2->isNumber() && tok2->str() != ".") + } else if (!tok2->isName() && !tok2->isNumber() && tok2->str() != ".") break; } } } // using boolean result in bitwise operation ! x [&|^] - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "!|<|<=|==|!=|>|>=")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "!|<|<=|==|!=|>|>=")) { const Token *tok2 = tok->next(); // Todo: There are false positives if '(' if encountered. It @@ -185,15 +169,13 @@ void CheckOther::clarifyCondition() if (Token::Match(tok2, "(|&")) continue; - while (tok2 && (tok2->isName() || tok2->isNumber() || Token::Match(tok2,".|(|["))) - { + while (tok2 && (tok2->isName() || tok2->isNumber() || Token::Match(tok2,".|(|["))) { if (Token::Match(tok2, "(|[")) tok2 = tok2->link(); tok2 = tok2->next(); } - if (Token::Match(tok2, "[&|^]")) - { + if (Token::Match(tok2, "[&|^]")) { // don't write false positives when templates are used if (Token::Match(tok, "<|>") && (Token::Match(tok2, "& ,|>") || Token::Match(tok2->previous(), "const &"))) @@ -241,16 +223,12 @@ void CheckOther::checkBitwiseOnBoolean() if (!_settings->inconclusive) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "(|.|return %var% [&|]")) - { - if (tok->next()->varId()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "(|.|return %var% [&|]")) { + if (tok->next()->varId()) { const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(tok->next()->varId()); if (var && (var->typeStartToken() == var->typeEndToken()) && - var->typeStartToken()->str() == "bool") - { + var->typeStartToken()->str() == "bool") { bitwiseOnBooleanError(tok->next(), tok->next()->str(), tok->strAt(2) == "&" ? "&&" : "||"); } } @@ -269,11 +247,9 @@ void CheckOther::checkSuspiciousSemicolon() if (!_settings->inconclusive || !_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Look for "if(); {}", "for(); {}" or "while(); {}" - if (Token::Match(tok, "if|for|while (")) - { + if (Token::Match(tok, "if|for|while (")) { const Token *end = tok->next()->link(); if (!end) continue; @@ -282,8 +258,7 @@ void CheckOther::checkSuspiciousSemicolon() // and the {..} block follows it without an extra empty line. if (Token::simpleMatch(end, ") { ; } {") && end->linenr() == end->tokAt(2)->linenr() - && end->linenr()+1 >= end->tokAt(4)->linenr()) - { + && end->linenr()+1 >= end->tokAt(4)->linenr()) { SuspiciousSemicolonError(tok); } } @@ -305,8 +280,7 @@ void CheckOther::warningOldStylePointerCast() (_tokenizer->tokens() && _tokenizer->fileLine(_tokenizer->tokens()).find(".cpp") == std::string::npos)) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Old style pointer casting.. if (!Token::Match(tok, "( const| %type% * ) %var%") && !Token::Match(tok, "( const| %type% * ) (| new")) @@ -339,8 +313,7 @@ void CheckOther::cstyleCastError(const Token *tok) void CheckOther::checkFflushOnInputStream() { const Token *tok = _tokenizer->tokens(); - while (tok && ((tok = Token::findmatch(tok, "fflush ( stdin )")) != NULL)) - { + while (tok && ((tok = Token::findmatch(tok, "fflush ( stdin )")) != NULL)) { fflushOnInputStreamError(tok, tok->strAt(2)); tok = tok->tokAt(4); } @@ -356,14 +329,12 @@ void CheckOther::fflushOnInputStreamError(const Token *tok, const std::string &v //--------------------------------------------------------------------------- void CheckOther::checkSizeofForNumericParameter() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "sizeof ( %num% )") || Token::Match(tok, "sizeof ( - %num% )") || Token::Match(tok, "sizeof %num%") || Token::Match(tok, "sizeof - %num%") - ) - { + ) { sizeofForNumericParameterError(tok); } } @@ -388,51 +359,38 @@ void CheckOther::checkSizeofForArrayParameter() { const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var%")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var%")) { int tokIdx = 1; - if (tok->tokAt(tokIdx)->str() == "(") - { + if (tok->tokAt(tokIdx)->str() == "(") { ++tokIdx; } - if (tok->tokAt(tokIdx)->varId() > 0) - { + if (tok->tokAt(tokIdx)->varId() > 0) { const Variable *var = symbolDatabase->getVariableFromVarId(tok->tokAt(tokIdx)->varId()); - if (var) - { + if (var) { const Token *declTok = var->nameToken(); - if (Token::simpleMatch(declTok->next(), "[")) - { + if (Token::simpleMatch(declTok->next(), "[")) { declTok = declTok->next()->link(); // multidimensional array - while (Token::simpleMatch(declTok->next(), "[")) - { + while (Token::simpleMatch(declTok->next(), "[")) { declTok = declTok->next()->link(); } - if (!(Token::Match(declTok->next(), "= %str%")) && !(Token::simpleMatch(declTok->next(), "= {")) && !(Token::simpleMatch(declTok->next(), ";"))) - { - if (Token::simpleMatch(declTok->next(), ",")) - { + if (!(Token::Match(declTok->next(), "= %str%")) && !(Token::simpleMatch(declTok->next(), "= {")) && !(Token::simpleMatch(declTok->next(), ";"))) { + if (Token::simpleMatch(declTok->next(), ",")) { declTok = declTok->next(); - while (!Token::simpleMatch(declTok, ";")) - { - if (Token::simpleMatch(declTok, ")")) - { + while (!Token::simpleMatch(declTok, ";")) { + if (Token::simpleMatch(declTok, ")")) { sizeofForArrayParameterError(tok); break; } - if (Token::Match(declTok, "(|[|{")) - { + if (Token::Match(declTok, "(|[|{")) { declTok = declTok->link(); } declTok = declTok->next(); } } } - if (Token::simpleMatch(declTok->next(), ")")) - { + if (Token::simpleMatch(declTok->next(), ")")) { sizeofForArrayParameterError(tok); } } @@ -477,32 +435,24 @@ void CheckOther::checkRedundantAssignmentInSwitch() // Find the beginning of a switch. E.g.: // switch (var) { ... const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern); - while (tok) - { + while (tok) { // Check the contents of the switch statement std::map varsAssigned; std::map stringsCopied; int indentLevel = 0; - for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { // Inside a conditional or loop. Don't mark variable accesses as being redundant. E.g.: // case 3: b = 1; // case 4: if (a) { b = 2; } // Doesn't make the b=1 redundant because it's conditional - if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) - { + if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) { const Token* endOfConditional = tok2->link(); - for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) - { - if (tok3->varId() != 0) - { + for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) { + if (tok3->varId() != 0) { varsAssigned.erase(tok3->varId()); stringsCopied.erase(tok3->varId()); - } - else if (Token::Match(tok3, functionPattern) || Token::Match(tok3, breakPattern)) - { + } else if (Token::Match(tok3, functionPattern) || Token::Match(tok3, breakPattern)) { varsAssigned.clear(); if (tok3->str() != "strcpy" && tok3->str() != "strncpy") @@ -510,12 +460,9 @@ void CheckOther::checkRedundantAssignmentInSwitch() } } tok2 = endOfConditional; - } - else + } else ++ indentLevel; - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { -- indentLevel; // End of the switch block @@ -526,8 +473,7 @@ void CheckOther::checkRedundantAssignmentInSwitch() // Variable assignment. Report an error if it's assigned to twice before a break. E.g.: // case 3: b = 1; // <== redundant // case 4: b = 2; - if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;") && tok2->varId() != 0) - { + if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;") && tok2->varId() != 0) { std::map::iterator i = varsAssigned.find(tok2->varId()); if (i == varsAssigned.end()) varsAssigned[tok2->varId()] = tok2; @@ -539,8 +485,7 @@ void CheckOther::checkRedundantAssignmentInSwitch() // String copy. Report an error if it's copied to twice before a break. E.g.: // case 3: strcpy(str, "a"); // <== redundant // case 4: strcpy(str, "b"); - else if (Token::Match(tok2->previous(), ";|{|}|: strcpy|strncpy ( %var% ,") && tok2->tokAt(2)->varId() != 0) - { + else if (Token::Match(tok2->previous(), ";|{|}|: strcpy|strncpy ( %var% ,") && tok2->tokAt(2)->varId() != 0) { std::map::iterator i = stringsCopied.find(tok2->tokAt(2)->varId()); if (i == stringsCopied.end()) stringsCopied[tok2->tokAt(2)->varId()] = tok2->tokAt(2); @@ -555,8 +500,7 @@ void CheckOther::checkRedundantAssignmentInSwitch() // Reset our record of assignments if there is a break or function call. E.g.: // case 3: b = 1; break; - if (Token::Match(tok2, functionPattern) || Token::Match(tok2, breakPattern)) - { + if (Token::Match(tok2, functionPattern) || Token::Match(tok2, breakPattern)) { varsAssigned.clear(); if (tok2->str() != "strcpy" && tok2->str() != "strncpy") @@ -596,8 +540,7 @@ void CheckOther::checkSwitchCaseFallThrough() // Find the beginning of a switch. E.g.: // switch (var) { ... const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern); - while (tok) - { + while (tok) { // Check the contents of the switch statement std::stack > ifnest; @@ -605,13 +548,10 @@ void CheckOther::checkSwitchCaseFallThrough() std::stack scopenest; bool justbreak = true; bool firstcase = true; - for (const Token *tok2 = tok->tokAt(1)->link()->tokAt(2); tok2; tok2 = tok2->next()) - { - if (Token::simpleMatch(tok2, "if (")) - { + for (const Token *tok2 = tok->tokAt(1)->link()->tokAt(2); tok2; tok2 = tok2->next()) { + if (Token::simpleMatch(tok2, "if (")) { tok2 = tok2->tokAt(1)->link()->next(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched if in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -619,15 +559,11 @@ void CheckOther::checkSwitchCaseFallThrough() } ifnest.push(std::make_pair(tok2->link(), false)); justbreak = false; - } - else if (Token::simpleMatch(tok2, "while (")) - { + } else if (Token::simpleMatch(tok2, "while (")) { tok2 = tok2->tokAt(1)->link()->next(); // skip over "do { } while ( ) ;" case - if (tok2->str() == "{") - { - if (tok2->link() == NULL) - { + if (tok2->str() == "{") { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched while in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -636,12 +572,9 @@ void CheckOther::checkSwitchCaseFallThrough() loopnest.push(tok2->link()); } justbreak = false; - } - else if (Token::simpleMatch(tok2, "do {")) - { + } else if (Token::simpleMatch(tok2, "do {")) { tok2 = tok2->tokAt(1); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched do in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -649,12 +582,9 @@ void CheckOther::checkSwitchCaseFallThrough() } loopnest.push(tok2->link()); justbreak = false; - } - else if (Token::simpleMatch(tok2, "for (")) - { + } else if (Token::simpleMatch(tok2, "for (")) { tok2 = tok2->tokAt(1)->link()->next(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched for in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -662,44 +592,29 @@ void CheckOther::checkSwitchCaseFallThrough() } loopnest.push(tok2->link()); justbreak = false; - } - else if (Token::Match(tok2, switchPattern)) - { + } else if (Token::Match(tok2, switchPattern)) { // skip over nested switch, we'll come to that soon tok2 = tok2->tokAt(1)->link()->next()->link(); - } - else if (Token::Match(tok2, breakPattern)) - { - if (loopnest.empty()) - { + } else if (Token::Match(tok2, breakPattern)) { + if (loopnest.empty()) { justbreak = true; } tok2 = Token::findmatch(tok2, ";"); - } - else if (Token::Match(tok2, "case|default")) - { - if (!justbreak && !firstcase) - { + } else if (Token::Match(tok2, "case|default")) { + if (!justbreak && !firstcase) { switchCaseFallThrough(tok2); } tok2 = Token::findmatch(tok2, ":"); justbreak = true; firstcase = false; - } - else if (tok2->str() == "{") - { + } else if (tok2->str() == "{") { scopenest.push(tok2->link()); - } - else if (tok2->str() == "}") - { - if (!ifnest.empty() && tok2 == ifnest.top().first) - { - if (tok2->next()->str() == "else") - { + } else if (tok2->str() == "}") { + if (!ifnest.empty() && tok2 == ifnest.top().first) { + if (tok2->next()->str() == "else") { tok2 = tok2->tokAt(2); ifnest.pop(); - if (tok2->link() == NULL) - { + if (tok2->link() == NULL) { std::ostringstream errmsg; errmsg << "unmatched if in switch: " << tok2->linenr(); reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str()); @@ -707,25 +622,16 @@ void CheckOther::checkSwitchCaseFallThrough() } ifnest.push(std::make_pair(tok2->link(), justbreak)); justbreak = false; - } - else - { + } else { justbreak &= ifnest.top().second; ifnest.pop(); } - } - else if (!loopnest.empty() && tok2 == loopnest.top()) - { + } else if (!loopnest.empty() && tok2 == loopnest.top()) { loopnest.pop(); - } - else if (!scopenest.empty() && tok2 == scopenest.top()) - { + } else if (!scopenest.empty() && tok2 == scopenest.top()) { scopenest.pop(); - } - else - { - if (!ifnest.empty() || !loopnest.empty() || !scopenest.empty()) - { + } else { + if (!ifnest.empty() || !loopnest.empty() || !scopenest.empty()) { std::ostringstream errmsg; errmsg << "unexpected end of switch: "; errmsg << "ifnest=" << ifnest.size(); @@ -742,9 +648,7 @@ void CheckOther::checkSwitchCaseFallThrough() // end of switch block break; } - } - else if (tok2->str() != ";") - { + } else if (tok2->str() != ";") { justbreak = false; } @@ -773,28 +677,24 @@ void CheckOther::checkSelfAssignment() // POD variables.. std::set pod; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->isStandardType() && Token::Match(tok->tokAt(2), "[,);]") && tok->next()->varId()) pod.insert(tok->next()->varId()); } const char selfAssignmentPattern[] = "%var% = %var% ;|=|)"; const Token *tok = Token::findmatch(_tokenizer->tokens(), selfAssignmentPattern); - while (tok) - { + while (tok) { if (Token::Match(tok->previous(), "[;{}]") && tok->varId() && tok->varId() == tok->tokAt(2)->varId() && - pod.find(tok->varId()) != pod.end()) - { + pod.find(tok->varId()) != pod.end()) { bool err = true; // no false positive for 'x = x ? x : 1;' // it is simplified to 'if (x) { x=x; } else { x=1; }'. The simplification // always write all tokens on 1 line (even if the statement is several lines), so // check if the linenr is the same for all the tokens. - if (Token::Match(tok->tokAt(-2), ") { %var% = %var% ; } else { %varid% =", tok->varId())) - { + if (Token::Match(tok->tokAt(-2), ") { %var% = %var% ; } else { %varid% =", tok->varId())) { // Find the 'if' token const Token *tokif = tok->tokAt(-2)->link()->previous(); @@ -832,15 +732,11 @@ void CheckOther::checkAssignmentInAssert() const Token *tok = Token::findmatch(_tokenizer->tokens(), assertPattern); const Token *endTok = tok ? tok->next()->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { const Token* varTok = Token::findmatch(tok->tokAt(2), "%var% --|++|+=|-=|*=|/=|&=|^=|=", endTok); - if (varTok) - { + if (varTok) { assignmentInAssertError(tok, varTok->str()); - } - else if (NULL != (varTok = Token::findmatch(tok->tokAt(2), "--|++ %var%", endTok))) - { + } else if (NULL != (varTok = Token::findmatch(tok->tokAt(2), "--|++ %var%", endTok))) { assignmentInAssertError(tok, varTok->strAt(1)); } @@ -884,24 +780,20 @@ void CheckOther::checkIncorrectLogicOperator() const Token *tok = Token::findmatch(_tokenizer->tokens(), conditionPattern); const Token *endTok = tok ? tok->next()->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { // Find a pair of comparison expressions with or without parenthesis // with a shared variable and constants and with a logical operator between them. // e.g. if (x != 3 || x != 4) const Token *logicTok = NULL, *term1Tok = NULL, *term2Tok = NULL; const Token *op1Tok = NULL, *op2Tok = NULL, *op3Tok = NULL, *nextTok = NULL; - if (NULL != (logicTok = Token::findmatch(tok, "( %any% !=|==|<|>|>=|<= %any% ) &&|%oror% ( %any% !=|==|<|>|>=|<= %any% ) %any%", endTok))) - { + if (NULL != (logicTok = Token::findmatch(tok, "( %any% !=|==|<|>|>=|<= %any% ) &&|%oror% ( %any% !=|==|<|>|>=|<= %any% ) %any%", endTok))) { term1Tok = logicTok->next(); term2Tok = logicTok->tokAt(7); op1Tok = logicTok->tokAt(2); op2Tok = logicTok->tokAt(5); op3Tok = logicTok->tokAt(8); nextTok = logicTok->tokAt(11); - } - else if (NULL != (logicTok = Token::findmatch(tok, "%any% !=|==|<|>|>=|<= %any% &&|%oror% %any% !=|==|<|>|>=|<= %any% %any%", endTok))) - { + } else if (NULL != (logicTok = Token::findmatch(tok, "%any% !=|==|<|>|>=|<= %any% &&|%oror% %any% !=|==|<|>|>=|<= %any% %any%", endTok))) { term1Tok = logicTok; term2Tok = logicTok->tokAt(4); op1Tok = logicTok->tokAt(1); @@ -910,52 +802,42 @@ void CheckOther::checkIncorrectLogicOperator() nextTok = logicTok->tokAt(7); } - if (logicTok) - { + if (logicTok) { // Find the common variable and the two different-valued constants unsigned int variableTested = 0; std::string firstConstant, secondConstant; bool varFirst1, varFirst2; unsigned int varId; const Token *varTok = NULL; - if (Token::Match(term1Tok, "%var% %any% %num%")) - { + if (Token::Match(term1Tok, "%var% %any% %num%")) { varTok = term1Tok; varId = varTok->varId(); - if (!varId) - { + if (!varId) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } varFirst1 = true; firstConstant = term1Tok->tokAt(2)->str(); - } - else if (Token::Match(term1Tok, "%num% %any% %var%")) - { + } else if (Token::Match(term1Tok, "%num% %any% %var%")) { varTok = term1Tok->tokAt(2); varId = varTok->varId(); - if (!varId) - { + if (!varId) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } varFirst1 = false; firstConstant = term1Tok->str(); - } - else - { + } else { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } - if (Token::Match(term2Tok, "%var% %any% %num%")) - { + if (Token::Match(term2Tok, "%var% %any% %num%")) { const unsigned int varId2 = term2Tok->varId(); - if (!varId2 || varId != varId2) - { + if (!varId2 || varId != varId2) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -963,12 +845,9 @@ void CheckOther::checkIncorrectLogicOperator() varFirst2 = true; secondConstant = term2Tok->tokAt(2)->str(); variableTested = varId; - } - else if (Token::Match(term2Tok, "%num% %any% %var%")) - { + } else if (Token::Match(term2Tok, "%num% %any% %var%")) { const unsigned int varId2 = term1Tok->tokAt(2)->varId(); - if (!varId2 || varId != varId2) - { + if (!varId2 || varId != varId2) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -976,16 +855,13 @@ void CheckOther::checkIncorrectLogicOperator() varFirst2 = false; secondConstant = term2Tok->str(); variableTested = varId; - } - else - { + } else { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; } - if (variableTested == 0 || firstConstant.empty() || secondConstant.empty()) - { + if (variableTested == 0 || firstConstant.empty() || secondConstant.empty()) { tok = Token::findmatch(endTok->next(), conditionPattern); endTok = tok ? tok->next()->link() : NULL; continue; @@ -994,8 +870,7 @@ void CheckOther::checkIncorrectLogicOperator() enum Position { First, Second, NA }; enum Relation { Equal, NotEqual, Less, LessEqual, More, MoreEqual }; enum LogicError { Exclusion, AlwaysTrue, AlwaysFalse, AlwaysFalseOr }; - struct Condition - { + struct Condition { const char *before; Position position1; const char *op1TokStr; @@ -1005,8 +880,7 @@ void CheckOther::checkIncorrectLogicOperator() const char *after; Relation relation; LogicError error; - } conditions[] = - { + } conditions[] = { { "!!&&", NA, "!=", "||", NA, "!=", "!!&&", NotEqual, Exclusion }, // (x != 1) || (x != 3) <- always true { "(", NA, "==", "&&", NA, "==", ")", NotEqual, AlwaysFalseOr }, // (x == 1) && (x == 3) <- always false { "(", First, "<", "&&", First, ">", ")", LessEqual, AlwaysFalseOr }, // (x < 1) && (x > 3) <- always false @@ -1031,8 +905,7 @@ void CheckOther::checkIncorrectLogicOperator() { "(", Second, "<", "&&", NA, "==", ")", More, AlwaysFalse }, // (5 < x) && (x == 1) <- second expression always false }; - for (unsigned int i = 0; i < (sizeof(conditions) / sizeof(conditions[0])); i++) - { + for (unsigned int i = 0; i < (sizeof(conditions) / sizeof(conditions[0])); i++) { if (!((conditions[i].position1 == NA) || (((conditions[i].position1 == First) && varFirst1) || ((conditions[i].position1 == Second) && !varFirst1)))) continue; @@ -1059,12 +932,10 @@ void CheckOther::checkIncorrectLogicOperator() (conditions[i].relation == Less && MathLib::isLess(firstConstant, secondConstant)) || (conditions[i].relation == LessEqual && MathLib::isLessEqual(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))) { if (conditions[i].error == Exclusion || conditions[i].error == AlwaysFalseOr) incorrectLogicOperatorError(term1Tok, conditions[i].error == Exclusion); - else - { + else { std::string text("When " + varTok->str() + " is greater than " + firstConstant + ", the comparison " + varTok->str() + " " + conditions[i].op3TokStr + " " + secondConstant + " is always " + (conditions[i].error == AlwaysTrue ? "true." : "false.")); @@ -1106,13 +977,11 @@ void CheckOther::checkCatchExceptionByValue() const Token *tok = Token::findmatch(_tokenizer->tokens(), catchPattern); const Token *endTok = tok ? tok->tokAt(2)->link() : NULL; - while (tok && endTok) - { + while (tok && endTok) { // Find a pass-by-value declaration in the catch(), excluding basic types // e.g. catch (std::exception err) const Token *tokType = Token::findmatch(tok, "%type% %var% )", endTok); - if (tokType && !tokType->isStandardType()) - { + if (tokType && !tokType->isStandardType()) { catchExceptionByValueError(tokType); } @@ -1135,29 +1004,23 @@ void CheckOther::catchExceptionByValueError(const Token *tok) void CheckOther::invalidFunctionUsage() { // strtol and strtoul.. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (!Token::Match(tok, "strtol|strtoul (")) continue; // Locate the third parameter of the function call.. int param = 1; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); else if (tok2->str() == ")") break; - else if (tok2->str() == ",") - { + else if (tok2->str() == ",") { ++param; - if (param == 3) - { - if (Token::Match(tok2, ", %num% )")) - { + if (param == 3) { + if (Token::Match(tok2, ", %num% )")) { const MathLib::bigint radix = MathLib::toLongNumber(tok2->next()->str()); - if (!(radix == 0 || (radix >= 2 && radix <= 36))) - { + if (!(radix == 0 || (radix >= 2 && radix <= 36))) { dangerousUsageStrtolError(tok2); } } @@ -1168,8 +1031,7 @@ void CheckOther::invalidFunctionUsage() } // sprintf|snprintf overlapping data - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Get variable id of target buffer.. unsigned int varid = 0; @@ -1191,18 +1053,14 @@ void CheckOther::invalidFunctionUsage() // is any source buffer overlapping the target buffer? int parlevel = 0; - while ((tok2 = tok2->next()) != NULL) - { + while ((tok2 = tok2->next()) != NULL) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { --parlevel; if (parlevel < 0) break; - } - else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) - { + } else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) { sprintfOverlappingDataError(tok2->next(), tok2->next()->str()); break; } @@ -1232,8 +1090,7 @@ void CheckOther::invalidScanf() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { const Token *formatToken = 0; if (Token::Match(tok, "scanf|vscanf ( %str% ,")) formatToken = tok->tokAt(2); @@ -1246,21 +1103,18 @@ void CheckOther::invalidScanf() // scan the string backwards, so we dont need to keep states const std::string &formatstr(formatToken->str()); - for (unsigned int i = 1; i < formatstr.length(); i++) - { + for (unsigned int i = 1; i < formatstr.length(); i++) { if (formatstr[i] == '%') format = !format; else if (!format) continue; - else if (std::isdigit(formatstr[i])) - { + else if (std::isdigit(formatstr[i])) { format = false; } - else if (std::isalpha(formatstr[i])) - { + else if (std::isalpha(formatstr[i])) { invalidScanfError(tok); format = false; } @@ -1300,83 +1154,60 @@ void CheckOther::checkComparisonOfBoolWithInt() return; std::map boolvars; // Contains all declarated standard type variables and indicates whether its a bool or not. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]") && tok->tokAt(1)->isStandardType()) // Declaration of standard type variable - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]") && tok->tokAt(1)->isStandardType()) { // Declaration of standard type variable boolvars[tok->tokAt(2)->varId()] = (tok->tokAt(1)->str() == "bool"); - } - else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< %num%")) // Comparing variable with number - { + } else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< %num%")) { // Comparing variable with number const Token *varTok = tok; const Token *numTok = tok->tokAt(2); std::map::const_iterator iVar = boolvars.find(varTok->varId()); if (iVar != boolvars.end() && iVar->second && // Variable has to be a boolean ((tok->tokAt(1)->str() != "==" && tok->tokAt(1)->str() != "!=") || - ((MathLib::toLongNumber(numTok->str()) != 0) && (!code_is_c() || MathLib::toLongNumber(numTok->str()) != 1)))) // == 0 and != 0 are allowed, for C also == 1 and != 1 - { + ((MathLib::toLongNumber(numTok->str()) != 0) && (!code_is_c() || MathLib::toLongNumber(numTok->str()) != 1)))) { // == 0 and != 0 are allowed, for C also == 1 and != 1 comparisonOfBoolWithIntError(varTok, numTok->str()); } - } - else if (Token::Match(tok, "%num% >|>=|==|!=|<=|< %var%")) // Comparing number with variable - { + } else if (Token::Match(tok, "%num% >|>=|==|!=|<=|< %var%")) { // Comparing number with variable const Token *varTok = tok->tokAt(2); const Token *numTok = tok; std::map::const_iterator iVar = boolvars.find(varTok->varId()); if (iVar != boolvars.end() && iVar->second && // Variable has to be a boolean ((tok->tokAt(1)->str() != "==" && tok->tokAt(1)->str() != "!=") || - ((MathLib::toLongNumber(numTok->str()) != 0) && (!code_is_c() || MathLib::toLongNumber(numTok->str()) != 1)))) // == 0 and != 0 are allowed, for C also == 1 and != 1 - { + ((MathLib::toLongNumber(numTok->str()) != 0) && (!code_is_c() || MathLib::toLongNumber(numTok->str()) != 1)))) { // == 0 and != 0 are allowed, for C also == 1 and != 1 comparisonOfBoolWithIntError(varTok, numTok->str()); } - } - else if (Token::Match(tok, "true|false >|>=|==|!=|<=|< %var%")) // Comparing boolean constant with variable - { + } else if (Token::Match(tok, "true|false >|>=|==|!=|<=|< %var%")) { // Comparing boolean constant with variable const Token *varTok = tok->tokAt(2); const Token *constTok = tok; std::map::const_iterator iVar = boolvars.find(varTok->varId()); - if (iVar != boolvars.end() && !iVar->second) // Variable has to be of non-boolean standard type - { + if (iVar != boolvars.end() && !iVar->second) { // Variable has to be of non-boolean standard type comparisonOfBoolWithIntError(varTok, constTok->str()); } - } - else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< true|false")) // Comparing variable with boolean constant - { + } else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< true|false")) { // Comparing variable with boolean constant const Token *varTok = tok; const Token *constTok = tok->tokAt(2); std::map::const_iterator iVar = boolvars.find(varTok->varId()); - if (iVar != boolvars.end() && !iVar->second) // Variable has to be of non-boolean standard type - { + if (iVar != boolvars.end() && !iVar->second) { // Variable has to be of non-boolean standard type comparisonOfBoolWithIntError(varTok, constTok->str()); } - } - else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< %var%")) // Comparing two variables, one of them boolean, one of them integer - { + } else if (Token::Match(tok, "%var% >|>=|==|!=|<=|< %var%")) { // Comparing two variables, one of them boolean, one of them integer const Token *var1Tok = tok->tokAt(2); const Token *var2Tok = tok; std::map::const_iterator iVar1 = boolvars.find(var1Tok->varId()); std::map::const_iterator iVar2 = boolvars.find(var2Tok->varId()); - if (iVar1 != boolvars.end() && iVar2 != boolvars.end()) - { + if (iVar1 != boolvars.end() && iVar2 != boolvars.end()) { if (iVar1->second && !iVar2->second) // Comparing boolean with non-bool standard type comparisonOfBoolWithIntError(var2Tok, var1Tok->str()); else if (!iVar1->second && iVar2->second) // Comparing non-bool standard type with boolean comparisonOfBoolWithIntError(var2Tok, var2Tok->str()); } - } - else if (Token::Match(tok, "( ! %var% ==|!= %num% )")) - { + } else if (Token::Match(tok, "( ! %var% ==|!= %num% )")) { const Token *numTok = tok->tokAt(4); - if (numTok && numTok->str() != "0") - { + if (numTok && numTok->str() != "0") { comparisonOfBoolWithIntError(numTok, "!"+tok->strAt(2)); } - } - else if (Token::Match(tok, "( %num% ==|!= ! %var% )")) - { + } else if (Token::Match(tok, "( %num% ==|!= ! %var% )")) { const Token *numTok = tok->tokAt(1); - if (numTok && numTok->str() != "0") - { + if (numTok && numTok->str() != "0") { comparisonOfBoolWithIntError(numTok, "!"+tok->strAt(4)); } } @@ -1411,8 +1242,7 @@ void CheckOther::checkDuplicateBreak() // Find consecutive break or continue statements. e.g.: // break; break; const Token *tok = Token::findmatch(_tokenizer->tokens(), breakPattern); - while (tok) - { + while (tok) { duplicateBreakError(tok); tok = Token::findmatch(tok->next(), breakPattern); } @@ -1435,35 +1265,27 @@ void CheckOther::checkUnsignedDivision() // Check for "ivar / uvar" and "uvar / ivar" std::map varsign; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) { if (tok->tokAt(1)->isUnsigned()) varsign[tok->tokAt(2)->varId()] = 'u'; else varsign[tok->tokAt(2)->varId()] = 's'; } - else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) - { - if (tok->strAt(3)[0] == '-') - { + else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) { + if (tok->strAt(3)[0] == '-') { char sign1 = varsign[tok->tokAt(1)->varId()]; - if (sign1 == 'u') - { + if (sign1 == 'u') { udivError(tok->next()); } } } - else if (Token::Match(tok, "(|[|=|%op% %num% / %var%")) - { - if (tok->strAt(1)[0] == '-') - { + else if (Token::Match(tok, "(|[|=|%op% %num% / %var%")) { + if (tok->strAt(1)[0] == '-') { char sign2 = varsign[tok->tokAt(3)->varId()]; - if (sign2 == 'u') - { + if (sign2 == 'u') { udivError(tok->next()); } } @@ -1482,8 +1304,7 @@ void CheckOther::udivError(const Token *tok) void CheckOther::checkMemsetZeroBytes() { const Token *tok = _tokenizer->tokens(); - while (tok && ((tok = Token::findmatch(tok, "memset ( %var% , %num% , 0 )")) != NULL)) - { + while (tok && ((tok = Token::findmatch(tok, "memset ( %var% , %num% , 0 )")) != NULL)) { memsetZeroBytesError(tok, tok->strAt(2)); tok = tok->tokAt(8); } @@ -1508,28 +1329,22 @@ void CheckOther::checkVariableScope() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // Walk through all tokens.. int indentlevel = 0; - for (const Token *tok = scope->classStart; tok; tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok; tok = tok->next()) { // Skip function local class and struct declarations.. - if ((tok->str() == "class") || (tok->str() == "struct") || (tok->str() == "union")) - { - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + if ((tok->str() == "class") || (tok->str() == "struct") || (tok->str() == "union")) { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { tok = tok2->link(); break; } - if (Token::Match(tok2, "[,);]")) - { + if (Token::Match(tok2, "[,);]")) { break; } } @@ -1537,19 +1352,15 @@ void CheckOther::checkVariableScope() break; } - else if (tok->str() == "{") - { + else if (tok->str() == "{") { ++indentlevel; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --indentlevel; if (indentlevel == 0) break;; } - if (indentlevel > 0 && Token::Match(tok, "[{};]")) - { + if (indentlevel > 0 && Token::Match(tok, "[{};]")) { // First token of statement.. const Token *tok1 = tok->next(); if (! tok1) @@ -1563,20 +1374,16 @@ void CheckOther::checkVariableScope() continue; // Variable declaration? - if (Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) - { + if (Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) { // Tokenizer modify "int i = 0;" to "int i; i = 0;", // so to handle this situation we just skip // initialization (see ticket #272). const unsigned int firstVarId = tok1->next()->varId(); const unsigned int secondVarId = tok1->tokAt(3)->varId(); - if (firstVarId > 0 && firstVarId == secondVarId) - { + if (firstVarId > 0 && firstVarId == secondVarId) { lookupVar(tok1->tokAt(6), tok1->strAt(1)); } - } - else if (tok1->isStandardType() && Token::Match(tok1, "%type% %var% [;=]")) - { + } else if (tok1->isStandardType() && Token::Match(tok1, "%type% %var% [;=]")) { lookupVar(tok1, tok1->strAt(1)); } } @@ -1598,30 +1405,23 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) int indentlevel = 0; int parlevel = 0; bool for_or_while = false; // is sub-scope a "for/while/etc". anything that is not "if" - while (tok) - { - if (tok->str() == "{") - { - if (tok->strAt(-1) == "=") - { - if (Token::findmatch(tok, varname.c_str(), tok->link())) - { + while (tok) { + if (tok->str() == "{") { + if (tok->strAt(-1) == "=") { + if (Token::findmatch(tok, varname.c_str(), tok->link())) { return; } tok = tok->link(); - } - else + } else ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel == 0) break; --indentlevel; - if (indentlevel == 0) - { + if (indentlevel == 0) { if (for_or_while && used2) return; used2 |= used1; @@ -1629,24 +1429,20 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) } } - else if (tok->str() == "(") - { + else if (tok->str() == "(") { ++parlevel; } - else if (tok->str() == ")") - { + else if (tok->str() == ")") { --parlevel; } // Bail out if references are used - else if (Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) - { + else if (Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) { return; } - else if (tok->str() == varname) - { + else if (tok->str() == varname) { if (indentlevel == 0) return; used1 = true; @@ -1656,14 +1452,12 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) return; } - else if (indentlevel == 0) - { + else if (indentlevel == 0) { // %unknown% ( %any% ) { // If %unknown% is anything except if, we assume // that it is a for or while loop or a macro hiding either one if (Token::simpleMatch(tok->next(), "(") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + Token::simpleMatch(tok->next()->link(), ") {")) { if (tok->str() != "if") for_or_while = true; } @@ -1672,8 +1466,7 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) for_or_while = true; // possible unexpanded macro hiding for/while.. - else if (tok->str() != "else" && Token::Match(tok->previous(), "[;{}] %type% {")) - { + else if (tok->str() != "else" && Token::Match(tok->previous(), "[;{}] %type% {")) { for_or_while = true; } @@ -1724,53 +1517,43 @@ void CheckOther::checkConstantFunctionParameter() const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // TODO: False negatives. This pattern only checks for string. // Investigate if there are other classes in the std // namespace and add them to the pattern. There are // streams for example (however it seems strange with // const stream parameter). - if (Token::Match(tok, "[,(] const std :: string %var% [,)]")) - { + if (Token::Match(tok, "[,(] const std :: string %var% [,)]")) { passedByValueError(tok, tok->strAt(5)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(8)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(14)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if (Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if (Token::Match(tok, "[,(] const %type% %var% [,)]")) - { + else if (Token::Match(tok, "[,(] const %type% %var% [,)]")) { // Check if type is a struct or class. - if (symbolDatabase->isClassOrStruct(tok->strAt(2))) - { + if (symbolDatabase->isClassOrStruct(tok->strAt(2))) { passedByValueError(tok, tok->strAt(3)); } } @@ -1795,12 +1578,10 @@ void CheckOther::checkCharVariable() const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring the variable.. if (Token::Match(tok, "[{};(,] const| char *| %var% [;=,)]") || - Token::Match(tok, "[{};(,] const| char %var% [")) - { + Token::Match(tok, "[{};(,] const| char %var% [")) { // goto 'char' token tok = tok->next(); if (tok->str() == "const") @@ -1818,37 +1599,31 @@ void CheckOther::checkCharVariable() // Check usage of char variable.. int indentlevel = 0; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { --indentlevel; if (indentlevel <= 0) break; } - if (!isPointer) - { + if (!isPointer) { std::string temp = "%var% [ " + tok->str() + " ]"; - if ((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) - { + if ((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) { charArrayIndexError(tok2->next()); break; } } - if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) - { + if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) { // is the char variable used in the calculation? if (tok2->tokAt(3)->varId() != tok->varId() && tok2->tokAt(5)->varId() != tok->varId()) continue; // it's ok with a bitwise and where the other operand is 0xff or less.. - if (tok2->strAt(4) == "&") - { + if (tok2->strAt(4) == "&") { if (tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) continue; if (tok2->tokAt(5)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(5))) @@ -1865,8 +1640,7 @@ void CheckOther::checkCharVariable() break; } - if (isPointer && Token::Match(tok2, "[;{}] %var% = %any% [&|] ( * %varid% ) ;", tok->varId())) - { + if (isPointer && Token::Match(tok2, "[;{}] %var% = %any% [&|] ( * %varid% ) ;", tok->varId())) { // it's ok with a bitwise and where the other operand is 0xff or less.. if (tok2->strAt(4) == "&" && tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) continue; @@ -1918,10 +1692,8 @@ void CheckOther::checkIncompleteStatement() if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (tok->str() == "(") - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (tok->str() == "(") { tok = tok->link(); if (Token::simpleMatch(tok, ") {") && Token::simpleMatch(tok->next()->link(), "} ;")) tok = tok->next()->link(); @@ -1933,12 +1705,10 @@ void CheckOther::checkIncompleteStatement() else if (tok->str() == "{" && Token::Match(tok->tokAt(-2), "%type% %var%")) tok = tok->link(); - else if (Token::Match(tok, "[;{}] %str%") || Token::Match(tok, "[;{}] %num% !!.")) - { + else if (Token::Match(tok, "[;{}] %str%") || Token::Match(tok, "[;{}] %num% !!.")) { // bailout if there is a "? :" in this statement bool bailout = false; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "?") bailout = true; else if (tok2->str() == ";") @@ -1963,26 +1733,22 @@ void CheckOther::constStatementError(const Token *tok, const std::string &type) void CheckOther::strPlusChar() { // Don't use this check for Java and C# programs.. - if (_tokenizer->isJavaOrCSharp()) - { + if (_tokenizer->isJavaOrCSharp()) { return; } bool charVars[10000] = {0}; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring char variable.. - if (Token::Match(tok, "char|int|short %var% [;=]")) - { + if (Token::Match(tok, "char|int|short %var% [;=]")) { unsigned int varid = tok->next()->varId(); if (varid > 0 && varid < 10000) charVars[varid] = true; } // - else if (Token::Match(tok, "[=(] %str% + %any%")) - { + else if (Token::Match(tok, "[=(] %str% + %any%")) { // char constant.. const std::string s = tok->strAt(3); if (s[0] == '\'') @@ -2005,18 +1771,14 @@ void CheckOther::strPlusCharError(const Token *tok) //--------------------------------------------------------------------------- void CheckOther::checkZeroDivision() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "[/%] %num%") && MathLib::isInt(tok->next()->str()) && - MathLib::toLongNumber(tok->next()->str()) == 0L) - { + MathLib::toLongNumber(tok->next()->str()) == 0L) { zerodivError(tok); - } - else if (Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && - MathLib::isInt(tok->tokAt(4)->str()) && - MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) - { + } else if (Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && + MathLib::isInt(tok->tokAt(4)->str()) && + MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) { zerodivError(tok); } } @@ -2031,15 +1793,13 @@ void CheckOther::zerodivError(const Token *tok) //--------------------------------------------------------------------------- void CheckOther::checkMathFunctions() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // case log(-2) if (tok->varId() == 0 && Token::Match(tok, "log|log10 ( %num% )") && MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) { mathfunctionCallError(tok); } // case log(-2.0) @@ -2047,8 +1807,7 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) - { + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) { mathfunctionCallError(tok); } @@ -2057,8 +1816,7 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && !MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) - { + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) { mathfunctionCallError(tok); } @@ -2067,45 +1825,39 @@ void CheckOther::checkMathFunctions() Token::Match(tok, "log|log10 ( %num% )") && !MathLib::isNegative(tok->tokAt(2)->str()) && MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) { mathfunctionCallError(tok); } // acos( x ), asin( x ) where x is defined for intervall [-1,+1], but not beyound else if (tok->varId() == 0 && Token::Match(tok, "acos|asin ( %num% )") && - std::fabs(MathLib::toDoubleNumber(tok->tokAt(2)->str())) > 1.0) - { + std::fabs(MathLib::toDoubleNumber(tok->tokAt(2)->str())) > 1.0) { mathfunctionCallError(tok); } // sqrt( x ): if x is negative the result is undefined else if (tok->varId() == 0 && Token::Match(tok, "sqrt|sqrtf|sqrtl ( %num% )") && - MathLib::isNegative(tok->tokAt(2)->str())) - { + MathLib::isNegative(tok->tokAt(2)->str())) { mathfunctionCallError(tok); } // atan2 ( x , y): x and y can not be zero, because this is mathematically not defined else if (tok->varId() == 0 && Token::Match(tok, "atan2 ( %num% , %num% )") && MathLib::isNullValue(tok->tokAt(2)->str()) && - MathLib::isNullValue(tok->tokAt(4)->str())) - { + MathLib::isNullValue(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } // fmod ( x , y) If y is zero, then either a range error will occur or the function will return zero (implementation-defined). else if (tok->varId() == 0 && Token::Match(tok, "fmod ( %num% , %num% )") && - MathLib::isNullValue(tok->tokAt(4)->str())) - { + MathLib::isNullValue(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } // pow ( x , y) If x is zero, and y is negative --> division by zero else if (tok->varId() == 0 && Token::Match(tok, "pow ( %num% , %num% )") && MathLib::isNullValue(tok->tokAt(2)->str()) && - MathLib::isNegative(tok->tokAt(4)->str())) - { + MathLib::isNegative(tok->tokAt(4)->str())) { mathfunctionCallError(tok, 2); } @@ -2114,14 +1866,12 @@ void CheckOther::checkMathFunctions() void CheckOther::mathfunctionCallError(const Token *tok, const unsigned int numParam) { - if (tok) - { + if (tok) { if (numParam == 1) reportError(tok, Severity::error, "wrongmathcall", "Passing value " + tok->tokAt(2)->str() + " to " + tok->str() + "() leads to undefined result"); else if (numParam == 2) reportError(tok, Severity::error, "wrongmathcall", "Passing value " + tok->tokAt(2)->str() + " and " + tok->tokAt(4)->str() + " to " + tok->str() + "() leads to undefined result"); - } - else + } else reportError(tok, Severity::error, "wrongmathcall", "Passing value " " to " "() leads to undefined result"); } @@ -2131,11 +1881,9 @@ void CheckOther::mathfunctionCallError(const Token *tok, const unsigned int numP static bool isFunction(const std::string &name, const Token *startToken) { const std::string pattern1(name + " ("); - for (const Token *tok = startToken; tok; tok = tok->next()) - { + for (const Token *tok = startToken; tok; tok = tok->next()) { // skip executable scopes etc - if (tok->str() == "(") - { + if (tok->str() == "(") { tok = tok->link(); if (Token::simpleMatch(tok, ") {")) tok = tok->next()->link(); @@ -2156,8 +1904,7 @@ bool CheckOther::code_is_c() const const std::string fname = _tokenizer->getFiles()->at(0); const size_t position = fname.rfind("."); - if (position != std::string::npos) - { + if (position != std::string::npos) { const std::string ext = fname.substr(position); if (ext == ".c" || ext == ".C") return true; @@ -2169,8 +1916,7 @@ bool CheckOther::code_is_c() const void CheckOther::checkMisusedScopedObject() { // Skip this check for .c files - if (code_is_c()) - { + if (code_is_c()) { return; } @@ -2178,22 +1924,17 @@ void CheckOther::checkMisusedScopedObject() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; unsigned int depth = 0; - for (const Token *tok = scope->classStart; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (const Token *tok = scope->classStart; tok; tok = tok->next()) { + if (tok->str() == "{") { ++depth; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --depth; if (depth == 0) break; @@ -2202,8 +1943,7 @@ void CheckOther::checkMisusedScopedObject() if (Token::Match(tok, "[;{}] %var% (") && Token::simpleMatch(tok->tokAt(2)->link(), ") ;") && symbolDatabase->isClassOrStruct(tok->next()->str()) - && !isFunction(tok->next()->str(), _tokenizer->tokens())) - { + && !isFunction(tok->next()->str(), _tokenizer->tokens())) { tok = tok->next(); misusedScopeObjectError(tok, tok->str()); tok = tok->next(); @@ -2222,23 +1962,18 @@ void CheckOther::misusedScopeObjectError(const Token *tok, const std::string& va //--------------------------------------------------------------------------- void CheckOther::checkIncorrectStringCompare() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, ". substr ( %any% , %num% ) ==|!= %str%")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, ". substr ( %any% , %num% ) ==|!= %str%")) { size_t clen = MathLib::toLongNumber(tok->tokAt(5)->str()); size_t slen = Token::getStrLength(tok->tokAt(8)); - if (clen != slen) - { + if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", tok->tokAt(8)->str(), tok->tokAt(5)->str()); } } - if (Token::Match(tok, "%str% ==|!= %var% . substr ( %any% , %num% )")) - { + if (Token::Match(tok, "%str% ==|!= %var% . substr ( %any% , %num% )")) { size_t clen = MathLib::toLongNumber(tok->tokAt(8)->str()); size_t slen = Token::getStrLength(tok); - if (clen != slen) - { + if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", tok->str(), tok->tokAt(8)->str()); } } @@ -2269,8 +2004,7 @@ static const std::string stringifyTokens(const Token *start, const Token *end) stringified.append(tok->str()); - while (tok && tok->next() && tok != end) - { + while (tok && tok->next() && tok != end) { if (tok->isUnsigned()) stringified.append("unsigned "); else if (tok->isSigned()) @@ -2289,8 +2023,7 @@ static const std::string stringifyTokens(const Token *start, const Token *end) static bool expressionHasSideEffects(const Token *first, const Token *last) { - for (const Token *tok = first; tok != last->next(); tok = tok->next()) - { + for (const Token *tok = first; tok != last->next(); tok = tok->next()) { // check for assignment if (tok->isAssignmentOp()) return true; @@ -2317,18 +2050,15 @@ void CheckOther::checkDuplicateIf() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function for if (...) and else if (...) statements - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::simpleMatch(tok, "if (") && tok->strAt(-1) != "else" && - Token::simpleMatch(tok->next()->link(), ") {")) - { + Token::simpleMatch(tok->next()->link(), ") {")) { std::map expressionMap; // get the expression from the token stream @@ -2342,8 +2072,7 @@ void CheckOther::checkDuplicateIf() // check all the else if (...) statements while (Token::simpleMatch(tok1, "} else if (") && - Token::simpleMatch(tok1->tokAt(3)->link(), ") {")) - { + Token::simpleMatch(tok1->tokAt(3)->link(), ") {")) { // get the expression from the token stream expression = stringifyTokens(tok1->tokAt(4), tok1->tokAt(3)->link()->previous()); @@ -2351,8 +2080,7 @@ void CheckOther::checkDuplicateIf() std::map::iterator it = expressionMap.find(expression); // found a duplicate - if (it != expressionMap.end()) - { + if (it != expressionMap.end()) { // check for expressions that have side effects and ignore them if (!expressionHasSideEffects(tok1->tokAt(4), tok1->tokAt(3)->link()->previous())) duplicateIfError(it->second, tok1->next()); @@ -2400,19 +2128,16 @@ void CheckOther::checkDuplicateBranch() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function for if (..) else - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::simpleMatch(tok, "if (") && tok->strAt(-1) != "else" && Token::simpleMatch(tok->next()->link(), ") {") && - Token::simpleMatch(tok->next()->link()->next()->link(), "} else {")) - { + Token::simpleMatch(tok->next()->link()->next()->link(), "} else {")) { // save if branch code std::string branch1 = stringifyTokens(tok->next()->link()->tokAt(2), tok->next()->link()->next()->link()->previous()); @@ -2459,33 +2184,26 @@ void CheckOther::checkDuplicateExpression() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { if (Token::Match(tok, "(|&&|%oror% %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% )|&&|%oror%") && - tok->strAt(1) == tok->strAt(3)) - { + tok->strAt(1) == tok->strAt(3)) { // float == float and float != float are valid NaN checks - if (Token::Match(tok->tokAt(2), "==|!=") && tok->next()->varId()) - { + if (Token::Match(tok->tokAt(2), "==|!=") && tok->next()->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId()); - if (var && var->typeStartToken() == var->typeEndToken()) - { + if (var && var->typeStartToken() == var->typeEndToken()) { if (Token::Match(var->typeStartToken(), "float|double")) continue; } } duplicateExpressionError(tok->next(), tok->tokAt(3), tok->strAt(2)); - } - else if (Token::Match(tok, "(|&&|%oror% %var% . %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% . %var% )|&&|%oror%") && - tok->strAt(1) == tok->strAt(5) && tok->strAt(3) == tok->strAt(7)) - { + } else if (Token::Match(tok, "(|&&|%oror% %var% . %var% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %var% . %var% )|&&|%oror%") && + tok->strAt(1) == tok->strAt(5) && tok->strAt(3) == tok->strAt(7)) { duplicateExpressionError(tok->next(), tok->tokAt(6), tok->strAt(4)); } } @@ -2517,15 +2235,13 @@ void CheckOther::checkAlwaysTrueOrFalseStringCompare() const char pattern2[] = "QString :: compare ( %str% , %str% )"; const Token *tok = _tokenizer->tokens(); - while (tok && (tok = Token::findmatch(tok, pattern1)) != NULL) - { + while (tok && (tok = Token::findmatch(tok, pattern1)) != NULL) { alwaysTrueFalseStringCompareError(tok, tok->strAt(2), tok->strAt(4)); tok = tok->tokAt(5); } tok = _tokenizer->tokens(); - while (tok && (tok = Token::findmatch(tok, pattern2)) != NULL) - { + while (tok && (tok = Token::findmatch(tok, pattern2)) != NULL) { alwaysTrueFalseStringCompareError(tok, tok->strAt(4), tok->strAt(6)); tok = tok->tokAt(7); } @@ -2537,16 +2253,13 @@ void CheckOther::alwaysTrueFalseStringCompareError(const Token *tok, const std:: const std::string string1 = (str1.size() < stringLen) ? str1 : (str1.substr(0, stringLen-2) + ".."); const std::string string2 = (str2.size() < stringLen) ? str2 : (str2.substr(0, stringLen-2) + ".."); - if (str1 == str2) - { + if (str1 == str2) { reportError(tok, Severity::warning, "staticStringCompare", "Comparison of always identical static strings.\n" "The compared strings, '" + string1 + "' and '" + string2 + "', are always identical. " "If the purpose is to compare these two strings, the comparison is unnecessary. " "If the strings are supposed to be different, then there is a bug somewhere."); - } - else if (_settings->isEnabled("performance")) - { + } else if (_settings->isEnabled("performance")) { reportError(tok, Severity::performance, "staticStringCompare", "Unnecessary comparison of static strings.\n" "The compared strings, '" + string1 + "' and '" + string2 + "', are static and always different. " @@ -2560,10 +2273,8 @@ void CheckOther::sizeofsizeof() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "sizeof (| sizeof")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "sizeof (| sizeof")) { sizeofsizeofError(tok); tok = tok->next(); } @@ -2585,23 +2296,17 @@ void CheckOther::sizeofCalculation() { if (!_settings->isEnabled("style")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "sizeof (")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "sizeof (")) { unsigned int parlevel = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel <= 1) break; --parlevel; - } - else if (Token::Match(tok2, "+|/")) - { + } else if (Token::Match(tok2, "+|/")) { sizeofCalculationError(tok2); break; } @@ -2620,10 +2325,8 @@ void CheckOther::sizeofCalculationError(const Token *tok) //----------------------------------------------------------------------------- void CheckOther::checkAssignBoolToPointer() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] %var% = %bool% ;")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] %var% = %bool% ;")) { const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const Variable *var1(symbolDatabase->getVariableFromVarId(tok->next()->varId())); @@ -2645,24 +2348,19 @@ void CheckOther::assignBoolToPointerError(const Token *tok) //----------------------------------------------------------------------------- void CheckOther::checkComparisonOfBoolExpressionWithInt() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "&&|%oror% %any% ) ==|!=|>|< %num%")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "&&|%oror% %any% ) ==|!=|>|< %num%")) { const std::string& op = tok->strAt(3); const std::string& num = tok->strAt(4); - if ((op == "<" || num != "0") && (op == ">" || num != "1")) - { + if ((op == "<" || num != "0") && (op == ">" || num != "1")) { comparisonOfBoolExpressionWithIntError(tok->next()); } } - else if (Token::Match(tok, "%num% ==|!=|>|< ( %any% &&|%oror%")) - { + else if (Token::Match(tok, "%num% ==|!=|>|< ( %any% &&|%oror%")) { const std::string& op = tok->strAt(1); const std::string& num = tok->str(); - if ((op == ">" || num != "0") && (op == "<" || num != "1")) - { + if ((op == ">" || num != "0") && (op == "<" || num != "1")) { comparisonOfBoolExpressionWithIntError(tok->next()); } } @@ -2688,35 +2386,26 @@ void CheckOther::checkSignOfUnsignedVariable() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; // check all the code in the function - for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) - { - if (Token::Match(tok, ";|(|&&|%oror% %var% <|<= 0 ;|)|&&|%oror%") && tok->next()->varId()) - { + for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next()) { + if (Token::Match(tok, ";|(|&&|%oror% %var% <|<= 0 ;|)|&&|%oror%") && tok->next()->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedLessThanZeroError(tok->next(), tok->next()->str()); - } - else if (Token::Match(tok, ";|(|&&|%oror% 0 > %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId()) - { + } else if (Token::Match(tok, ";|(|&&|%oror% 0 > %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedLessThanZeroError(tok->tokAt(3), tok->strAt(3)); - } - else if (Token::Match(tok, ";|(|&&|%oror% 0 <= %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId()) - { + } else if (Token::Match(tok, ";|(|&&|%oror% 0 <= %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedPositiveError(tok->tokAt(3), tok->strAt(3)); - } - else if (Token::Match(tok, ";|(|&&|%oror% %var% >= 0 ;|)|&&|%oror%") && tok->next()->varId()) - { + } else if (Token::Match(tok, ";|(|&&|%oror% %var% >= 0 ;|)|&&|%oror%") && tok->next()->varId()) { const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId()); if (var && var->typeEndToken()->isUnsigned()) unsignedPositiveError(tok->next(), tok->next()->str()); diff --git a/lib/checkother.h b/lib/checkother.h index a39c1e13f..97692fc37 100644 --- a/lib/checkother.h +++ b/lib/checkother.h @@ -33,8 +33,7 @@ class Token; /** @brief Various small checks */ -class CheckOther : public Check -{ +class CheckOther : public Check { public: /** @brief This constructor is used when registering the CheckClass */ CheckOther() : Check(myName()) @@ -46,8 +45,7 @@ public: { } /** @brief Run checks against the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckOther checkOther(tokenizer, settings, errorLogger); // Coding style checks @@ -76,8 +74,7 @@ public: } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckOther checkOther(tokenizer, settings, errorLogger); checkOther.clarifyCalculation(); @@ -278,8 +275,7 @@ public: void comparisonOfBoolExpressionWithIntError(const Token *tok); void SuspiciousSemicolonError(const Token *tok); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckOther c(0, settings, errorLogger); // error @@ -330,13 +326,11 @@ public: c.SuspiciousSemicolonError(0); } - std::string myName() const - { + std::string myName() const { return "Other"; } - std::string classInfo() const - { + std::string classInfo() const { return "Other checks\n" // error @@ -391,11 +385,9 @@ private: * @brief Used in warningRedundantCode() * Iterates through the %var% tokens in a fully qualified name and concatenates them. */ - std::string concatNames(const Token **tok) const - { + std::string concatNames(const Token **tok) const { std::string varname; - while (Token::Match(*tok, "%var% ::|.")) - { + while (Token::Match(*tok, "%var% ::|.")) { varname.append((*tok)->str()); varname.append((*tok)->next()->str()); *tok = (*tok)->tokAt(2); diff --git a/lib/checkpostfixoperator.cpp b/lib/checkpostfixoperator.cpp index 272d71f02..bda65b531 100644 --- a/lib/checkpostfixoperator.cpp +++ b/lib/checkpostfixoperator.cpp @@ -28,9 +28,8 @@ // Register this check class (by creating a static instance of it) -namespace -{ -CheckPostfixOperator instance; +namespace { + CheckPostfixOperator instance; } void CheckPostfixOperator::postfixOperator() @@ -45,49 +44,36 @@ void CheckPostfixOperator::postfixOperator() if (Token::Match(tok, "++|--")) tok = tok->next(); - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { bool result = false; - if (Token::Match(tok, "++|--")) - { - if (Token::Match(tok->previous()->previous(), ";|{|}") && Token::Match(tok->next(), ";|)|,")) - { + if (Token::Match(tok, "++|--")) { + if (Token::Match(tok->previous()->previous(), ";|{|}") && Token::Match(tok->next(), ";|)|,")) { result = true; - } - else if (tok->strAt(-2) == ",") - { + } else if (tok->strAt(-2) == ",") { int i(1); - while (tok->strAt(i) != ")" && tok->tokAt(i) != 0) - { - if (tok->strAt(i) == ";") - { + while (tok->strAt(i) != ")" && tok->tokAt(i) != 0) { + if (tok->strAt(i) == ";") { result = true; break; } ++i; } - } - else if (tok->strAt(-2) == "<<" && tok->strAt(1) == "<<") - { + } else if (tok->strAt(-2) == "<<" && tok->strAt(1) == "<<") { result = true; } } - if (result && tok->previous()->varId()) - { + if (result && tok->previous()->varId()) { const Variable *var = symbolDatabase->getVariableFromVarId(tok->previous()->varId()); if (!var || !Token::Match(var->typeEndToken(), "%type%")) continue; const Token *decltok = var->nameToken(); - if (Token::Match(decltok->previous(), "iterator|const_iterator|reverse_iterator|const_reverse_iterator")) - { + if (Token::Match(decltok->previous(), "iterator|const_iterator|reverse_iterator|const_reverse_iterator")) { // the variable is an iterator postfixOperatorError(tok); - } - else if (var->type()) - { + } else if (var->type()) { // the variable is an instance of class postfixOperatorError(tok); } diff --git a/lib/checkpostfixoperator.h b/lib/checkpostfixoperator.h index e7e4651fb..5ab06e775 100644 --- a/lib/checkpostfixoperator.h +++ b/lib/checkpostfixoperator.h @@ -31,8 +31,7 @@ * @brief Using postfix operators ++ or -- rather than postfix operator. */ -class CheckPostfixOperator : public Check -{ +class CheckPostfixOperator : public Check { public: /** This constructor is used when registering the CheckPostfixOperator */ CheckPostfixOperator() : Check(myName()) @@ -43,8 +42,7 @@ public: : Check(myName(), tokenizer, settings, errorLogger) { } - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckPostfixOperator checkPostfixOperator(tokenizer, settings, errorLogger); checkPostfixOperator.postfixOperator(); } @@ -56,19 +54,16 @@ private: /** Report Error */ void postfixOperatorError(const Token *tok); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckPostfixOperator c(0, settings, errorLogger); c.postfixOperatorError(0); } - std::string myName() const - { + std::string myName() const { return "Using postfix operators"; } - std::string classInfo() const - { + std::string classInfo() const { return "Warn if using postfix operators ++ or -- rather than prefix operator\n"; } }; diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index 39cab32b2..b772e7218 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -22,9 +22,8 @@ #include // Register this check class (by creating a static instance of it) -namespace -{ -CheckStl instance; +namespace { + CheckStl instance; } @@ -49,8 +48,7 @@ void CheckStl::iterators() { // Using same iterator against different containers. // for (it = foo.begin(); it != bar.end(); ++it) - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Locate an iterator.. if (!Token::Match(tok, "%var% = %var% . begin ( ) ;|+")) continue; @@ -69,8 +67,7 @@ void CheckStl::iterators() // Scan through the rest of the code and see if the iterator is // used against other containers. - for (const Token *tok2 = tok->tokAt(7); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(7); tok2; tok2 = tok2->next()) { // If a { is found then count it and continue if (tok2->str() == "{" && ++indent) continue; @@ -80,26 +77,22 @@ void CheckStl::iterators() break; // Is iterator compared against different container? - if (Token::Match(tok2, "%varid% != %var% . end ( )", iteratorId) && tok2->tokAt(2)->varId() != containerId) - { + if (Token::Match(tok2, "%varid% != %var% . end ( )", iteratorId) && tok2->tokAt(2)->varId() != containerId) { iteratorsError(tok2, tok->strAt(2), tok2->strAt(2)); tok2 = tok2->tokAt(6); } // Is the iterator used in a insert/erase operation? - else if (Token::Match(tok2, "%var% . insert|erase ( %varid% )|,", iteratorId)) - { + else if (Token::Match(tok2, "%var% . insert|erase ( %varid% )|,", iteratorId)) { // It is bad to insert/erase an invalid iterator if (!validIterator) invalidIteratorError(tok2, tok2->strAt(4)); // If insert/erase is used on different container then // report an error - if (tok2->varId() != containerId && tok2->tokAt(5)->str() != ".") - { + if (tok2->varId() != containerId && tok2->tokAt(5)->str() != ".") { // skip error message if container is a set.. - if (tok2->varId() > 0) - { + if (tok2->varId() > 0) { const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const Variable *variableInfo = symbolDatabase->getVariableFromVarId(tok2->varId()); const Token *decltok = variableInfo ? variableInfo->typeStartToken() : NULL; @@ -122,8 +115,7 @@ void CheckStl::iterators() // it = foo.erase(.. // taking the result of an erase is ok - else if (Token::Match(tok2, "%varid% = %var% . erase (", iteratorId)) - { + else if (Token::Match(tok2, "%varid% = %var% . erase (", iteratorId)) { // the returned iterator is valid validIterator = true; @@ -134,8 +126,7 @@ void CheckStl::iterators() } // Reassign the iterator - else if (Token::Match(tok2, "%varid% = %var% ;", iteratorId)) - { + else if (Token::Match(tok2, "%varid% = %var% ;", iteratorId)) { // Assume that the iterator becomes valid. // TODO: add checking that checks if the iterator becomes valid or not validIterator = true; @@ -145,32 +136,25 @@ void CheckStl::iterators() } // Dereferencing invalid iterator? - else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) - { + else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) { dereferenceErasedError(tok2, tok2->strAt(1)); tok2 = tok2->next(); - } - else if (!validIterator && Token::Match(tok2, "%varid% . %var%", iteratorId)) - { + } else if (!validIterator && Token::Match(tok2, "%varid% . %var%", iteratorId)) { dereferenceErasedError(tok2, tok2->strAt(0)); tok2 = tok2->tokAt(2); - } - else if (Token::Match(tok2, "%var% . erase ( * %varid%", iteratorId) && tok2->varId() == containerId) - { + } else if (Token::Match(tok2, "%var% . erase ( * %varid%", iteratorId) && tok2->varId() == containerId) { // eraseByValueError(tok2, tok2->strAt(0), tok2->strAt(5)); } // bailout handling. Assume that the iterator becomes valid if we see return/break. // TODO: better handling - else if (Token::Match(tok2, "return|break")) - { + else if (Token::Match(tok2, "return|break")) { validIterator = true; } // bailout handling. Assume that the iterator becomes valid if we see else. // TODO: better handling - else if (tok2->str() == "else") - { + else if (tok2->str() == "else") { validIterator = true; } } @@ -187,16 +171,13 @@ void CheckStl::mismatchingContainersError(const Token *tok) void CheckStl::mismatchingContainers() { // Check if different containers are used in various calls of standard functions - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() != "std") continue; // TODO: If iterator variables are used instead then there are false negatives. - if (Token::Match(tok, "std :: find|find_if|count|transform|replace|replace_if|sort ( %var% . begin|rbegin ( ) , %var% . end|rend ( ) ,")) - { - if (tok->tokAt(4)->str() != tok->tokAt(10)->str()) - { + if (Token::Match(tok, "std :: find|find_if|count|transform|replace|replace_if|sort ( %var% . begin|rbegin ( ) , %var% . end|rend ( ) ,")) { + if (tok->tokAt(4)->str() != tok->tokAt(10)->str()) { mismatchingContainersError(tok); } } @@ -207,29 +188,25 @@ void CheckStl::mismatchingContainers() void CheckStl::stlOutOfBounds() { // Scan through all tokens.. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // only interested in "for" loops if (!Token::simpleMatch(tok, "for (")) continue; // check if the for loop condition is wrong unsigned int indent = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++indent; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (indent == 0) break; --indent; } - if (Token::Match(tok2, "; %var% <= %var% . size ( ) ;")) - { + if (Token::Match(tok2, "; %var% <= %var% . size ( ) ;")) { // Count { and } for tok3 unsigned int indent3 = 0; @@ -239,18 +216,14 @@ void CheckStl::stlOutOfBounds() // variable id for the container variable unsigned int varId = tok2->tokAt(3)->varId(); - for (const Token *tok3 = tok2->tokAt(8); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(8); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indent3; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indent3 <= 1) break; --indent3; - } - else if (tok3->varId() == varId) - { + } else if (tok3->varId() == varId) { if (Token::simpleMatch(tok3->next(), ". size ( )")) break; else if (Token::Match(tok3->next(), "[ %varid% ]", numId)) @@ -273,17 +246,14 @@ void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, con /** * @brief %Check for invalid iterator usage after erase/insert/etc */ -class EraseCheckLoop : public ExecutionPath -{ +class EraseCheckLoop : public ExecutionPath { public: - static void checkScope(CheckStl *checkStl, const Token *it) - { + static void checkScope(CheckStl *checkStl, const Token *it) { const Token *tok = it; // Search for the start of the loop body.. int indentlevel = 1; - while (indentlevel > 0 && 0 != (tok = tok->next())) - { + while (indentlevel > 0 && 0 != (tok = tok->next())) { if (tok->str() == "(") tok = tok->link(); else if (tok->str() == ")") @@ -304,8 +274,7 @@ public: c.end(checks, tok->link()); - while (!checks.empty()) - { + while (!checks.empty()) { delete checks.back(); checks.pop_back(); } @@ -314,22 +283,19 @@ public: private: /** Startup constructor */ EraseCheckLoop(Check *o, unsigned int varid) - : ExecutionPath(o, varid), eraseToken(0) - { + : ExecutionPath(o, varid), eraseToken(0) { } /** @brief token where iterator is erased (non-zero => the iterator is invalid) */ const Token *eraseToken; /** @brief Copy this check. Called from the ExecutionPath baseclass. */ - ExecutionPath *copy() - { + ExecutionPath *copy() { return new EraseCheckLoop(*this); } /** @brief is another execution path equal? */ - bool is_equal(const ExecutionPath *e) const - { + bool is_equal(const ExecutionPath *e) const { const EraseCheckLoop *c = static_cast(e); return (eraseToken == c->eraseToken); } @@ -338,29 +304,24 @@ private: void operator=(const EraseCheckLoop &); /** @brief parse tokens */ - const Token *parse(const Token &tok, std::list &checks) const - { + const Token *parse(const Token &tok, std::list &checks) const { // bail out if there are assignments. We don't check the assignments properly. - if (Token::Match(&tok, "[;{}] %var% =") || Token::Match(&tok, "= %var% ;")) - { + if (Token::Match(&tok, "[;{}] %var% =") || Token::Match(&tok, "= %var% ;")) { ExecutionPath::bailOutVar(checks, tok.next()->varId()); } // the loop stops here. Bail out all execution checks that reach // this statement - if (Token::Match(&tok, "[;{}] break ;")) - { + if (Token::Match(&tok, "[;{}] break ;")) { ExecutionPath::bailOut(checks); } // erasing iterator => it is invalidated - if (Token::Match(&tok, "erase ( ++|--| %var% )")) - { + if (Token::Match(&tok, "erase ( ++|--| %var% )")) { // check if there is a "it = ints.erase(it);" pattern. if so // the it is not invalidated. const Token *token = &tok; - while (NULL != (token = token ? token->previous() : 0)) - { + while (NULL != (token = token ? token->previous() : 0)) { if (Token::Match(token, "[;{}]")) break; else if (token->str() == "=") @@ -368,8 +329,7 @@ private: } // the it is invalidated by the erase.. - if (token) - { + if (token) { // get variable id for the iterator unsigned int iteratorId = 0; if (tok.tokAt(2)->isName()) @@ -378,11 +338,9 @@ private: iteratorId = tok.tokAt(3)->varId(); // invalidate this iterator in the corresponding checks - for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) - { + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { EraseCheckLoop *c = dynamic_cast(*it); - if (c && c->varId == iteratorId) - { + if (c && c->varId == iteratorId) { c->eraseToken = &tok; } } @@ -399,8 +357,7 @@ private: * @param checks The execution paths. All execution paths in the list are executed in the current scope * @return true => bail out all checking **/ - bool parseCondition(const Token &tok, std::list &checks) - { + bool parseCondition(const Token &tok, std::list &checks) { // no checking of conditions. (void)tok; (void)checks; @@ -408,17 +365,13 @@ private: } /** @brief going out of scope - all execution paths end */ - void end(const std::list &checks, const Token * /*tok*/) const - { + void end(const std::list &checks, const Token * /*tok*/) const { // check if there are any invalid iterators. If so there is an error. - for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) - { + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { EraseCheckLoop *c = dynamic_cast(*it); - if (c && c->eraseToken) - { + if (c && c->eraseToken) { CheckStl *checkStl = dynamic_cast(c->owner); - if (checkStl) - { + if (checkStl) { checkStl->eraseError(c->eraseToken); } } @@ -429,16 +382,11 @@ private: void CheckStl::erase() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "for (")) - { - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == ";") - { - if (Token::Match(tok2, "; %var% !=")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "for (")) { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == ";") { + if (Token::Match(tok2, "; %var% !=")) { // Get declaration token for var.. const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const Variable *variableInfo = symbolDatabase->getVariableFromVarId(tok2->next()->varId()); @@ -458,16 +406,14 @@ void CheckStl::erase() if (Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% != %var% . end ( )") && tok2->str() == tok2->tokAt(8)->str() && - tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) - { + tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) { EraseCheckLoop::checkScope(this, tok2); break; } } } - if (Token::Match(tok, "while ( %var% !=")) - { + if (Token::Match(tok, "while ( %var% !=")) { const unsigned int varid = tok->tokAt(2)->varId(); if (varid > 0 && Token::findmatch(_tokenizer->tokens(), "> :: iterator %varid%", varid)) EraseCheckLoop::checkScope(this, tok->tokAt(2)); @@ -487,10 +433,8 @@ void CheckStl::eraseError(const Token *tok) void CheckStl::pushback() { // Pointer can become invalid after push_back or push_front.. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "%var% = & %var% [")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "%var% = & %var% [")) { // Variable id for pointer const unsigned int pointerId(tok->varId()); @@ -503,12 +447,10 @@ void CheckStl::pushback() // Count { , } and parentheses for tok2 int indent = 0; bool invalidPointer = false; - for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { if (tok2->str() == "{" || tok2->str() == "(") ++indent; - else if (tok2->str() == "}" || tok2->str() == ")") - { + else if (tok2->str() == "}" || tok2->str() == ")") { if (indent == 0 && Token::simpleMatch(tok2, ") {")) tok2 = tok2->next(); else @@ -520,8 +462,7 @@ void CheckStl::pushback() invalidPointer = true; // Using invalid pointer.. - if (invalidPointer && tok2->varId() == pointerId) - { + if (invalidPointer && tok2->varId() == pointerId) { if (tok2->previous()->str() == "*") invalidPointerError(tok2, tok2->str()); else if (tok2->next()->str() == ".") @@ -533,16 +474,14 @@ void CheckStl::pushback() } // Iterator becomes invalid after reserve, push_back or push_front.. - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (!Token::simpleMatch(tok, "vector <")) continue; // if iterator declaration inside for() loop bool iteratorDeclaredInsideLoop = false; if ((tok->tokAt(-2) && Token::simpleMatch(tok->tokAt(-2), "for (")) || - (tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::"))) - { + (tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::"))) { iteratorDeclaredInsideLoop = true; } @@ -557,8 +496,7 @@ void CheckStl::pushback() if (iteratorid == 0) continue; - if (iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=") - { + if (iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=") { // skip "> :: iterator|const_iterator" tok = tok->tokAt(3); } @@ -570,12 +508,10 @@ void CheckStl::pushback() int indent = 0; std::string invalidIterator; - for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { if (tok2->str() == "{" || tok2->str() == "(") ++indent; - else if (tok2->str() == "}" || tok2->str() == ")") - { + else if (tok2->str() == "}" || tok2->str() == ")") { if (indent == 0 && Token::simpleMatch(tok2, ") {")) tok2 = tok2->next(); else @@ -583,13 +519,11 @@ void CheckStl::pushback() } // Using push_back or push_front inside a loop.. - if (Token::simpleMatch(tok2, "for (")) - { + if (Token::simpleMatch(tok2, "for (")) { tok2 = tok2->tokAt(2); } - if (Token::Match(tok2, "%varid% = %var% . begin ( ) ; %varid% != %var% . end ( ) ; ++| %varid% ++| ) {", iteratorid)) - { + if (Token::Match(tok2, "%varid% = %var% . begin ( ) ; %varid% != %var% . end ( ) ; ++| %varid% ++| ) {", iteratorid)) { // variable id for the loop iterator const unsigned int varId(tok2->tokAt(2)->varId()); if (varId == 0) @@ -599,23 +533,17 @@ void CheckStl::pushback() // Count { and } for tok3 unsigned int indent3 = 0; - for (const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indent3; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indent3 <= 1) break; --indent3; - } - else if (tok3->str() == "break" || tok3->str() == "return") - { + } else if (tok3->str() == "break" || tok3->str() == "return") { pushbackTok = 0; break; - } - else if (Token::Match(tok3, "%varid% . push_front|push_back|insert|reserve (", varId)) - { + } else if (Token::Match(tok3, "%varid% . push_front|push_back|insert|reserve (", varId)) { pushbackTok = tok3->tokAt(2); } } @@ -625,25 +553,19 @@ void CheckStl::pushback() } // Assigning iterator.. - if (Token::Match(tok2, "%varid% =", iteratorid)) - { - if (Token::Match(tok2->tokAt(2), "%var% . begin|end|rbegin|rend ( )")) - { + if (Token::Match(tok2, "%varid% =", iteratorid)) { + if (Token::Match(tok2->tokAt(2), "%var% . begin|end|rbegin|rend ( )")) { vectorid = tok2->tokAt(2)->varId(); tok2 = tok2->tokAt(6); - } - else - { + } else { vectorid = 0; } invalidIterator = ""; } // push_back on vector.. - if (vectorid > 0 && Token::Match(tok2, "%varid% . push_front|push_back|insert|reserve (", vectorid)) - { - if (!invalidIterator.empty() && Token::Match(tok2->tokAt(2), "insert ( %varid% ,", iteratorid)) - { + if (vectorid > 0 && Token::Match(tok2, "%varid% . push_front|push_back|insert|reserve (", vectorid)) { + if (!invalidIterator.empty() && Token::Match(tok2->tokAt(2), "insert ( %varid% ,", iteratorid)) { invalidIteratorError(tok2, invalidIterator, tok2->strAt(4)); break; } @@ -653,14 +575,12 @@ void CheckStl::pushback() } // TODO: instead of bail out for 'else' try to check all execution paths. - else if (tok2->str() == "return" || tok2->str() == "break" || tok2->str() == "else") - { + else if (tok2->str() == "return" || tok2->str() == "break" || tok2->str() == "else") { invalidIterator.clear(); } // Using invalid iterator.. - if (!invalidIterator.empty()) - { + if (!invalidIterator.empty()) { if (Token::Match(tok2, "++|--|*|+|-|(|,|=|!= %varid%", iteratorid)) invalidIteratorError(tok2, invalidIterator, tok2->strAt(1)); if (Token::Match(tok2, "%varid% ++|--|+|-", iteratorid)) @@ -692,37 +612,30 @@ void CheckStl::stlBoundries() // containers (not the vector).. static const char STL_CONTAINER_LIST[] = "bitset|deque|list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set"; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring iterator.. - if (tok->str() == "<" && Token::Match(tok->previous(), STL_CONTAINER_LIST)) - { + if (tok->str() == "<" && Token::Match(tok->previous(), STL_CONTAINER_LIST)) { const std::string container_name(tok->strAt(-1)); while (tok && tok->str() != ">") tok = tok->next(); if (!tok) break; - if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) - { + if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) { const unsigned int iteratorid(tok->tokAt(3)->varId()); if (iteratorid == 0) continue; // Using "iterator < ..." is not allowed unsigned int indentlevel = 0; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel == 0) break; --indentlevel; - } - else if (Token::Match(tok2, "!!* %varid% <", iteratorid)) - { + } else if (Token::Match(tok2, "!!* %varid% <", iteratorid)) { stlBoundriesError(tok2, container_name); } } @@ -749,10 +662,8 @@ void CheckStl::if_find() const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::Match(tok, "if ( !| %var% . find ( %any% ) )")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::Match(tok, "if ( !| %var% . find ( %any% ) )")) { // goto %var% tok = tok->tokAt(2); if (!tok->isName()) @@ -760,8 +671,7 @@ void CheckStl::if_find() const unsigned int varid = tok->varId(); const Variable *var = symbolDatabase->getVariableFromVarId(varid); - if (var) - { + if (var) { // Is the variable a std::string or STL container? const Token * decl = var->nameToken(); while (decl && !Token::Match(decl, "[;{}(,]")) @@ -778,16 +688,14 @@ void CheckStl::if_find() } } - if (Token::Match(tok, "if ( !| std :: find|find_if (")) - { + if (Token::Match(tok, "if ( !| std :: find|find_if (")) { // goto '(' for the find tok = tok->tokAt(4); if (tok->isName()) tok = tok->next(); // check that result is checked properly - if (Token::simpleMatch(tok->link(), ") )")) - { + if (Token::simpleMatch(tok->link(), ") )")) { if_findError(tok, false); } } @@ -813,8 +721,7 @@ void CheckStl::if_findError(const Token *tok, bool str) bool CheckStl::isStlContainer(unsigned int varid) { // check if this token is defined - if (varid) - { + if (varid) { // find where this token is defined const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(varid); @@ -851,50 +758,41 @@ void CheckStl::size() if (!_settings->isEnabled("performance")) return; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "%var% . size ( )") || - Token::Match(tok, "%var% . %var% . size ( )")) - { + Token::Match(tok, "%var% . %var% . size ( )")) { int offset = 5; const Token *tok1 = tok; unsigned int varid = 0; // get the variable id - if (tok->strAt(2) != "size") - { + if (tok->strAt(2) != "size") { offset = 7; tok1 = tok1->tokAt(2); // found a.b.size(), lookup class/struct variable const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(tok->varId()); - if (var && var->type()) - { + if (var && var->type()) { // get class/struct variable type const Scope *type = var->type(); // lookup variable member std::list::const_iterator it; - for (it = type->varlist.begin(); it != type->varlist.end(); ++it) - { - if (it->name() == tok1->str()) - { + for (it = type->varlist.begin(); it != type->varlist.end(); ++it) { + if (it->name() == tok1->str()) { // found member variable, save varid varid = it->varId(); break; } } } - } - else + } else varid = tok1->varId(); - if (varid) - { + if (varid) { // check for comparison to zero if (Token::Match(tok->tokAt(offset), "==|!=|> 0") || - Token::Match(tok->tokAt(-2), "0 ==|!=|<")) - { + Token::Match(tok->tokAt(-2), "0 ==|!=|<")) { if (isStlContainer(varid)) sizeError(tok1); } @@ -902,8 +800,7 @@ void CheckStl::size() // check for using as boolean expression else if ((Token::Match(tok->tokAt(-2), "if|while (") || Token::Match(tok->tokAt(-3), "if|while ( !")) && - tok->strAt(offset) == ")") - { + tok->strAt(offset) == ")") { if (isStlContainer(varid)) sizeError(tok1); } @@ -930,8 +827,7 @@ void CheckStl::redundantCondition() " %var% . remove ( %any% ) ; " "}|}|"; const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); - while (tok) - { + while (tok) { bool b(tok->tokAt(15)->str() == "{"); // Get tokens for the fields %var% and %any% @@ -944,8 +840,7 @@ void CheckStl::redundantCondition() // Check if all the "%var%" fields are the same and if all the "%any%" are the same.. if (var1->str() == var2->str() && var2->str() == var3->str() && - any1->str() == any2->str()) - { + any1->str() == any2->str()) { redundantIfRemoveError(tok); } @@ -963,12 +858,9 @@ void CheckStl::redundantIfRemoveError(const Token *tok) void CheckStl::missingComparison() { - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "for (")) - { - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "for (")) { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == ";") break; @@ -985,8 +877,7 @@ void CheckStl::missingComparison() // increment iterator if (!Token::simpleMatch(tok2->tokAt(16), ("++ " + tok2->str() + " )").c_str()) && - !Token::simpleMatch(tok2->tokAt(16), (tok2->str() + " ++ )").c_str())) - { + !Token::simpleMatch(tok2->tokAt(16), (tok2->str() + " ++ )").c_str())) { continue; } @@ -1000,17 +891,14 @@ void CheckStl::missingComparison() unsigned int indentlevel = 0; // Parse loop.. - for (const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indentlevel == 0) break; --indentlevel; - } - else if (Token::Match(tok3, "%varid% ++", iteratorId)) + } else if (Token::Match(tok3, "%varid% ++", iteratorId)) incrementToken = tok3; else if (Token::Match(tok3->previous(), "++ %varid% !!.", iteratorId)) incrementToken = tok3; @@ -1018,8 +906,7 @@ void CheckStl::missingComparison() incrementToken = 0; else if (tok3->str() == "break" || tok3->str() == "return") incrementToken = 0; - else if (Token::Match(tok3, "%varid% = %var% . insert ( ++| %varid% ++| ,", iteratorId)) - { + else if (Token::Match(tok3, "%varid% = %var% . insert ( ++| %varid% ++| ,", iteratorId)) { // skip insertion.. tok3 = tok3->tokAt(6)->link(); if (!tok3) @@ -1050,22 +937,18 @@ void CheckStl::missingComparisonError(const Token *incrementToken1, const Token void CheckStl::string_c_str() { // Try to detect common problems when using string::c_str() - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Locate executable scopes: - if (Token::Match(tok, ") const| {")) - { + if (Token::Match(tok, ") const| {")) { std::set localvar; std::set pointers; // scan through this executable scope: unsigned int indentlevel = 0; - while (NULL != (tok = tok->next())) - { + while (NULL != (tok = tok->next())) { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; @@ -1084,22 +967,17 @@ void CheckStl::string_c_str() // Invalid usage.. else if (Token::Match(tok, "throw %var% . c_str ( ) ;") && tok->next()->varId() > 0 && - localvar.find(tok->next()->varId()) != localvar.end()) - { + localvar.find(tok->next()->varId()) != localvar.end()) { string_c_strError(tok); - } - else if (Token::Match(tok, "[;{}] %var% = %var% . str ( ) . c_str ( ) ;") && - tok->next()->varId() > 0 && - pointers.find(tok->next()->varId()) != pointers.end()) - { + } else if (Token::Match(tok, "[;{}] %var% = %var% . str ( ) . c_str ( ) ;") && + tok->next()->varId() > 0 && + pointers.find(tok->next()->varId()) != pointers.end()) { string_c_strError(tok); - } - else if (Token::Match(tok, "[;{}] %var% = %var% (") && - Token::simpleMatch(tok->tokAt(4)->link(), ") . c_str ( ) ;") && - tok->next()->varId() > 0 && - pointers.find(tok->next()->varId()) != pointers.end() && - Token::findmatch(_tokenizer->tokens(), ("std :: string " + tok->strAt(3) + " (").c_str())) - { + } else if (Token::Match(tok, "[;{}] %var% = %var% (") && + Token::simpleMatch(tok->tokAt(4)->link(), ") . c_str ( ) ;") && + tok->next()->varId() > 0 && + pointers.find(tok->next()->varId()) != pointers.end() && + Token::findmatch(_tokenizer->tokens(), ("std :: string " + tok->strAt(3) + " (").c_str())) { string_c_strError(tok); } } @@ -1122,44 +1000,30 @@ void CheckStl::checkAutoPointer() std::set::const_iterator iter; static const char STL_CONTAINER_LIST[] = "bitset|deque|list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set|vector"; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "auto_ptr <")) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "auto_ptr <")) { if ((tok->previous() && tok->previous()->str() == "<" && Token::Match(tok->tokAt(-2), STL_CONTAINER_LIST)) || - (Token::Match(tok->tokAt(-3), "< std :: auto_ptr") && Token::Match(tok->tokAt(-4), STL_CONTAINER_LIST))) - { + (Token::Match(tok->tokAt(-3), "< std :: auto_ptr") && Token::Match(tok->tokAt(-4), STL_CONTAINER_LIST))) { autoPointerContainerError(tok); - } - else - { + } else { const Token *tok2 = tok->next()->next(); - while (tok2) - { - if (Token::Match(tok2, "> %var%")) - { + while (tok2) { + if (Token::Match(tok2, "> %var%")) { const Token *tok3 = tok2->next()->next(); - while (tok3 && tok3->str() != ";") - { + while (tok3 && tok3->str() != ";") { tok3 = tok3->next(); } - if (tok3) - { + if (tok3) { tok3 = tok3->previous()->previous(); - if (Token::simpleMatch(tok3->previous(), "[ ] )")) - { + if (Token::simpleMatch(tok3->previous(), "[ ] )")) { autoPointerArrayError(tok2->next()); - } - else if (tok3->varId()) - { + } else if (tok3->varId()) { const Token *decltok = Token::findmatch(_tokenizer->tokens(), "%varid% = new %type% [", tok3->varId()); - if (decltok) - { + if (decltok) { autoPointerArrayError(tok2->next()); } } - if (tok2->next()->varId()) - { + if (tok2->next()->varId()) { autoPtrVarId.insert(tok2->next()->varId()); } break; @@ -1168,25 +1032,17 @@ void CheckStl::checkAutoPointer() tok2 = tok2->next(); } } - } - else - { - if (Token::Match(tok, "%var% = %var% ;")) - { - if (_settings->isEnabled("style")) - { + } else { + if (Token::Match(tok, "%var% = %var% ;")) { + if (_settings->isEnabled("style")) { iter = autoPtrVarId.find(tok->next()->next()->varId()); - if (iter != autoPtrVarId.end()) - { + if (iter != autoPtrVarId.end()) { autoPointerError(tok->next()->next()); } } - } - else if (Token::Match(tok, "%var% = new %type% [") || Token::Match(tok, "%var% . reset ( new %type% [")) - { + } else if (Token::Match(tok, "%var% = new %type% [") || Token::Match(tok, "%var% . reset ( new %type% [")) { iter = autoPtrVarId.find(tok->varId()); - if (iter != autoPtrVarId.end()) - { + if (iter != autoPtrVarId.end()) { autoPointerArrayError(tok); } } diff --git a/lib/checkstl.h b/lib/checkstl.h index b9951b49f..a98b12ddf 100644 --- a/lib/checkstl.h +++ b/lib/checkstl.h @@ -31,8 +31,7 @@ class Token; /** @brief %Check STL usage (invalidation of iterators, mismatching containers, etc) */ -class CheckStl : public Check -{ +class CheckStl : public Check { public: /** This constructor is used when registering the CheckClass */ CheckStl() : Check(myName()) @@ -44,8 +43,7 @@ public: { } /** Simplified checks. The token list is simplified. */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckStl checkStl(tokenizer, settings, errorLogger); checkStl.stlOutOfBounds(); @@ -164,8 +162,7 @@ private: void autoPointerContainerError(const Token *tok); void autoPointerArrayError(const Token *tok); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckStl c(0, settings, errorLogger); c.invalidIteratorError(0, "iterator"); c.iteratorsError(0, "container1", "container2"); @@ -186,13 +183,11 @@ private: c.autoPointerArrayError(0); } - std::string myName() const - { + std::string myName() const { return "STL usage"; } - std::string classInfo() const - { + std::string classInfo() const { return "Check for invalid usage of STL:\n" "* out of bounds errors\n" "* misuse of iterators when iterating through a container\n" diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index f09b48bae..a03da46cc 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -26,9 +26,8 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckUninitVar instance; +namespace { + CheckUninitVar instance; } //--------------------------------------------------------------------------- @@ -39,19 +38,16 @@ CheckUninitVar instance; /** * @brief %Check that uninitialized variables aren't used (using ExecutionPath) * */ -class UninitVar : public ExecutionPath -{ +class UninitVar : public ExecutionPath { public: /** Startup constructor */ UninitVar(Check *c) - : ExecutionPath(c, 0), pointer(false), array(false), alloc(false), strncpy_(false), memset_nonzero(false) - { + : ExecutionPath(c, 0), pointer(false), array(false), alloc(false), strncpy_(false), memset_nonzero(false) { } private: /** Create a copy of this check */ - ExecutionPath *copy() - { + ExecutionPath *copy() { return new UninitVar(*this); } @@ -60,13 +56,11 @@ private: /** internal constructor for creating extra checks */ UninitVar(Check *c, unsigned int v, const std::string &name, bool p, bool a) - : ExecutionPath(c, v), varname(name), pointer(p), array(a), alloc(false), strncpy_(false), memset_nonzero(false) - { + : ExecutionPath(c, v), varname(name), pointer(p), array(a), alloc(false), strncpy_(false), memset_nonzero(false) { } /** is other execution path equal? */ - bool is_equal(const ExecutionPath *e) const - { + bool is_equal(const ExecutionPath *e) const { const UninitVar *c = static_cast(e); return (varname == c->varname && pointer == c->pointer && array == c->array && alloc == c->alloc && strncpy_ == c->strncpy_ && memset_nonzero == c->memset_nonzero); } @@ -90,13 +84,11 @@ private: bool memset_nonzero; /** allocating pointer. For example : p = malloc(10); */ - static void alloc_pointer(std::list &checks, unsigned int varid) - { + static void alloc_pointer(std::list &checks, unsigned int varid) { // loop through the checks and perform a allocation if the // variable id matches std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); if (c && c->varId == varid) c->alloc = true; @@ -104,8 +96,7 @@ private: } /** Initializing a pointer value. For example: *p = 0; */ - static void init_pointer(std::list &checks, const Token *tok) - { + static void init_pointer(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); if (!varid) return; @@ -113,19 +104,14 @@ private: // loop through the checks and perform a initialization if the // variable id matches std::list::iterator it = checks.begin(); - while (it != checks.end()) - { + while (it != checks.end()) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid) - { - if (c->alloc || c->array) - { + if (c && c->varId == varid) { + if (c->alloc || c->array) { delete c; checks.erase(it++); continue; - } - else - { + } else { use_pointer(checks, tok); } } @@ -135,8 +121,7 @@ private: } /** Deallocate a pointer. For example: free(p); */ - static void dealloc_pointer(std::list &checks, const Token *tok) - { + static void dealloc_pointer(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); if (!varid) return; @@ -144,17 +129,13 @@ private: // loop through the checks and perform a deallocation if the // variable id matches std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid) - { + if (c && c->varId == varid) { // unallocated pointer variable => error - if (c->pointer && !c->alloc) - { + if (c->pointer && !c->alloc) { CheckUninitVar *checkUninitVar = dynamic_cast(c->owner); - if (checkUninitVar) - { + if (checkUninitVar) { checkUninitVar->uninitvarError(tok, c->varname); break; } @@ -171,8 +152,7 @@ private: * \param tok1 the "p" token * \param tok2 the "x" token */ - static void pointer_assignment(std::list &checks, const Token *tok1, const Token *tok2) - { + static void pointer_assignment(std::list &checks, const Token *tok1, const Token *tok2) { // Variable id for "left hand side" variable const unsigned int varid1(tok1->varId()); if (varid1 == 0) @@ -186,22 +166,18 @@ private: std::list::const_iterator it; // bail out if first variable is a pointer - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid1 && c->pointer) - { + if (c && c->varId == varid1 && c->pointer) { bailOutVar(checks, varid1); break; } } // bail out if second variable is a array/pointer - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid2 && (c->pointer || c->array)) - { + if (c && c->varId == varid2 && (c->pointer || c->array)) { bailOutVar(checks, varid2); break; } @@ -210,36 +186,30 @@ private: /** Initialize an array with strncpy. */ - static void init_strncpy(std::list &checks, const Token *tok) - { + static void init_strncpy(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); if (!varid) return; std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid) - { + if (c && c->varId == varid) { c->strncpy_ = true; } } } /** Initialize an array with memset (not zero). */ - static void init_memset_nonzero(std::list &checks, const Token *tok) - { + static void init_memset_nonzero(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); if (!varid) return; std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid) - { + if (c && c->varId == varid) { c->memset_nonzero = true; } } @@ -254,18 +224,15 @@ private: * @param mode specific behaviour * @return if error is found, true is returned */ - static bool use(std::list &checks, const Token *tok, const int mode) - { + static bool use(std::list &checks, const Token *tok, const int mode) { const unsigned int varid(tok->varId()); if (varid == 0) return false; std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); - if (c && c->varId == varid) - { + if (c && c->varId == varid) { // mode 0 : the variable is used "directly" // example: .. = var; // it is ok to read the address of an uninitialized array. @@ -287,8 +254,7 @@ private: continue; CheckUninitVar *checkUninitVar = dynamic_cast(c->owner); - if (checkUninitVar) - { + if (checkUninitVar) { if (c->strncpy_ || c->memset_nonzero) checkUninitVar->uninitstringError(tok, c->varname, c->strncpy_); else if (c->pointer && c->alloc) @@ -311,8 +277,7 @@ private: * @param tok variable token * @return if error is found, true is returned */ - static bool use(std::list &checks, const Token *tok) - { + static bool use(std::list &checks, const Token *tok) { return use(checks, tok, 0); } @@ -321,8 +286,7 @@ private: * @param checks all available checks * @param tok variable token */ - static void use_array(std::list &checks, const Token *tok) - { + static void use_array(std::list &checks, const Token *tok) { use(checks, tok, 1); } @@ -332,8 +296,7 @@ private: * @param tok variable token * @return if error is found, true is returned */ - static bool use_pointer(std::list &checks, const Token *tok) - { + static bool use_pointer(std::list &checks, const Token *tok) { return use(checks, tok, 2); } @@ -343,8 +306,7 @@ private: * @param tok variable token * @return if error is found, true is returned */ - static bool use_dead_pointer(std::list &checks, const Token *tok) - { + static bool use_dead_pointer(std::list &checks, const Token *tok) { return use(checks, tok, 3); } @@ -355,30 +317,25 @@ private: * @param tok variable token * @return if error is found, true is returned */ - static bool use_array_or_pointer_data(std::list &checks, const Token *tok) - { + static bool use_array_or_pointer_data(std::list &checks, const Token *tok) { return use(checks, tok, 4); } /** declaring a variable */ - void declare(std::list &checks, const Token *vartok, const Token &tok, const bool p, const bool a) const - { + void declare(std::list &checks, const Token *vartok, const Token &tok, const bool p, const bool a) const { if (vartok->varId() == 0) return; // Suppress warnings if variable in inner scope has same name as variable in outer scope - if (!tok.isStandardType()) - { + if (!tok.isStandardType()) { std::set dup; - for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) - { + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { UninitVar *c = dynamic_cast(*it); if (c && c->varname == vartok->str() && c->varId != vartok->varId()) dup.insert(c->varId); } - if (!dup.empty()) - { + if (!dup.empty()) { for (std::set::const_iterator it = dup.begin(); it != dup.end(); ++it) bailOutVar(checks, *it); return; @@ -394,11 +351,9 @@ private: * @param tok2 start token of rhs * @param checks the execution paths */ - void parserhs(const Token *tok2, std::list &checks) const - { + void parserhs(const Token *tok2, std::list &checks) const { // check variable usages in rhs/index - while (NULL != (tok2 = tok2->next())) - { + while (NULL != (tok2 = tok2->next())) { if (Token::Match(tok2, "[;)=?]")) break; if (Token::Match(tok2, "%var% (")) @@ -406,14 +361,11 @@ private: if (tok2->varId() && !Token::Match(tok2->previous(), "&|::") && !Token::simpleMatch(tok2->tokAt(-2), "& (") && - !Token::simpleMatch(tok2->next(), "=")) - { + !Token::simpleMatch(tok2->next(), "=")) { // Multiple assignments.. - if (Token::Match(tok2->next(), ".|[")) - { + if (Token::Match(tok2->next(), ".|[")) { const Token * tok3 = tok2; - while (tok3) - { + while (tok3) { if (Token::Match(tok3->next(), ". %var%")) tok3 = tok3->tokAt(2); else if (tok3->strAt(1) == "[") @@ -431,8 +383,7 @@ private: foundError = use(checks, tok2); // prevent duplicate error messages - if (foundError) - { + if (foundError) { bailOutVar(checks, tok2->varId()); } } @@ -441,11 +392,9 @@ private: } /** parse tokens. @sa ExecutionPath::parse */ - const Token *parse(const Token &tok, std::list &checks) const - { + const Token *parse(const Token &tok, std::list &checks) const { // Variable declaration.. - if (Token::Match(tok.previous(), "[;{}] %var%") && tok.str() != "return") - { + if (Token::Match(tok.previous(), "[;{}] %var%") && tok.str() != "return") { if (Token::Match(&tok, "enum %type% {")) return tok.tokAt(2)->link(); @@ -453,8 +402,7 @@ private: while (Token::Match(vartok, "const|struct")) vartok = vartok->next(); - if (Token::Match(vartok, "%type% *| %var% ;")) - { + if (Token::Match(vartok, "%type% *| %var% ;")) { vartok = vartok->next(); const bool p(vartok->str() == "*"); if (p) @@ -466,25 +414,21 @@ private: // Variable declaration for array.. if (Token::Match(vartok, "%type% %var% [") && vartok->isStandardType() && - Token::simpleMatch(vartok->tokAt(2)->link(), "] ;")) - { + Token::simpleMatch(vartok->tokAt(2)->link(), "] ;")) { vartok = vartok->next(); declare(checks, vartok, tok, false, true); return vartok->next()->link(); } // Template pointer variable.. - if (Token::Match(vartok, "%type% ::|<")) - { + if (Token::Match(vartok, "%type% ::|<")) { while (Token::Match(vartok, "%type% ::")) vartok = vartok->tokAt(2); - if (Token::Match(vartok, "%type% < %type%")) - { + if (Token::Match(vartok, "%type% < %type%")) { vartok = vartok->tokAt(3); while (vartok && (vartok->str() == "*" || vartok->isName())) vartok = vartok->next(); - if (Token::Match(vartok, "> * %var% ;")) - { + if (Token::Match(vartok, "> * %var% ;")) { declare(checks, vartok->tokAt(2), tok, true, false); return vartok->tokAt(2); } @@ -492,23 +436,18 @@ private: } } - if (tok.str() == "return") - { + if (tok.str() == "return") { // is there assignment or ternary operator in the return statement? bool assignment = false; - for (const Token *tok2 = tok.next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) - { - if (tok2->str() == "=" || tok2->str() == ">>" || tok2->str() == "?" || Token::Match(tok2, "(|, &")) - { + for (const Token *tok2 = tok.next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { + if (tok2->str() == "=" || tok2->str() == ">>" || tok2->str() == "?" || Token::Match(tok2, "(|, &")) { assignment = true; break; } } - if (!assignment) - { - for (const Token *tok2 = tok.next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) - { + if (!assignment) { + for (const Token *tok2 = tok.next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { if (tok2->isName() && tok2->strAt(1) == "(") tok2 = tok2->next()->link(); @@ -518,19 +457,16 @@ private: } } - if (tok.varId()) - { + if (tok.varId()) { // array variable passed as function parameter.. - if (Token::Match(tok.previous(), "[(,] %var% [+-,)]")) - { + if (Token::Match(tok.previous(), "[(,] %var% [+-,)]")) { use(checks, &tok); //use_array(checks, &tok); return &tok; } // Used.. - if (Token::Match(tok.previous(), "[[(,+-*/|=] %var% ]|)|,|;|%op%")) - { + if (Token::Match(tok.previous(), "[[(,+-*/|=] %var% ]|)|,|;|%op%")) { // initialize reference variable if (Token::Match(tok.tokAt(-3), "& %var% =")) bailOutVar(checks, tok.varId()); @@ -539,28 +475,20 @@ private: return &tok; } - if (Token::Match(tok.previous(), "++|--") || Token::Match(tok.next(), "++|--")) - { + if (Token::Match(tok.previous(), "++|--") || Token::Match(tok.next(), "++|--")) { use(checks, &tok); return &tok; } - if (Token::Match(tok.previous(), "[;{}] %var% [=[.]")) - { - if (tok.next()->str() == ".") - { - if (use_dead_pointer(checks, &tok)) - { + if (Token::Match(tok.previous(), "[;{}] %var% [=[.]")) { + if (tok.next()->str() == ".") { + if (use_dead_pointer(checks, &tok)) { return &tok; } - } - else - { + } else { const Token *tok2 = tok.next(); - if (tok2->str() == "[" && Token::simpleMatch(tok2->link(), "] =")) - { - if (use_dead_pointer(checks, &tok)) - { + if (tok2->str() == "[" && Token::simpleMatch(tok2->link(), "] =")) { + if (use_dead_pointer(checks, &tok)) { return &tok; } @@ -571,29 +499,23 @@ private: } // pointer aliasing? - if (Token::Match(tok.tokAt(2), "%var% ;")) - { + if (Token::Match(tok.tokAt(2), "%var% ;")) { pointer_assignment(checks, &tok, tok.tokAt(2)); } } - if (Token::simpleMatch(tok.next(), "(")) - { + if (Token::simpleMatch(tok.next(), "(")) { use_pointer(checks, &tok); } - if (Token::Match(tok.tokAt(-2), "[;{}] *")) - { - if (Token::simpleMatch(tok.next(), "=")) - { + if (Token::Match(tok.tokAt(-2), "[;{}] *")) { + if (Token::simpleMatch(tok.next(), "=")) { // is the pointer used in the rhs? bool used = false; - for (const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) { if (Token::Match(tok2, "[,;=(]")) break; - else if (Token::Match(tok2, "* %varid%", tok.varId())) - { + else if (Token::Match(tok2, "* %varid%", tok.varId())) { used = true; break; } @@ -602,49 +524,41 @@ private: use_pointer(checks, &tok); else init_pointer(checks, &tok); - } - else - { + } else { use_pointer(checks, &tok); } return &tok; } - if (Token::Match(tok.next(), "= malloc|kmalloc") || Token::simpleMatch(tok.next(), "= new char [")) - { + if (Token::Match(tok.next(), "= malloc|kmalloc") || Token::simpleMatch(tok.next(), "= new char [")) { alloc_pointer(checks, tok.varId()); if (tok.tokAt(3)->str() == "(") return tok.tokAt(3); } - else if (Token::Match(tok.previous(), "<<|>>") || Token::simpleMatch(tok.next(), "=")) - { + else if (Token::Match(tok.previous(), "<<|>>") || Token::simpleMatch(tok.next(), "=")) { // TODO: Don't bail out for "<<" and ">>" if these are // just computations ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } - if (Token::simpleMatch(tok.next(), "[")) - { + if (Token::simpleMatch(tok.next(), "[")) { const Token *tok2 = tok.next()->link(); - if (Token::simpleMatch(tok2 ? tok2->next() : 0, "=")) - { + if (Token::simpleMatch(tok2 ? tok2->next() : 0, "=")) { ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } } if (Token::simpleMatch(tok.previous(), "delete") || - Token::simpleMatch(tok.tokAt(-3), "delete [ ]")) - { + Token::simpleMatch(tok.tokAt(-3), "delete [ ]")) { dealloc_pointer(checks, &tok); return &tok; } } - if (Token::Match(&tok, "%var% (") && uvarFunctions.find(tok.str()) == uvarFunctions.end()) - { + if (Token::Match(&tok, "%var% (") && uvarFunctions.find(tok.str()) == uvarFunctions.end()) { // sizeof/typeof doesn't dereference. A function name that is all uppercase // might be an unexpanded macro that uses sizeof/typeof if (Token::Match(&tok, "sizeof|typeof (")) @@ -652,8 +566,7 @@ private: // deallocate pointer if (Token::Match(&tok, "free|kfree|fclose ( %var% )") || - Token::Match(&tok, "realloc ( %var%")) - { + Token::Match(&tok, "realloc ( %var%")) { dealloc_pointer(checks, tok.tokAt(2)); return tok.tokAt(3); } @@ -662,8 +575,7 @@ private: { std::list var; CheckNullPointer::parseFunctionCall(tok, var, 1); - for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) - { + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) { use_array(checks, *it); use_dead_pointer(checks, *it); } @@ -671,45 +583,36 @@ private: // Using uninitialized pointer is bad if using null pointer is bad std::list var2; CheckNullPointer::parseFunctionCall(tok, var2, 0); - for (std::list::const_iterator it = var2.begin(); it != var2.end(); ++it) - { + for (std::list::const_iterator it = var2.begin(); it != var2.end(); ++it) { if (std::find(var.begin(), var.end(), *it) == var.end()) use_dead_pointer(checks, *it); } } // strncpy doesn't 0-terminate first parameter - if (Token::Match(&tok, "strncpy ( %var% ,")) - { - if (Token::Match(tok.tokAt(4), "%str% ,")) - { - if (Token::Match(tok.tokAt(6), "%num% )")) - { + if (Token::Match(&tok, "strncpy ( %var% ,")) { + if (Token::Match(tok.tokAt(4), "%str% ,")) { + if (Token::Match(tok.tokAt(6), "%num% )")) { const std::size_t len = Token::getStrLength(tok.tokAt(4)); const MathLib::bigint sz = MathLib::toLongNumber(tok.strAt(6)); - if (sz >= 0 && len >= static_cast(sz)) - { + if (sz >= 0 && len >= static_cast(sz)) { init_strncpy(checks, tok.tokAt(2)); return tok.next()->link(); } } - } - else - { + } else { init_strncpy(checks, tok.tokAt(2)); return tok.next()->link(); } } // memset (not zero terminated).. - if (Token::Match(&tok, "memset ( %var% , !!0 , %num% )")) - { + if (Token::Match(&tok, "memset ( %var% , !!0 , %num% )")) { init_memset_nonzero(checks, tok.tokAt(2)); return tok.next()->link(); } - if (Token::simpleMatch(&tok, "asm ( )")) - { + if (Token::simpleMatch(&tok, "asm ( )")) { ExecutionPath::bailOut(checks); return &tok; } @@ -717,41 +620,34 @@ private: // is the variable passed as a parameter to some function? unsigned int parlevel = 0; std::set bailouts; - for (const Token *tok2 = tok.next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok.next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel <= 1) break; --parlevel; } - else if (Token::Match(tok2, "sizeof|typeof (")) - { + else if (Token::Match(tok2, "sizeof|typeof (")) { tok2 = tok2->next()->link(); if (!tok2) break; } // ticket #2367 : unexpanded macro that uses sizeof|typeof? - else if (Token::Match(tok2, "%type% (") && CheckNullPointer::isUpper(tok2->str())) - { + else if (Token::Match(tok2, "%type% (") && CheckNullPointer::isUpper(tok2->str())) { tok2 = tok2->next()->link(); if (!tok2) break; } - else if (tok2->varId()) - { - if (Token::Match(tok2->tokAt(-2), "[(,] *") || Token::Match(tok2->next(), ". %var%")) - { + else if (tok2->varId()) { + if (Token::Match(tok2->tokAt(-2), "[(,] *") || Token::Match(tok2->next(), ". %var%")) { // find function call.. const Token *functionCall = tok2; - while (0 != (functionCall = functionCall ? functionCall->previous() : 0)) - { + while (0 != (functionCall = functionCall ? functionCall->previous() : 0)) { if (functionCall->str() == "(") break; if (functionCall->str() == ")") @@ -759,8 +655,7 @@ private: } functionCall = functionCall ? functionCall->previous() : 0; - if (functionCall) - { + if (functionCall) { if (functionCall->isName() && !CheckNullPointer::isUpper(functionCall->str()) && use_dead_pointer(checks, tok2)) ExecutionPath::bailOutVar(checks, tok2->varId()); } @@ -771,13 +666,10 @@ private: bailouts.insert(tok2->varId()); // array initialization.. - if (Token::Match(tok2->previous(), "[,(] %var% [+-]")) - { + if (Token::Match(tok2->previous(), "[,(] %var% [+-]")) { // if var is array, bailout - for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) - { - if ((*it)->varId == tok2->varId()) - { + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { + if ((*it)->varId == tok2->varId()) { const UninitVar *c = dynamic_cast(*it); if (c && (c->array || (c->pointer && c->alloc))) bailouts.insert(tok2->varId()); @@ -793,64 +685,50 @@ private: } // function call via function pointer - if (Token::Match(&tok, "( * %var% ) (")) - { + if (Token::Match(&tok, "( * %var% ) (")) { // is the variable passed as a parameter to some function? unsigned int parlevel = 0; - for (const Token *tok2 = tok.link()->next(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok.link()->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel <= 1) break; --parlevel; } - else if (tok2->varId()) - { + else if (tok2->varId()) { // it is possible that the variable is initialized here ExecutionPath::bailOutVar(checks, tok2->varId()); } } } - if (tok.str() == "return") - { + if (tok.str() == "return") { // Todo: if (!array && .. - if (Token::Match(tok.next(), "%var% ;")) - { + if (Token::Match(tok.next(), "%var% ;")) { use(checks, tok.next()); - } - else if (Token::Match(tok.next(), "%var% [")) - { + } else if (Token::Match(tok.next(), "%var% [")) { use_array_or_pointer_data(checks, tok.next()); } } - if (tok.varId()) - { - if (Token::simpleMatch(tok.previous(), "=")) - { - if (Token::Match(tok.tokAt(-3), "& %var% =")) - { + if (tok.varId()) { + if (Token::simpleMatch(tok.previous(), "=")) { + if (Token::Match(tok.tokAt(-3), "& %var% =")) { bailOutVar(checks, tok.varId()); return &tok; } - if (!Token::Match(tok.tokAt(-3), ". %var% =")) - { - if (!Token::Match(tok.tokAt(-3), "[;{}] %var% =")) - { + if (!Token::Match(tok.tokAt(-3), ". %var% =")) { + if (!Token::Match(tok.tokAt(-3), "[;{}] %var% =")) { use(checks, &tok); return &tok; } const unsigned int varid2 = tok.tokAt(-2)->varId(); - if (varid2) - { + if (varid2) { { use(checks, &tok); return &tok; @@ -859,33 +737,28 @@ private: } } - if (Token::simpleMatch(tok.next(), ".")) - { + if (Token::simpleMatch(tok.next(), ".")) { bailOutVar(checks, tok.varId()); return &tok; } - if (Token::simpleMatch(tok.next(), "[")) - { + if (Token::simpleMatch(tok.next(), "[")) { ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } - if (Token::Match(tok.tokAt(-2), "[,(=] *")) - { + if (Token::Match(tok.tokAt(-2), "[,(=] *")) { use_pointer(checks, &tok); return &tok; } - if (Token::simpleMatch(tok.previous(), "&")) - { + if (Token::simpleMatch(tok.previous(), "&")) { ExecutionPath::bailOutVar(checks, tok.varId()); } } // Parse "for" - if (Token::Match(&tok, "[;{}] for (")) - { + if (Token::Match(&tok, "[;{}] for (")) { // initialized variables std::set varid1; varid1.insert(0); @@ -894,8 +767,7 @@ private: const Token *tok2; // parse setup - for (tok2 = tok.tokAt(3); tok2 != tok.link(); tok2 = tok2->next()) - { + for (tok2 = tok.tokAt(3); tok2 != tok.link(); tok2 = tok2->next()) { if (tok2->str() == ";") break; if (tok2->varId()) @@ -905,8 +777,7 @@ private: return &tok; // parse condition - if (Token::Match(tok2, "; %var% <|<=|>=|> %num% ;")) - { + if (Token::Match(tok2, "; %var% <|<=|>=|> %num% ;")) { // If the variable hasn't been initialized then call "use" if (varid1.find(tok2->next()->varId()) == varid1.end()) use(checks, tok2->next()); @@ -919,8 +790,7 @@ private: // parse the stepcode if (Token::Match(tok2, "; ++|-- %var% ) {") || - Token::Match(tok2, "; %var% ++|-- ) {")) - { + Token::Match(tok2, "; %var% ++|-- ) {")) { // get id of variable.. unsigned int varid = tok2->next()->varId(); if (!varid) @@ -928,29 +798,24 @@ private: // Check that the variable hasn't been initialized and // that it isn't initialized in the body.. - if (varid1.find(varid) == varid1.end()) - { + if (varid1.find(varid) == varid1.end()) { unsigned int indentlevel = 0; - for (const Token *tok3 = tok2->tokAt(5); tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(5); tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indentlevel == 0) break; --indentlevel; } - if (tok3->varId() == varid) - { + if (tok3->varId() == varid) { varid = 0; // variable is used.. maybe it's initialized. clear the variable id. break; } } // If the variable isn't initialized in the body call "use" - if (varid != 0) - { + if (varid != 0) { // goto variable tok2 = tok2->next(); if (!tok2->varId()) @@ -966,24 +831,21 @@ private: return &tok; } - bool parseCondition(const Token &tok, std::list &checks) - { + bool parseCondition(const Token &tok, std::list &checks) { if (tok.varId() && Token::Match(&tok, "%var% <|<=|==|!=|)")) use(checks, &tok); else if (Token::Match(&tok, "!| %var% [")) use_array_or_pointer_data(checks, tok.str() == "!" ? tok.next() : &tok); - else if (Token::Match(&tok, "!| %var% (")) - { + else if (Token::Match(&tok, "!| %var% (")) { std::list var; CheckNullPointer::parseFunctionCall(tok.str() == "!" ? *tok.next() : tok, var, 1); for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) use_array(checks, *it); } - else if (Token::Match(&tok, "! %var% )")) - { + else if (Token::Match(&tok, "! %var% )")) { use(checks, &tok); return false; } @@ -991,27 +853,21 @@ private: return ExecutionPath::parseCondition(tok, checks); } - void parseLoopBody(const Token *tok, std::list &checks) const - { - while (tok) - { + void parseLoopBody(const Token *tok, std::list &checks) const { + while (tok) { if (tok->str() == "{" || tok->str() == "}" || tok->str() == "for") return; - if (Token::simpleMatch(tok, "if (")) - { + if (Token::simpleMatch(tok, "if (")) { // bail out all variables that are used in the condition unsigned int parlevel = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel == 0) break; --parlevel; - } - else if (tok2->varId()) + } else if (tok2->varId()) ExecutionPath::bailOutVar(checks, tok2->varId()); } } @@ -1025,33 +881,26 @@ public: /** Functions that don't handle uninitialized variables well */ static std::set uvarFunctions; - static void analyseFunctions(const Token * const tokens, std::set &func) - { - for (const Token *tok = tokens; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + static void analyseFunctions(const Token * const tokens, std::set &func) { + for (const Token *tok = tokens; tok; tok = tok->next()) { + if (tok->str() == "{") { tok = tok->link(); continue; } - if (tok->str() != "::" && Token::Match(tok->next(), "%var% ( %type%")) - { + if (tok->str() != "::" && Token::Match(tok->next(), "%var% ( %type%")) { if (!Token::Match(tok->tokAt(2)->link(), ") [{;]")) continue; const Token *tok2 = tok->tokAt(3); - while (tok2 && tok2->str() != ")") - { + while (tok2 && tok2->str() != ")") { if (tok2->str() == ",") tok2 = tok2->next(); - if (Token::Match(tok2, "%type% %var% ,|)") && tok2->isStandardType()) - { + if (Token::Match(tok2, "%type% %var% ,|)") && tok2->isStandardType()) { tok2 = tok2->tokAt(2); continue; } - if (tok2->isStandardType() && Token::Match(tok2, "%type% & %var% ,|)")) - { + if (tok2->isStandardType() && Token::Match(tok2, "%type% & %var% ,|)")) { const unsigned int varid(tok2->tokAt(2)->varId()); // flags for read/write @@ -1059,28 +908,22 @@ public: // check how the variable is used in the function unsigned int indentlevel = 0; - for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indentlevel <= 1) break; --indentlevel; - } - else if (indentlevel == 0 && tok3->str() == ";") + } else if (indentlevel == 0 && tok3->str() == ";") break; - else if (indentlevel >= 1 && tok3->varId() == varid) - { + else if (indentlevel >= 1 && tok3->varId() == varid) { if (Token::Match(tok3->previous(), "++|--") || - Token::Match(tok3->next(), "++|--")) - { + Token::Match(tok3->next(), "++|--")) { r = true; } - else - { + else { w = true; break; } @@ -1094,16 +937,14 @@ public: continue; } - if (Token::Match(tok2, "const %type% &|*| const| %var% ,|)") && tok2->next()->isStandardType()) - { + if (Token::Match(tok2, "const %type% &|*| const| %var% ,|)") && tok2->next()->isStandardType()) { tok2 = tok2->tokAt(3); while (tok2->isName()) tok2 = tok2->next(); continue; } - if (Token::Match(tok2, "const %type% %var% [ ] ,|)") && tok2->next()->isStandardType()) - { + if (Token::Match(tok2, "const %type% %var% [ ] ,|)") && tok2->next()->isStandardType()) { tok2 = tok2->tokAt(5); continue; } diff --git a/lib/checkuninitvar.h b/lib/checkuninitvar.h index ebca05e5e..bc371250f 100644 --- a/lib/checkuninitvar.h +++ b/lib/checkuninitvar.h @@ -33,8 +33,7 @@ class Token; /** @brief Checking for uninitialized variables */ -class CheckUninitVar : public Check -{ +class CheckUninitVar : public Check { public: /** @brief This constructor is used when registering the CheckUninitVar */ CheckUninitVar() : Check(myName()) @@ -46,16 +45,14 @@ public: { } /** @brief Run checks against the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { (void)tokenizer; (void)settings; (void)errorLogger; } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckUninitVar checkUninitVar(tokenizer, settings, errorLogger); checkUninitVar.executionPaths(); } @@ -77,8 +74,7 @@ public: void uninitdataError(const Token *tok, const std::string &varname); void uninitvarError(const Token *tok, const std::string &varname); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckUninitVar c(0, settings, errorLogger); // error @@ -87,13 +83,11 @@ public: c.uninitvarError(0, "varname"); } - std::string myName() const - { + std::string myName() const { return "Uninitialized variables"; } - std::string classInfo() const - { + std::string classInfo() const { return "Uninitialized variables\n" "* using uninitialized variables and data\n"; } diff --git a/lib/checkunusedfunctions.cpp b/lib/checkunusedfunctions.cpp index 1844928be..bbf0ffcf3 100644 --- a/lib/checkunusedfunctions.cpp +++ b/lib/checkunusedfunctions.cpp @@ -33,14 +33,12 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) { // Function declarations.. - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (tok->fileIndex() != 0) continue; // token contains a ':' => skip to next ; or { - if (tok->str().find(":") != std::string::npos) - { + if (tok->str().find(":") != std::string::npos) { while (tok && tok->str().find_first_of(";{")) tok = tok->next(); if (tok) @@ -66,10 +64,8 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) funcname = 0; // Check that ") {" is found.. - for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) - { - if (tok2->str() == ")") - { + for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) { + if (tok2->str() == ")") { if (! Token::simpleMatch(tok2, ") {") && ! Token::simpleMatch(tok2, ") const {") && ! Token::simpleMatch(tok2, ") const throw ( ) {") && @@ -79,21 +75,18 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) } } - if (funcname) - { + if (funcname) { FunctionUsage &func = _functions[ funcname->str()]; if (!func.lineNumber) func.lineNumber = funcname->linenr(); // No filename set yet.. - if (func.filename.empty()) - { + if (func.filename.empty()) { func.filename = tokenizer.getFiles()->at(0); } // Multiple files => filename = "+" - else if (func.filename != tokenizer.getFiles()->at(0)) - { + else if (func.filename != tokenizer.getFiles()->at(0)) { //func.filename = "+"; func.usedOtherFile |= func.usedSameFile; } @@ -101,12 +94,10 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) } // Function usage.. - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { const Token *funcname = 0; - if (Token::Match(tok->next(), "%var% (")) - { + if (Token::Match(tok->next(), "%var% (")) { funcname = tok->next(); } @@ -120,16 +111,13 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) continue; // funcname ( => Assert that the end parenthesis isn't followed by { - if (Token::Match(funcname, "%var% (")) - { + if (Token::Match(funcname, "%var% (")) { int parlevel = 0; - for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { --parlevel; if (parlevel == 0 && (Token::Match(tok2, ") const|{"))) funcname = NULL; @@ -139,8 +127,7 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) } } - if (funcname) - { + if (funcname) { FunctionUsage &func = _functions[ funcname->str()]; if (func.filename.empty() || func.filename == "+") @@ -156,24 +143,20 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) void CheckUnusedFunctions::check(ErrorLogger * const errorLogger) { - for (std::map::const_iterator it = _functions.begin(); it != _functions.end(); ++it) - { + for (std::map::const_iterator it = _functions.begin(); it != _functions.end(); ++it) { const FunctionUsage &func = it->second; if (func.usedOtherFile || func.filename.empty()) continue; if (it->first == "main" || it->first == "WinMain" || it->first == "_tmain" || it->first == "if") continue; - if (! func.usedSameFile) - { + if (! func.usedSameFile) { std::string filename; if (func.filename == "+") filename = ""; else filename = func.filename; unusedFunctionError(errorLogger, filename, func.lineNumber, it->first); - } - else if (! func.usedOtherFile) - { + } else if (! func.usedOtherFile) { /** @todo add error message "function is only used in it can be static" */ /* std::ostringstream errmsg; @@ -189,8 +172,7 @@ void CheckUnusedFunctions::unusedFunctionError(ErrorLogger * const errorLogger, const std::string &funcname) { std::list locationList; - if (!filename.empty()) - { + if (!filename.empty()) { ErrorLogger::ErrorMessage::FileLocation fileLoc; fileLoc.setfile(filename); fileLoc.line = lineNumber; diff --git a/lib/checkunusedfunctions.h b/lib/checkunusedfunctions.h index a620cee8d..d78c25a47 100644 --- a/lib/checkunusedfunctions.h +++ b/lib/checkunusedfunctions.h @@ -29,8 +29,7 @@ /// @addtogroup Checks /// @{ -class CheckUnusedFunctions: public Check -{ +class CheckUnusedFunctions: public Check { public: /** @brief This constructor is used when registering the CheckUnusedFunctions */ CheckUnusedFunctions() : Check(myName()) @@ -50,8 +49,7 @@ public: private: - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckUnusedFunctions c(0, settings, errorLogger); c.unusedFunctionError(errorLogger, "", 0, "funcName"); } @@ -66,23 +64,19 @@ private: /** * Dummy implementation, just to provide error for --errorlist */ - void runSimplifiedChecks(const Tokenizer *, const Settings *, ErrorLogger *) - { + void runSimplifiedChecks(const Tokenizer *, const Settings *, ErrorLogger *) { } - std::string myName() const - { + std::string myName() const { return "Unused functions"; } - std::string classInfo() const - { + std::string classInfo() const { return "Check for functions that are never called\n"; } - class FunctionUsage - { + class FunctionUsage { public: FunctionUsage() : lineNumber(0), usedSameFile(false), usedOtherFile(false) { } diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index b1bfe6c55..d96828e8b 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -24,23 +24,20 @@ //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) -namespace -{ -CheckUnusedVar instance; +namespace { + CheckUnusedVar instance; } /** * @brief This class is used to capture the control flow within a function. */ -class ScopeInfo -{ +class ScopeInfo { public: ScopeInfo() : _token(NULL), _parent(NULL) { } ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { } ~ScopeInfo(); - ScopeInfo *parent() - { + ScopeInfo *parent() { return _parent; } ScopeInfo *addChild(const Token *token); @@ -54,8 +51,7 @@ private: ScopeInfo::~ScopeInfo() { - while (!_children.empty()) - { + while (!_children.empty()) { delete *_children.begin(); _children.pop_front(); } @@ -74,10 +70,8 @@ void ScopeInfo::remove(ScopeInfo *scope) { std::list::iterator it; - for (it = _children.begin(); it != _children.end(); ++it) - { - if (*it == scope) - { + for (it = _children.begin(); it != _children.end(); ++it) { + if (*it == scope) { delete *it; _children.erase(it); break; @@ -88,14 +82,12 @@ void ScopeInfo::remove(ScopeInfo *scope) /** * @brief This class is used create a list of variables within a function. */ -class Variables -{ +class Variables { public: enum VariableType { standard, array, pointer, reference, pointerArray, referenceArray, pointerPointer }; /** Store information about variable usage */ - class VariableUsage - { + class VariableUsage { public: VariableUsage(const Token *name = 0, VariableType type = standard, @@ -110,20 +102,17 @@ public: _read(read), _write(write), _modified(modified), - _allocateMemory(allocateMemory) - { + _allocateMemory(allocateMemory) { } /** variable is used.. set both read+write */ - void use() - { + void use() { _read = true; _write = true; } /** is variable unused? */ - bool unused() const - { + bool unused() const { return (_read == false && _write == false); } @@ -140,12 +129,10 @@ public: typedef std::map VariableMap; - void clear() - { + void clear() { _varUsage.clear(); } - VariableMap &varUsage() - { + VariableMap &varUsage() { return _varUsage; } void addVar(const Token *name, VariableType type, ScopeInfo *scope, bool write_); @@ -160,8 +147,7 @@ public: void modified(unsigned int varid); VariableUsage *find(unsigned int varid); void alias(unsigned int varid1, unsigned int varid2, bool replace); - void erase(unsigned int varid) - { + void erase(unsigned int varid) { _varUsage.erase(varid); } void eraseAliases(unsigned int varid); @@ -185,8 +171,7 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) VariableUsage *var2 = find(varid2); // alias to self - if (varid1 == varid2) - { + if (varid1 == varid2) { if (var1) var1->use(); return; @@ -194,11 +179,9 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) std::set::iterator i; - if (replace) - { + if (replace) { // remove var1 from all aliases - for (i = var1->_aliases.begin(); i != var1->_aliases.end(); ++i) - { + for (i = var1->_aliases.begin(); i != var1->_aliases.end(); ++i) { VariableUsage *temp = find(*i); if (temp) @@ -210,8 +193,7 @@ void Variables::alias(unsigned int varid1, unsigned int varid2, bool replace) } // var1 gets all var2s aliases - for (i = var2->_aliases.begin(); i != var2->_aliases.end(); ++i) - { + for (i = var2->_aliases.begin(); i != var2->_aliases.end(); ++i) { if (*i != varid1) var1->_aliases.insert(*i); } @@ -228,13 +210,11 @@ void Variables::clearAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { // remove usage from all aliases std::set::iterator i; - for (i = usage->_aliases.begin(); i != usage->_aliases.end(); ++i) - { + for (i = usage->_aliases.begin(); i != usage->_aliases.end(); ++i) { VariableUsage *temp = find(*i); if (temp) @@ -250,8 +230,7 @@ void Variables::eraseAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) @@ -294,12 +273,10 @@ void Variables::readAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -312,14 +289,12 @@ void Variables::readAll(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_read = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -340,12 +315,10 @@ void Variables::writeAliases(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -358,14 +331,12 @@ void Variables::writeAll(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_write = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -378,14 +349,12 @@ void Variables::use(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->use(); std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -398,14 +367,12 @@ void Variables::modified(unsigned int varid) { VariableUsage *usage = find(varid); - if (usage) - { + if (usage) { usage->_modified = true; std::set::iterator aliases; - for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) - { + for (aliases = usage->_aliases.begin(); aliases != usage->_aliases.end(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) @@ -416,8 +383,7 @@ void Variables::modified(unsigned int varid) Variables::VariableUsage *Variables::find(unsigned int varid) { - if (varid) - { + if (varid) { VariableMap::iterator i = _varUsage.find(varid); if (i != _varUsage.end()) return &i->second; @@ -430,8 +396,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference int next = 0; // a = a + b; - if (Token::Match(tok, "%var% = %var% !!;") && tok->str() == tok->strAt(2)) - { + if (Token::Match(tok, "%var% = %var% !!;") && tok->str() == tok->strAt(2)) { return 2; } @@ -439,8 +404,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference const unsigned int varid1 = tok->varId(); Variables::VariableUsage *var1 = variables.find(varid1); - if (var1) - { + if (var1) { Variables::VariableUsage *var2 = 0; int start = 1; @@ -453,8 +417,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (Token::Match(tok->tokAt(start), "&| %var%") || Token::Match(tok->tokAt(start), "( const| struct|union| %type% *| ) &| %var%") || Token::Match(tok->tokAt(start), "( const| struct|union| %type% *| ) ( &| %var%") || - Token::Match(tok->tokAt(start), "%any% < const| struct|union| %type% *| > ( &| %var%")) - { + Token::Match(tok->tokAt(start), "%any% < const| struct|union| %type% *| > ( &| %var%")) { unsigned char offset = 0; unsigned int varid2; bool addressOf = false; @@ -463,8 +426,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference variables.use(tok->tokAt(start)->varId()); // use = read + write // check for C style cast - if (tok->tokAt(start)->str() == "(") - { + if (tok->tokAt(start)->str() == "(") { if (tok->tokAt(start + 1)->str() == "const") offset++; @@ -474,29 +436,22 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (tok->tokAt(start + 2 + offset)->str() == "*") offset++; - if (tok->tokAt(start + 3 + offset)->str() == "&") - { + if (tok->tokAt(start + 3 + offset)->str() == "&") { addressOf = true; next = start + 4 + offset; - } - else if (tok->tokAt(start + 3 + offset)->str() == "(") - { - if (tok->tokAt(start + 4 + offset)->str() == "&") - { + } else if (tok->tokAt(start + 3 + offset)->str() == "(") { + if (tok->tokAt(start + 4 + offset)->str() == "&") { addressOf = true; next = start + 5 + offset; - } - else + } else next = start + 4 + offset; - } - else + } else next = start + 3 + offset; } // check for C++ style cast else if (tok->tokAt(start)->str().find("cast") != std::string::npos && - tok->tokAt(start + 1)->str() == "<") - { + tok->tokAt(start + 1)->str() == "<") { if (tok->tokAt(start + 2)->str() == "const") offset++; @@ -506,30 +461,24 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference if (tok->tokAt(start + 3 + offset)->str() == "*") offset++; - if (tok->tokAt(start + 5 + offset)->str() == "&") - { + if (tok->tokAt(start + 5 + offset)->str() == "&") { addressOf = true; next = start + 6 + offset; - } - else + } else next = start + 5 + offset; } // check for var ? ... - else if (Token::Match(tok->tokAt(start), "%var% ?")) - { + else if (Token::Match(tok->tokAt(start), "%var% ?")) { next = start; } // no cast - else - { - if (tok->tokAt(start)->str() == "&") - { + else { + if (tok->tokAt(start)->str() == "&") { addressOf = true; next = start + 1; - } - else if (tok->tokAt(start)->str() == "new") + } else if (tok->tokAt(start)->str() == "new") return 0; else next = start; @@ -539,18 +488,14 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference varid2 = tok->tokAt(next)->varId(); var2 = variables.find(varid2); - if (var2) // local variable (alias or read it) - { - if (var1->_type == Variables::pointer) - { + if (var2) { // local variable (alias or read it) + if (var1->_type == Variables::pointer) { if (dereference) variables.read(varid2); - else - { + else { if (addressOf || var2->_type == Variables::array || - var2->_type == Variables::pointer) - { + var2->_type == Variables::pointer) { bool replace = true; // check if variable declared in same scope @@ -558,23 +503,20 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference replace = true; // not in same scope as declaration - else - { + else { std::set::iterator assignment; // check for an assignment in this scope assignment = var1->_assignments.find(scope); // no other assignment in this scope - if (assignment == var1->_assignments.end()) - { + if (assignment == var1->_assignments.end()) { // nothing to replace if (var1->_assignments.empty()) replace = false; // this variable has previous assignments - else - { + else { /** * @todo determine if existing aliases should be replaced or merged */ @@ -584,8 +526,7 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference } // assignment in this scope - else - { + else { // replace when only one other assignment if (var1->_assignments.size() == 1) replace = true; @@ -597,53 +538,41 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference } variables.alias(varid1, varid2, replace); - } - else if (tok->tokAt(next + 1)->str() == "?") - { + } else if (tok->tokAt(next + 1)->str() == "?") { if (var2->_type == Variables::reference) variables.readAliases(varid2); else variables.read(varid2); } } - } - else if (var1->_type == Variables::reference) - { + } else if (var1->_type == Variables::reference) { variables.alias(varid1, varid2, true); - } - else - { + } else { if (var2->_type == Variables::pointer && tok->tokAt(next + 1)->str() == "[") variables.readAliases(varid2); variables.read(varid2); } - } - else // not a local variable (or an unsupported local variable) - { - if (var1->_type == Variables::pointer && !dereference) - { + } else { // not a local variable (or an unsupported local variable) + if (var1->_type == Variables::pointer && !dereference) { // check if variable declaration is in this scope if (var1->_scope == scope) variables.clearAliases(varid1); - else - { + else { std::set::iterator assignment; // check for an assignment in this scope assignment = var1->_assignments.find(scope); // no other assignment in this scope - if (assignment == var1->_assignments.end()) - { + if (assignment == var1->_assignments.end()) { /** * @todo determine if existing aliases should be discarded */ } // this assignment replaces the last assignment in this scope - else - { + else { // aliased variables in a larger scope are not supported // remove all aliases variables.clearAliases(varid1); @@ -658,17 +587,14 @@ static int doAssignment(Variables &variables, const Token *tok, bool dereference // check for alias to struct member // char c[10]; a.b = c; - else if (Token::Match(tok->tokAt(-2), "%var% .")) - { - if (Token::Match(tok->tokAt(2), "%var%")) - { + else if (Token::Match(tok->tokAt(-2), "%var% .")) { + if (Token::Match(tok->tokAt(2), "%var%")) { unsigned int varid2 = tok->tokAt(2)->varId(); Variables::VariableUsage *var2 = variables.find(varid2); // struct member aliased to local variable if (var2 && (var2->_type == Variables::array || - var2->_type == Variables::pointer)) - { + var2->_type == Variables::pointer)) { // erase aliased variable and all variables that alias it // to prevent false positives variables.eraseAll(varid2); @@ -730,8 +656,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() std::list::const_iterator scope; - for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) - { + for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { // only check functions if (scope->type != Scope::eFunction) continue; @@ -747,10 +672,8 @@ void CheckUnusedVar::checkFunctionVariableUsage() ScopeInfo *info = &scopes; unsigned int indentlevel = 0; - for (const Token *tok = tok1; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (const Token *tok = tok1; tok; tok = tok->next()) { + if (tok->str() == "{") { // replace the head node when found if (indentlevel == 0) scopes = ScopeInfo(tok, NULL); @@ -758,19 +681,15 @@ void CheckUnusedVar::checkFunctionVariableUsage() else info = info->addChild(tok); ++indentlevel; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --indentlevel; info = info->parent(); if (indentlevel == 0) break; - } - else if (Token::Match(tok, "struct|union|class {") || - Token::Match(tok, "struct|union|class %type% {|:")) - { + } else if (Token::Match(tok, "struct|union|class {") || + Token::Match(tok, "struct|union|class %type% {|:")) { while (tok->str() != "{") tok = tok->next(); tok = tok->link(); @@ -778,8 +697,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() break; } - if (Token::Match(tok, "[;{}] asm ( ) ;")) - { + if (Token::Match(tok, "[;{}] asm ( ) ;")) { variables.clear(); break; } @@ -787,16 +705,14 @@ void CheckUnusedVar::checkFunctionVariableUsage() // standard type declaration with possible initialization // int i; int j = 0; static int k; if (Token::Match(tok, "[;{}] static| %type% %var% ;|=") && - !Token::Match(tok->next(), "return|throw")) - { + !Token::Match(tok->next(), "return|throw")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; if (isStatic) tok = tok->next(); - if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) - { + if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) { variables.addVar(tok->next(), Variables::standard, info, tok->tokAt(2)->str() == "=" || isStatic); } @@ -805,8 +721,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // standard const type declaration // const int i = x; - else if (Token::Match(tok, "[;{}] const %type% %var% =")) - { + else if (Token::Match(tok, "[;{}] const %type% %var% =")) { tok = tok->next()->next(); if (tok->isStandardType() || isRecordTypeWithoutSideEffects(tok->next())) @@ -817,8 +732,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // std::string declaration with possible initialization // std::string s; std::string s = "string"; - else if (Token::Match(tok, "[;{}] static| std :: string %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| std :: string %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -833,8 +747,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // standard struct type declaration with possible initialization // struct S s; struct S s = { 0 }; static struct S s; else if (Token::Match(tok, "[;{}] static| struct %type% %var% ;|=") && - (isRecordTypeWithoutSideEffects(tok->strAt(1) == "static" ? tok->tokAt(4) : tok->tokAt(3)))) - { + (isRecordTypeWithoutSideEffects(tok->strAt(1) == "static" ? tok->tokAt(4) : tok->tokAt(3)))) { tok = tok->next(); bool isStatic = tok->str() == "static"; @@ -851,8 +764,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // standard type declaration and initialization using constructor // int i(0); static int j(0); else if (Token::Match(tok, "[;{}] static| %type% %var% ( %any% ) ;") && - nextIsStandardType(tok)) - { + nextIsStandardType(tok)) { tok = tok->next(); if (tok->str() == "static") @@ -869,8 +781,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // standard type declaration of array of with possible initialization // int i[10]; int j[2] = { 0, 1 }; static int k[2] = { 2, 3 }; else if (Token::Match(tok, "[;{}] static| const| %type% *| %var% [ %any% ] ;|=") && - nextIsStandardType(tok)) - { + nextIsStandardType(tok)) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -880,8 +791,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return" && tok->str() != "throw") - { + if (tok->str() != "return" && tok->str() != "throw") { bool isPointer = bool(tok->strAt(1) == "*"); const Token * const nametok = tok->tokAt(isPointer ? 2 : 1); @@ -893,25 +803,21 @@ void CheckUnusedVar::checkFunctionVariableUsage() variables.read(nametok->tokAt(2)->varId()); // look at initializers - if (Token::simpleMatch(nametok->tokAt(4), "= {")) - { + if (Token::simpleMatch(nametok->tokAt(4), "= {")) { tok = nametok->tokAt(6); - while (tok->str() != "}") - { + while (tok->str() != "}") { if (Token::Match(tok, "%var%")) variables.read(tok->varId()); tok = tok->next(); } - } - else + } else tok = nametok->tokAt(3); } } // pointer or reference declaration with possible initialization // int * i; int * j = 0; static int * k = 0; - else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -924,8 +830,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() if (tok->strAt(1) == "::") tok = tok->tokAt(2); - if (tok->str() != "return" && tok->str() != "throw") - { + if (tok->str() != "return" && tok->str() != "throw") { Variables::VariableType type; if (tok->next()->str() == "*") @@ -949,8 +854,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // pointer to pointer declaration with possible initialization // int ** i; int ** j = 0; static int ** k = 0; - else if (Token::Match(tok, "[;{}] static| const| %type% * * %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% * * %var% ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -960,8 +864,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return") - { + if (tok->str() != "return") { bool written = tok->tokAt(4)->str() == "="; variables.addVar(tok->tokAt(3), Variables::pointerPointer, info, written || isStatic); @@ -978,8 +881,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // pointer or reference of struct or union declaration with possible initialization // struct s * i; struct s * j = 0; static struct s * k = 0; - else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% ;|=")) { Variables::VariableType type; tok = tok->next(); @@ -1012,8 +914,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // pointer or reference declaration with initialization using constructor // int * i(j); int * k(i); static int * l(i); else if (Token::Match(tok, "[;{}] static| const| %type% &|* %var% ( %any% ) ;") && - nextIsStandardTypeOrVoid(tok)) - { + nextIsStandardTypeOrVoid(tok)) { Variables::VariableType type; tok = tok->next(); @@ -1038,20 +939,16 @@ void CheckUnusedVar::checkFunctionVariableUsage() variables.addVar(tok->tokAt(2), type, info, true); // check if a local variable is used to initialize this variable - if (varid > 0) - { + if (varid > 0) { Variables::VariableUsage *var = variables.find(varid); - if (type == Variables::pointer) - { + if (type == Variables::pointer) { variables.use(tok->tokAt(4)->varId()); if (var && (var->_type == Variables::array || var->_type == Variables::pointer)) var->_aliases.insert(tok->varId()); - } - else - { + } else { variables.readAll(tok->tokAt(4)->varId()); if (var) var->_aliases.insert(tok->varId()); @@ -1062,8 +959,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // array of pointer or reference declaration with possible initialization // int * p[10]; int * q[10] = { 0 }; static int * * r[10] = { 0 }; - else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% [ %any% ] ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| %type% *|& %var% [ %any% ] ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -1073,8 +969,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() if (tok->str() == "const") tok = tok->next(); - if (tok->str() != "return") - { + if (tok->str() != "return") { variables.addVar(tok->tokAt(2), tok->next()->str() == "*" ? Variables::pointerArray : Variables::referenceArray, info, tok->tokAt(6)->str() == "=" || isStatic); @@ -1089,8 +984,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // array of pointer or reference of struct or union declaration with possible initialization // struct S * p[10]; struct T * q[10] = { 0 }; static struct S * r[10] = { 0 }; - else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% [ %any% ] ;|=")) - { + else if (Token::Match(tok, "[;{}] static| const| struct|union %type% *|& %var% [ %any% ] ;|=")) { tok = tok->next(); const bool isStatic = tok->str() == "static"; @@ -1114,28 +1008,21 @@ void CheckUnusedVar::checkFunctionVariableUsage() // Freeing memory (not considered "using" the pointer if it was also allocated in this function) else if (Token::Match(tok, "free|g_free|kfree|vfree ( %var% )") || Token::Match(tok, "delete %var% ;") || - Token::Match(tok, "delete [ ] %var% ;")) - { + Token::Match(tok, "delete [ ] %var% ;")) { unsigned int varid = 0; - if (tok->str() != "delete") - { + if (tok->str() != "delete") { varid = tok->tokAt(2)->varId(); tok = tok->tokAt(3); - } - else if (tok->strAt(1) == "[") - { + } else if (tok->strAt(1) == "[") { varid = tok->tokAt(3)->varId(); tok = tok->tokAt(4); - } - else - { + } else { varid = tok->next()->varId(); tok = tok->tokAt(2); } Variables::VariableUsage *var = variables.find(varid); - if (var && !var->_allocateMemory) - { + if (var && !var->_allocateMemory) { variables.readAll(varid); } } @@ -1146,14 +1033,12 @@ void CheckUnusedVar::checkFunctionVariableUsage() // assignment else if (!Token::Match(tok->tokAt(-2), "[;{}.] %var% (") && (Token::Match(tok, "*| (| ++|--| %var% ++|--| )| =") || - Token::Match(tok, "*| ( const| %type% *| ) %var% ="))) - { + Token::Match(tok, "*| ( const| %type% *| ) %var% ="))) { bool dereference = false; bool pre = false; bool post = false; - if (tok->str() == "*") - { + if (tok->str() == "*") { dereference = true; tok = tok->next(); } @@ -1164,8 +1049,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() else if (tok->str() == "(") tok = tok->next(); - if (Token::Match(tok, "++|--")) - { + if (Token::Match(tok, "++|--")) { pre = true; tok = tok->next(); } @@ -1181,30 +1065,24 @@ void CheckUnusedVar::checkFunctionVariableUsage() if (pre || post) variables.use(varid1); - if (dereference) - { + if (dereference) { Variables::VariableUsage *var = variables.find(varid1); if (var && var->_type == Variables::array) variables.write(varid1); variables.writeAliases(varid1); variables.read(varid1); - } - else - { + } else { Variables::VariableUsage *var = variables.find(varid1); - if (var && var->_type == Variables::reference) - { + if (var && var->_type == Variables::reference) { variables.writeAliases(varid1); variables.read(varid1); } // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable else if (var && var->_type == Variables::pointer && - Token::Match(start, "%var% = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) - { + Token::Match(start, "%var% = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) { bool allocate = true; - if (start->strAt(2) == "new") - { + if (start->strAt(2) == "new") { const Token *type = start->tokAt(3); // skip nothrow @@ -1213,8 +1091,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() type = type->link()->next(); // is it a user defined type? - if (!type->isStandardType()) - { + if (!type->isStandardType()) { if (!isRecordTypeWithoutSideEffects(start)) allocate = false; } @@ -1224,25 +1101,18 @@ void CheckUnusedVar::checkFunctionVariableUsage() variables.allocateMemory(varid1); else variables.write(varid1); - } - else if (varid1 && Token::Match(tok, "%varid% .", varid1)) - { + } else if (varid1 && Token::Match(tok, "%varid% .", varid1)) { variables.use(varid1); - } - else - { + } else { variables.write(varid1); } Variables::VariableUsage *var2 = variables.find(tok->varId()); - if (var2) - { - if (var2->_type == Variables::reference) - { + if (var2) { + if (var2->_type == Variables::reference) { variables.writeAliases(tok->varId()); variables.read(tok->varId()); - } - else if (tok->varId() != varid1 && Token::Match(tok, "%var% .")) + } else if (tok->varId() != varid1 && Token::Match(tok, "%var% .")) variables.read(tok->varId()); else if (tok->varId() != varid1 && var2->_type == Variables::standard && @@ -1257,8 +1127,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() equal = tok->tokAt(4); // checked for chained assignments - if (tok != start && equal->str() == "=") - { + if (tok != start && equal->str() == "=") { Variables::VariableUsage *var = variables.find(tok->varId()); if (var && var->_type != Variables::reference) @@ -1269,25 +1138,19 @@ void CheckUnusedVar::checkFunctionVariableUsage() } // assignment - else if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->next()->link(), "] =")) - { + else if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->next()->link(), "] =")) { unsigned int varid = tok->varId(); const Variables::VariableUsage *var = variables.find(varid); - if (var) - { + if (var) { // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable if (var->_type == Variables::pointer && - Token::Match(tok->next()->link(), "] = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) - { + Token::Match(tok->next()->link(), "] = new|malloc|calloc|g_malloc|kmalloc|vmalloc")) { variables.allocateMemory(varid); - } - else if (var->_type == Variables::pointer || var->_type == Variables::reference) - { + } else if (var->_type == Variables::pointer || var->_type == Variables::reference) { variables.read(varid); variables.writeAliases(varid); - } - else + } else variables.writeAll(varid); } } @@ -1307,8 +1170,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() variables.use(tok->next()->link()->next()->varId()); // use = read + write // function - else if (Token::Match(tok, "%var% (")) - { + else if (Token::Match(tok, "%var% (")) { variables.read(tok->varId()); if (Token::Match(tok->tokAt(2), "%var% =")) variables.read(tok->tokAt(2)->varId()); @@ -1330,28 +1192,23 @@ void CheckUnusedVar::checkFunctionVariableUsage() else if (Token::Match(tok, "; %var% ;")) variables.readAll(tok->next()->varId()); - else if (Token::Match(tok, "++|-- %var%")) - { + else if (Token::Match(tok, "++|-- %var%")) { if (tok->strAt(-1) != ";") variables.use(tok->next()->varId()); else variables.modified(tok->next()->varId()); } - else if (Token::Match(tok, "%var% ++|--")) - { + else if (Token::Match(tok, "%var% ++|--")) { if (tok->strAt(-1) != ";") variables.use(tok->varId()); else variables.modified(tok->varId()); } - else if (tok->isAssignmentOp()) - { - for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) - { - if (tok2->varId()) - { + else if (tok->isAssignmentOp()) { + for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { + if (tok2->varId()) { variables.read(tok2->varId()); if (tok2->next()->isAssignmentOp()) variables.write(tok2->varId()); @@ -1362,8 +1219,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() // Check usage of all variables in the current scope.. Variables::VariableMap::const_iterator it; - for (it = variables.varUsage().begin(); it != variables.varUsage().end(); ++it) - { + for (it = variables.varUsage().begin(); it != variables.varUsage().end(); ++it) { const Variables::VariableUsage &usage = it->second; const std::string &varname = usage._name->str(); @@ -1430,13 +1286,11 @@ void CheckUnusedVar::checkStructMemberUsage() return; std::string structname; - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (tok->fileIndex() != 0) continue; - if (Token::Match(tok, "struct|union %type% {")) - { + if (Token::Match(tok, "struct|union %type% {")) { structname.clear(); if (Token::simpleMatch(tok->previous(), "extern")) continue; @@ -1446,10 +1300,8 @@ void CheckUnusedVar::checkStructMemberUsage() structname = tok->strAt(1); // Bail out if struct/union contain any functions - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "(") - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == "(") { structname.clear(); break; } @@ -1477,8 +1329,7 @@ void CheckUnusedVar::checkStructMemberUsage() if (tok->str() == "}") structname.clear(); - if (!structname.empty() && Token::Match(tok, "[{;]")) - { + if (!structname.empty() && Token::Match(tok, "[{;]")) { // Declaring struct variable.. std::string varname; @@ -1500,17 +1351,14 @@ void CheckUnusedVar::checkStructMemberUsage() // Check if the struct variable is used anywhere in the file const std::string usagePattern(". " + varname); bool used = false; - for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) - { - if (Token::simpleMatch(tok2, usagePattern.c_str())) - { + for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) { + if (Token::simpleMatch(tok2, usagePattern.c_str())) { used = true; break; } } - if (! used) - { + if (! used) { unusedStructMemberError(tok->next(), structname, varname); } } diff --git a/lib/checkunusedvar.h b/lib/checkunusedvar.h index c7fb76dad..97260581b 100644 --- a/lib/checkunusedvar.h +++ b/lib/checkunusedvar.h @@ -33,8 +33,7 @@ class Token; /** @brief Various small checks */ -class CheckUnusedVar : public Check -{ +class CheckUnusedVar : public Check { public: /** @brief This constructor is used when registering the CheckClass */ CheckUnusedVar() : Check(myName()) @@ -46,8 +45,7 @@ public: { } /** @brief Run checks against the normal token list */ - void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckUnusedVar checkUnusedVar(tokenizer, settings, errorLogger); // Coding style checks @@ -56,8 +54,7 @@ public: } /** @brief Run checks against the simplified token list */ - void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - { + void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckUnusedVar checkUnusedVar(tokenizer, settings, errorLogger); } @@ -74,8 +71,7 @@ public: void unreadVariableError(const Token *tok, const std::string &varname); void unassignedVariableError(const Token *tok, const std::string &varname); - void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) - { + void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) { CheckUnusedVar c(0, settings, errorLogger); // style/warning @@ -86,13 +82,11 @@ public: c.unusedStructMemberError(0, "structname", "variable"); } - std::string myName() const - { + std::string myName() const { return "UnusedVar"; } - std::string classInfo() const - { + std::string classInfo() const { return "UnusedVar checks\n" // style diff --git a/lib/cppcheck.cpp b/lib/cppcheck.cpp index 766c9d476..7de38609f 100644 --- a/lib/cppcheck.cpp +++ b/lib/cppcheck.cpp @@ -85,8 +85,7 @@ unsigned int CppCheck::check(const std::string &path, const std::string &content std::string CppCheck::replaceAll(std::string code, const std::string &from, const std::string &to) { size_t pos = 0; - while ((pos = code.find(from, pos)) != std::string::npos) - { + while ((pos = code.find(from, pos)) != std::string::npos) { code.replace(pos, from.length(), to); pos += to.length(); } @@ -98,25 +97,20 @@ bool CppCheck::findError(std::string code, const char FileName[]) { // First make sure that error occurs with the original code checkFile(code, FileName); - if (_errorList.empty()) - { + if (_errorList.empty()) { // Error does not occur with this code return false; } std::string previousCode = code; std::string error = _errorList.front(); - for (;;) - { + for (;;) { // Try to remove included files from the source size_t found=previousCode.rfind("\n#endfile"); - if (found == std::string::npos) - { + if (found == std::string::npos) { // No modifications can be done to the code - } - else - { + } else { // Modify code and re-check it to see if error // is still there. code = previousCode.substr(found+9); @@ -124,14 +118,11 @@ bool CppCheck::findError(std::string code, const char FileName[]) checkFile(code, FileName); } - if (_errorList.empty()) - { + if (_errorList.empty()) { // Latest code didn't fail anymore. Fall back // to previous code code = previousCode; - } - else - { + } else { error = _errorList.front(); } @@ -155,8 +146,7 @@ unsigned int CppCheck::processFile() // TODO: Should this be moved out to its own function so all the files can be // analysed before any files are checked? - if (_settings.test_2_pass && _settings._jobs == 1) - { + if (_settings.test_2_pass && _settings._jobs == 1) { const std::string printname = Path::toNativeSeparators(_filename); reportOut("Analysing " + printname + "..."); @@ -169,54 +159,45 @@ unsigned int CppCheck::processFile() if (_settings.terminated()) return exitcode; - if (_settings._errorsOnly == false) - { + if (_settings._errorsOnly == false) { std::string fixedpath(_filename); fixedpath = Path::simplifyPath(fixedpath.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("...")); } - try - { + try { Preprocessor preprocessor(&_settings, this); std::list configurations; std::string filedata = ""; - if (!_fileContent.empty()) - { + if (!_fileContent.empty()) { // File content was given as a string std::istringstream iss(_fileContent); preprocessor.preprocess(iss, filedata, configurations, _filename, _settings._includePaths); - } - else - { + } else { // Only file name was given, read the content from file std::ifstream fin(_filename.c_str()); Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults); preprocessor.preprocess(fin, filedata, configurations, _filename, _settings._includePaths); } - if (_settings.checkConfiguration) - { + if (_settings.checkConfiguration) { return 0; } _settings.ifcfg = bool(configurations.size() > 1); - if (!_settings.userDefines.empty()) - { + if (!_settings.userDefines.empty()) { configurations.clear(); configurations.push_back(_settings.userDefines); } int checkCount = 0; - for (std::list::const_iterator it = configurations.begin(); it != configurations.end(); ++it) - { + for (std::list::const_iterator it = configurations.begin(); it != configurations.end(); ++it) { // Check only 12 first configurations, after that bail out, unless --force // was used. - if (!_settings._force && checkCount > 11) - { + if (!_settings._force && checkCount > 11) { const std::string fixedpath = Path::toNativeSeparators(_filename); ErrorLogger::ErrorMessage::FileLocation location; @@ -234,8 +215,7 @@ unsigned int CppCheck::processFile() "toomanyconfigs", false); - if (!_settings.nomsg.isSuppressedLocal(errmsg._id, fixedpath, location.line)) - { + if (!_settings.nomsg.isSuppressedLocal(errmsg._id, fixedpath, location.line)) { reportErr(errmsg); } @@ -248,8 +228,7 @@ unsigned int CppCheck::processFile() t.Stop(); // If only errors are printed, print filename after the check - if (_settings._errorsOnly == false && it != configurations.begin()) - { + if (_settings._errorsOnly == false && it != configurations.begin()) { std::string fixedpath = Path::simplifyPath(_filename.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("...")); @@ -259,23 +238,17 @@ unsigned int CppCheck::processFile() if (!appendCode.empty()) Preprocessor::preprocessWhitespaces(appendCode); - if (_settings.debugFalsePositive) - { - if (findError(codeWithoutCfg + appendCode, _filename.c_str())) - { + if (_settings.debugFalsePositive) { + if (findError(codeWithoutCfg + appendCode, _filename.c_str())) { return exitcode; } - } - else - { + } else { checkFile(codeWithoutCfg + appendCode, _filename.c_str()); } ++checkCount; } - } - catch (std::runtime_error &e) - { + } catch (std::runtime_error &e) { // Exception was thrown when checking this file.. const std::string fixedpath = Path::toNativeSeparators(_filename); _errorLogger.reportOut("Bailing out from checking " + fixedpath + ": " + e.what()); @@ -293,8 +266,7 @@ unsigned int CppCheck::processFile() void CppCheck::checkFunctionUsage() { // This generates false positives - especially for libraries - if (_settings.isEnabled("unusedFunction") && _settings._jobs == 1) - { + if (_settings.isEnabled("unusedFunction") && _settings._jobs == 1) { const bool verbose_orig = _settings._verbose; _settings._verbose = false; @@ -317,8 +289,7 @@ void CppCheck::analyseFile(std::istream &fin, const std::string &filename) preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths); const std::string code = Preprocessor::getcode(filedata, "", filename, &_settings, &_errorLogger); - if (_settings.checkConfiguration) - { + if (_settings.checkConfiguration) { return; } @@ -330,16 +301,14 @@ void CppCheck::analyseFile(std::istream &fin, const std::string &filename) // Analyse the tokens.. std::set data; - for (std::list::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) - { + for (std::list::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { (*it)->analyse(tokenizer.tokens(), data); } // Save analysis results.. // TODO: This loop should be protected by a mutex or something like that // The saveAnalysisData must _not_ be called from many threads at the same time. - for (std::list::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) - { + for (std::list::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { (*it)->saveAnalysisData(data); } } @@ -362,8 +331,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) Timer timer("Tokenizer::tokenize", _settings._showtime, &S_timerResults); result = _tokenizer.tokenize(istr, FileName, cfg); timer.Stop(); - if (!result) - { + if (!result) { // File had syntax errors, abort return; } @@ -373,8 +341,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) timer2.Stop(); // call all "runChecks" in all registered Check classes - for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) - { + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { if (_settings.terminated()) return; @@ -396,8 +363,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) _checkUnusedFunctions.parseTokens(_tokenizer); // call all "runSimplifiedChecks" in all registered Check classes - for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) - { + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { if (_settings.terminated()) return; @@ -407,14 +373,12 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) #ifdef HAVE_RULES // Are there extra rules? - if (!_settings.rules.empty()) - { + if (!_settings.rules.empty()) { std::ostringstream ostr; for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); const std::string str(ostr.str()); - for (std::list::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) - { + for (std::list::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) { const Settings::Rule &rule = *it; if (rule.pattern.empty() || rule.id.empty() || rule.severity.empty()) continue; @@ -422,8 +386,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) const char *error = 0; int erroffset = 0; pcre *re = pcre_compile(rule.pattern.c_str(),0,&error,&erroffset,NULL); - if (!re && error) - { + if (!re && error) { ErrorLogger::ErrorMessage errmsg(std::list(), Severity::error, error, @@ -437,8 +400,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) int pos = 0; int ovector[30]; - while (0 <= pcre_exec(re, NULL, str.c_str(), (int)str.size(), pos, 0, ovector, 30)) - { + while (0 <= pcre_exec(re, NULL, str.c_str(), (int)str.size(), pos, 0, ovector, 30)) { unsigned int pos1 = (unsigned int)ovector[0]; unsigned int pos2 = (unsigned int)ovector[1]; @@ -451,11 +413,9 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) loc.line = 0; unsigned int len = 0; - for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next()) { len = len + 1 + tok->str().size(); - if (len > pos1) - { + if (len > pos1) { loc.setfile(_tokenizer.getFiles()->at(tok->fileIndex())); loc.line = tok->linenr(); break; @@ -495,8 +455,7 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg) if (errmsg.empty()) return; - if (_settings.debugFalsePositive) - { + if (_settings.debugFalsePositive) { // Don't print out error _errorList.push_back(errmsg); return; @@ -508,19 +467,15 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg) std::string file; unsigned int line(0); - if (!msg._callStack.empty()) - { + if (!msg._callStack.empty()) { file = msg._callStack.back().getfile(false); line = msg._callStack.back().line; } - if (_useGlobalSuppressions) - { + if (_useGlobalSuppressions) { if (_settings.nomsg.isSuppressed(msg._id, file, line)) return; - } - else - { + } else { if (_settings.nomsg.isSuppressedLocal(msg._id, file, line)) return; } @@ -530,8 +485,7 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg) _errorList.push_back(errmsg); std::string errmsg2(errmsg); - if (_settings._verbose) - { + if (_settings._verbose) { errmsg2 += "\n Defines=\'" + cfg + "\'\n"; } diff --git a/lib/cppcheck.h b/lib/cppcheck.h index 73a5ccc05..d9a1b7a0f 100644 --- a/lib/cppcheck.h +++ b/lib/cppcheck.h @@ -37,8 +37,7 @@ * errors or places that could be improved. * Usage: See check() for more info. */ -class CppCheck : public ErrorLogger -{ +class CppCheck : public ErrorLogger { public: /** * @brief Constructor. @@ -118,8 +117,7 @@ public: /** * @brief Terminate checking. The checking will be terminated as soon as possible. */ - void terminate() - { + void terminate() { _settings.terminate(); } diff --git a/lib/errorlogger.cpp b/lib/errorlogger.cpp index 76e368c06..7de154108 100644 --- a/lib/errorlogger.cpp +++ b/lib/errorlogger.cpp @@ -52,13 +52,10 @@ void ErrorLogger::ErrorMessage::setmsg(const std::string &msg) // If there is no newline then both the summary and verbose messages // are the given message const std::string::size_type pos = msg.find("\n"); - if (pos == std::string::npos) - { + if (pos == std::string::npos) { _shortMessage = msg; _verboseMessage = msg; - } - else - { + } else { _shortMessage = msg.substr(0, pos); _verboseMessage = msg.substr(pos + 1); } @@ -70,8 +67,7 @@ std::string ErrorLogger::ErrorMessage::serialize() const std::ostringstream oss; oss << _id.length() << " " << _id; oss << Severity::toString(_severity).length() << " " << Severity::toString(_severity); - if (_inconclusive) - { + if (_inconclusive) { const std::string inconclusive("inconclusive"); oss << inconclusive.length() << " " << inconclusive; } @@ -79,8 +75,7 @@ std::string ErrorLogger::ErrorMessage::serialize() const oss << _verboseMessage.length() << " " << _verboseMessage; oss << _callStack.size() << " "; - for (std::list::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok) - { + for (std::list::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok) { std::ostringstream smallStream; smallStream << (*tok).line << ":" << (*tok).getfile(); oss << smallStream.str().length() << " " << smallStream.str(); @@ -95,22 +90,19 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data) _callStack.clear(); std::istringstream iss(data); std::vector results; - while (iss.good()) - { + while (iss.good()) { unsigned int len = 0; if (!(iss >> len)) return false; iss.get(); std::string temp; - for (unsigned int i = 0; i < len && iss.good(); ++i) - { + for (unsigned int i = 0; i < len && iss.good(); ++i) { char c = static_cast(iss.get()); temp.append(1, c); } - if (temp == "inconclusive") - { + if (temp == "inconclusive") { _inconclusive = true; continue; } @@ -129,16 +121,14 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data) if (!(iss >> stackSize)) return false; - while (iss.good()) - { + while (iss.good()) { unsigned int len = 0; if (!(iss >> len)) return false; iss.get(); std::string temp; - for (unsigned int i = 0; i < len && iss.good(); ++i) - { + for (unsigned int i = 0; i < len && iss.good(); ++i) { char c = static_cast(iss.get()); temp.append(1, c); } @@ -167,14 +157,12 @@ std::string ErrorLogger::ErrorMessage::getXMLHeader(int xml_version) ostr << "\n"; // version 1 header - if (xml_version <= 1) - { + if (xml_version <= 1) { ostr << ""; } // version 2 header - else - { + else { ostr << "\n"; ostr << " \n"; ostr << " "; @@ -192,8 +180,7 @@ static std::string stringToXml(std::string s) { // convert a string so it can be save as xml attribute data std::string::size_type pos = 0; - while ((pos = s.find_first_of("<>&\"\n", pos)) != std::string::npos) - { + while ((pos = s.find_first_of("<>&\"\n", pos)) != std::string::npos) { if (s[pos] == '<') s.insert(pos + 1, "<"); else if (s[pos] == '>') @@ -216,15 +203,13 @@ std::string ErrorLogger::ErrorMessage::toXML(bool verbose, int version) const std::ostringstream xml; // The default xml format - if (version == 1) - { + if (version == 1) { // No inconclusive messages in the xml version 1 if (_inconclusive) return ""; xml << "" << std::endl; - for (std::list::const_reverse_iterator it = _callStack.rbegin(); it != _callStack.rend(); ++it) - { + for (std::list::const_reverse_iterator it = _callStack.rbegin(); it != _callStack.rend(); ++it) { xml << " &unmatched) { - for (std::list::const_iterator i = unmatched.begin(); i != unmatched.end(); ++i) - { + for (std::list::const_iterator i = unmatched.begin(); i != unmatched.end(); ++i) { std::list callStack; callStack.push_back(ErrorLogger::ErrorMessage::FileLocation(i->file, i->line)); reportErr(ErrorLogger::ErrorMessage(callStack, Severity::information, "Unmatched suppression: " + i->id, "unmatchedSuppression", false)); @@ -326,8 +302,7 @@ void ErrorLogger::reportUnmatchedSuppressions(const std::list &callStack) { std::ostringstream ostr; - for (std::list::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok) - { + for (std::list::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok) { ostr << (tok == callStack.begin() ? "" : " -> ") << "[" << (*tok).getfile(); if ((*tok).line != 0) ostr << ":" << (*tok).line; diff --git a/lib/errorlogger.h b/lib/errorlogger.h index 8844c8269..bbc826599 100644 --- a/lib/errorlogger.h +++ b/lib/errorlogger.h @@ -33,14 +33,12 @@ class Tokenizer; /// @{ /** @brief enum class for severity. Used when reporting errors. */ -class Severity -{ +class Severity { public: /** * Message severities. */ - enum SeverityType - { + enum SeverityType { /** * No severity (default value). */ @@ -92,10 +90,8 @@ public: debug }; - static std::string toString(SeverityType severity) - { - switch (severity) - { + static std::string toString(SeverityType severity) { + switch (severity) { case none: return ""; case error: @@ -115,8 +111,7 @@ public: }; return "???"; } - static SeverityType fromString(const std::string &severity) - { + static SeverityType fromString(const std::string &severity) { if (severity.empty()) return none; if (severity == "none") @@ -143,32 +138,27 @@ public: * @brief This is an interface, which the class responsible of error logging * should implement. */ -class ErrorLogger -{ +class ErrorLogger { public: /** * Wrapper for error messages, provided by reportErr() */ - class ErrorMessage - { + class ErrorMessage { public: /** * File name and line number. * Internally paths are stored with / separator. When getting the filename * it is by default converted to native separators. */ - class FileLocation - { + class FileLocation { public: - FileLocation() - { + FileLocation() { line = 0; } FileLocation(const std::string &file, unsigned int aline) - : line(aline), _file(file) - { + : line(aline), _file(file) { } /** @@ -225,14 +215,12 @@ public: void setmsg(const std::string &msg); /** Short message (single line short message) */ - const std::string &shortMessage() const - { + const std::string &shortMessage() const { return _shortMessage; } /** Verbose message (may be the same as the short message) */ - const std::string &verboseMessage() const - { + const std::string &verboseMessage() const { return _verboseMessage; } @@ -279,8 +267,7 @@ public: * @param stage for example preprocess / tokenize / simplify / check * @param value progress value (0-100) */ - virtual void reportProgress(const std::string &filename, const char stage[], const unsigned int value) - { + virtual void reportProgress(const std::string &filename, const char stage[], const unsigned int value) { (void)filename; (void)stage; (void)value; diff --git a/lib/executionpath.cpp b/lib/executionpath.cpp index f719f14f0..4d39879f8 100644 --- a/lib/executionpath.cpp +++ b/lib/executionpath.cpp @@ -30,33 +30,25 @@ bool ExecutionPath::parseCondition(const Token &tok, std::list & checks) { unsigned int parlevel = 0; - for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel == 0) break; --parlevel; - } - else if (Token::Match(tok2, "[;{}]")) + } else if (Token::Match(tok2, "[;{}]")) break; - if (tok2->varId() != 0) - { + if (tok2->varId() != 0) { bailOutVar(checks, tok2->varId()); } } - for (std::list::iterator it = checks.begin(); it != checks.end();) - { - if ((*it)->varId > 0 && (*it)->numberOfIf >= 1) - { + for (std::list::iterator it = checks.begin(); it != checks.end();) { + if ((*it)->varId > 0 && (*it)->numberOfIf >= 1) { delete *it; checks.erase(it++); - } - else - { + } else { ++it; } } @@ -98,11 +90,9 @@ static void parseIfSwitchBody(const Token * const tok, { std::set countif2; std::list c; - if (!checks.empty()) - { + if (!checks.empty()) { std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { if ((*it)->numberOfIf == 0) c.push_back((*it)->copy()); if ((*it)->varId != 0) @@ -110,10 +100,8 @@ static void parseIfSwitchBody(const Token * const tok, } } ExecutionPath::checkScope(tok, c); - while (!c.empty()) - { - if (c.back()->varId == 0) - { + while (!c.empty()) { + if (c.back()->varId == 0) { delete c.back(); c.pop_back(); continue; @@ -121,10 +109,8 @@ static void parseIfSwitchBody(const Token * const tok, bool duplicate = false; std::list::const_iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { - if (*(*it) == *c.back() && (*it)->numberOfIf == c.back()->numberOfIf) - { + for (it = checks.begin(); it != checks.end(); ++it) { + if (*(*it) == *c.back() && (*it)->numberOfIf == c.back()->numberOfIf) { duplicate = true; countif2.erase((*it)->varId); break; @@ -149,13 +135,11 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che const std::auto_ptr check(checks.front()->copy()); - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { // might be a noreturn function.. if (Token::simpleMatch(tok->tokAt(-2), ") ; }") && Token::Match(tok->tokAt(-2)->link()->tokAt(-2), "[;{}] %var% (") && - tok->tokAt(-2)->link()->previous()->varId() == 0) - { + tok->tokAt(-2)->link()->previous()->varId() == 0) { ExecutionPath::bailOut(checks); return; } @@ -163,27 +147,22 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che if (tok->str() == "}") return; - if (tok->str() == "break") - { + if (tok->str() == "break") { ExecutionPath::bailOut(checks); return; } - if (Token::simpleMatch(tok, "while (")) - { + if (Token::simpleMatch(tok, "while (")) { // parse condition - if (checks.size() > 10 || check->parseCondition(*tok->tokAt(2), checks)) - { + if (checks.size() > 10 || check->parseCondition(*tok->tokAt(2), checks)) { ExecutionPath::bailOut(checks); return; } // skip "while (fgets()!=NULL)" - if (Token::simpleMatch(tok, "while ( fgets (")) - { + if (Token::simpleMatch(tok, "while ( fgets (")) { const Token *tok2 = tok->tokAt(3)->link(); - if (Token::simpleMatch(tok2, ") ) {")) - { + if (Token::simpleMatch(tok2, ") ) {")) { tok = tok2->tokAt(2)->link(); if (!tok) break; @@ -193,48 +172,40 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // goto/setjmp/longjmp => bailout - if (Token::Match(tok, "goto|setjmp|longjmp")) - { + if (Token::Match(tok, "goto|setjmp|longjmp")) { ExecutionPath::bailOut(checks); return; } // ?: => bailout - if (tok->str() == "?") - { - for (const Token *tok2 = tok; tok2 && tok2->str() != ";"; tok2 = tok2->next()) - { + if (tok->str() == "?") { + for (const Token *tok2 = tok; tok2 && tok2->str() != ";"; tok2 = tok2->next()) { if (tok2->varId() > 0) ExecutionPath::bailOutVar(checks, tok2->varId()); } } - if (tok->str() == "switch") - { + if (tok->str() == "switch") { // parse condition - if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) - { + if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) { ExecutionPath::bailOut(checks); return; } const Token *tok2 = tok->next()->link(); - if (Token::simpleMatch(tok2, ") { case")) - { + if (Token::simpleMatch(tok2, ") { case")) { // what variable ids should the if be counted for? std::set countif; std::list newchecks; - for (tok2 = tok2->tokAt(2); tok2; tok2 = tok2->next()) - { + for (tok2 = tok2->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") tok2 = tok2->link(); else if (tok2->str() == "}") break; else if (tok2->str() == "case" && - !Token::Match(tok2, "case %num% : ; case")) - { + !Token::Match(tok2, "case %num% : ; case")) { parseIfSwitchBody(tok2, checks, newchecks, countif); } } @@ -244,8 +215,7 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che // Increase numberOfIf std::list::iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { if (countif.find((*it)->varId) != countif.end()) (*it)->numberOfIf++; } @@ -253,31 +223,26 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // for/while/switch/do .. bail out - if (Token::Match(tok, "for|while|switch|do")) - { + if (Token::Match(tok, "for|while|switch|do")) { // goto { const Token *tok2 = tok->next(); if (tok2 && tok2->str() == "(") tok2 = tok2->link(); if (tok2 && tok2->str() == ")") tok2 = tok2->next(); - if (!tok2 || tok2->str() != "{") - { + if (!tok2 || tok2->str() != "{") { ExecutionPath::bailOut(checks); return; } - if (tok->str() != "switch") - { - for (const Token *tok3 = tok; tok3 && tok3 != tok2; tok3 = tok3->next()) - { + if (tok->str() != "switch") { + for (const Token *tok3 = tok; tok3 && tok3 != tok2; tok3 = tok3->next()) { if (tok3->varId()) ExecutionPath::bailOutVar(checks, tok3->varId()); } // it is not certain that a for/while will be executed: - for (std::list::iterator it = checks.begin(); it != checks.end();) - { + for (std::list::iterator it = checks.begin(); it != checks.end();) { if ((*it)->numberOfIf > 0) checks.erase(it++); else @@ -285,28 +250,22 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // #2231 - loop body only contains a conditional initialization.. - if (Token::simpleMatch(tok2->next(), "if (")) - { + if (Token::simpleMatch(tok2->next(), "if (")) { // Start { for the if block const Token *tok3 = tok2->tokAt(2)->link(); - if (Token::simpleMatch(tok3,") {")) - { + if (Token::simpleMatch(tok3,") {")) { tok3 = tok3->next(); // End } for the if block const Token *tok4 = tok3->link(); if (Token::Match(tok3, "{ %var% =") && Token::simpleMatch(tok4, "} }") && - Token::simpleMatch(tok4->tokAt(-2), "break ;")) - { + Token::simpleMatch(tok4->tokAt(-2), "break ;")) { // Is there a assignment and then a break? const Token *t = Token::findmatch(tok3, ";"); - if (t && t->tokAt(3) == tok4) - { - for (std::list::iterator it = checks.begin(); it != checks.end(); ++it) - { - if ((*it)->varId == tok3->next()->varId()) - { + if (t && t->tokAt(3) == tok4) { + for (std::list::iterator it = checks.begin(); it != checks.end(); ++it) { + if ((*it)->varId == tok3->next()->varId()) { (*it)->numberOfIf++; break; } @@ -331,8 +290,7 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che // bail out all variables if the scope contains a "return" // bail out all variables used in this for/while/switch/do - for (; tok && tok != tok2; tok = tok->next()) - { + for (; tok && tok != tok2; tok = tok->next()) { if (tok->str() == "return") ExecutionPath::bailOut(checks); if (tok->varId()) @@ -343,21 +301,17 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // bailout used variables in '; FOREACH ( .. ) { .. }' - else if (tok->str() != "if" && Token::Match(tok->previous(), "[;{}] %var% (")) - { + else if (tok->str() != "if" && Token::Match(tok->previous(), "[;{}] %var% (")) { // goto { const Token *tok2 = tok->next()->link(); - if (tok2 && tok2->str() == ")") - { + if (tok2 && tok2->str() == ")") { tok2 = tok2->next(); - if (tok2 && tok2->str() == "{") - { + if (tok2 && tok2->str() == "{") { // goto "}" tok2 = tok2->link(); // bail out all variables used in "{ .. }" - for (; tok && tok != tok2; tok = tok->next()) - { + for (; tok && tok != tok2; tok = tok->next()) { if (tok->varId()) ExecutionPath::bailOutVar(checks, tok->varId()); } @@ -366,43 +320,36 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // .. ) { ... } => bail out - if (Token::simpleMatch(tok, ") {")) - { + if (Token::simpleMatch(tok, ") {")) { ExecutionPath::bailOut(checks); return; } - if (Token::Match(tok, "abort|exit (")) - { + if (Token::Match(tok, "abort|exit (")) { ExecutionPath::bailOut(checks); return; } // don't parse into "struct type { .." - if (Token::Match(tok, "struct|union|class %type% {|:")) - { + if (Token::Match(tok, "struct|union|class %type% {|:")) { while (tok && tok->str() != "{" && tok->str() != ";") tok = tok->next(); tok = tok ? tok->link() : 0; - if (!tok) - { + if (!tok) { ExecutionPath::bailOut(checks); return; } } - if (Token::simpleMatch(tok, "= {")) - { + if (Token::simpleMatch(tok, "= {")) { // GCC struct initialization.. bail out - if (Token::Match(tok->tokAt(2), ". %var% =")) - { + if (Token::Match(tok->tokAt(2), ". %var% =")) { ExecutionPath::bailOut(checks); return; } tok = tok->next()->link(); - if (!tok) - { + if (!tok) { ExecutionPath::bailOut(checks); return; } @@ -410,27 +357,23 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che } // ; { ... } - if (Token::Match(tok->previous(), "[;{}] {")) - { + if (Token::Match(tok->previous(), "[;{}] {")) { ExecutionPath::checkScope(tok->next(), checks); tok = tok->link(); continue; } - if (tok->str() == "if") - { + if (tok->str() == "if") { // what variable ids should the numberOfIf be counted for? std::set countif; std::list newchecks; - while (tok->str() == "if") - { + while (tok->str() == "if") { // goto "(" tok = tok->next(); // parse condition - if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) - { + if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) { ExecutionPath::bailOut(checks); ExecutionPath::bailOut(newchecks); return; @@ -442,8 +385,7 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che // goto "{" tok = tok ? tok->next() : 0; - if (!Token::simpleMatch(tok, "{")) - { + if (!Token::simpleMatch(tok, "{")) { ExecutionPath::bailOut(checks); ExecutionPath::bailOut(newchecks); return; @@ -467,8 +409,7 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che // there is no "if".. ExecutionPath::checkScope(tok->next(), checks); tok = tok->link(); - if (!tok) - { + if (!tok) { ExecutionPath::bailOut(newchecks); return; } @@ -479,22 +420,17 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che // Increase numberOfIf std::list::iterator it; - for (it = checks.begin(); it != checks.end(); ++it) - { + for (it = checks.begin(); it != checks.end(); ++it) { if (countif.find((*it)->varId) != countif.end()) (*it)->numberOfIf++; } // Delete checks that have numberOfIf >= 2 - for (it = checks.begin(); it != checks.end();) - { - if ((*it)->varId > 0 && (*it)->numberOfIf >= 2) - { + for (it = checks.begin(); it != checks.end();) { + if ((*it)->varId > 0 && (*it)->numberOfIf >= 2) { delete *it; checks.erase(it++); - } - else - { + } else { ++it; } } @@ -511,8 +447,7 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che if (tok->str() == "return" || tok->str() == "throw" || tok->str() == "continue" || - tok->str() == "break") - { + tok->str() == "break") { ExecutionPath::bailOut(checks); } } @@ -520,14 +455,12 @@ void ExecutionPath::checkScope(const Token *tok, std::list &che void checkExecutionPaths(const Token *tok, ExecutionPath *c) { - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (tok->str() != ")") continue; // Start of implementation.. - if (Token::Match(tok, ") const| {")) - { + if (Token::Match(tok, ") const| {")) { // goto the "{" tok = tok->next(); if (tok->str() == "const") @@ -539,8 +472,7 @@ void checkExecutionPaths(const Token *tok, ExecutionPath *c) c->end(checks, tok->link()); - while (!checks.empty()) - { + while (!checks.empty()) { delete checks.back(); checks.pop_back(); } diff --git a/lib/executionpath.h b/lib/executionpath.h index bc296f4e7..4bc651d6f 100644 --- a/lib/executionpath.h +++ b/lib/executionpath.h @@ -28,8 +28,7 @@ class Check; * Base class for Execution Paths checking * An execution path is a linear list of statements. There are no "if"/.. to worry about. **/ -class ExecutionPath -{ +class ExecutionPath { private: /** No implementation */ void operator=(const ExecutionPath &); @@ -62,10 +61,8 @@ public: * bail out all execution paths * @param checks the execution paths to bail out on **/ - static void bailOut(std::list &checks) - { - while (!checks.empty()) - { + static void bailOut(std::list &checks) { + while (!checks.empty()) { delete checks.back(); checks.pop_back(); } @@ -76,21 +73,16 @@ public: * @param checks the execution paths to bail out on * @param varid the specific variable id **/ - static void bailOutVar(std::list &checks, const unsigned int varid) - { + static void bailOutVar(std::list &checks, const unsigned int varid) { if (varid == 0) return; std::list::iterator it = checks.begin(); - while (it != checks.end()) - { - if ((*it)->varId == varid) - { + while (it != checks.end()) { + if ((*it)->varId == varid) { delete *it; checks.erase(it++); - } - else - { + } else { ++it; } } @@ -117,8 +109,7 @@ public: * @param tok the first token in the loop body (the token after the {) * @param checks The execution paths */ - virtual void parseLoopBody(const Token *tok, std::list &checks) const - { + virtual void parseLoopBody(const Token *tok, std::list &checks) const { (void)tok; (void)checks; } @@ -127,8 +118,7 @@ public: virtual void end(const std::list & /*checks*/, const Token * /*tok*/) const { } - bool operator==(const ExecutionPath &e) const - { + bool operator==(const ExecutionPath &e) const { return bool(varId == e.varId && is_equal(&e)); } diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index 033ecfaa0..a70c3071b 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -35,8 +35,7 @@ MathLib::bigint MathLib::toLongNumber(const std::string &str) // hexadecimal numbers: if (str.compare(0, 2, "0x") == 0 || str.compare(0, 3, "+0x") == 0 - || str.compare(0, 3, "-0x") == 0) - { + || str.compare(0, 3, "-0x") == 0) { bigint ret = 0; std::istringstream istr(str.substr((str[0]=='0') ? 2U : 3U)); istr >> std::hex >> ret; @@ -46,8 +45,7 @@ MathLib::bigint MathLib::toLongNumber(const std::string &str) // octal numbers: if (str.compare(0, 1, "0") == 0 || str.compare(0, 2, "+0") == 0 - || str.compare(0, 2, "-0") == 0) - { + || str.compare(0, 2, "-0") == 0) { bigint ret = 0; std::istringstream istr(str.substr((str[0]=='0') ? 1U : 2U)); istr >> std::oct >> ret; @@ -65,8 +63,7 @@ MathLib::bigint MathLib::toLongNumber(const std::string &str) double MathLib::toDoubleNumber(const std::string &str) { - if (str.compare(0, 2, "0x") == 0) - { + if (str.compare(0, 2, "0x") == 0) { return std::strtoul(str.c_str(), '\0', 16); } // nullcheck @@ -117,8 +114,7 @@ bool MathLib::isInt(const std::string & s) // prechecking has nothing found,... // gather information - enum Representation - { + enum Representation { eScientific = 0 // NumberE+Number or NumberENumber , eOctal // starts with 0 , eHex // starts with 0x @@ -134,16 +130,11 @@ bool MathLib::isInt(const std::string & s) while (std::isspace(s[n])) ++n; // determine type - if (s.find("E", 0) != std::string::npos) - { + if (s.find("E", 0) != std::string::npos) { Mode = eScientific; - } - else if (s.find("0x", n, 2) != std::string::npos) - { + } else if (s.find("0x", n, 2) != std::string::npos) { Mode = eHex; - } - else if (s.length() > 1 && s[0] == '0' && std::isdigit(s[1])) - { + } else if (s.length() > 1 && s[0] == '0' && std::isdigit(s[1])) { Mode = eOctal; } @@ -151,14 +142,12 @@ bool MathLib::isInt(const std::string & s) if (s[n] == '-' || s[n] == '+') ++n; // check scientific notation - if (Mode == eScientific) - { + if (Mode == eScientific) { // check digits while (std::isdigit(s[n])) ++n; // check scientific notation - if (std::tolower(s[n]) == 'e') - { + if (std::tolower(s[n]) == 'e') { ++n; // check positive exponent if (s[n] == '+') ++n; @@ -169,25 +158,20 @@ bool MathLib::isInt(const std::string & s) } } // check hex notation - else if (Mode == eHex) - { + else if (Mode == eHex) { ++n; // 0 ++n; // x while (std::isxdigit(s[n])) ++n; } // check octal notation - else if (Mode == eOctal) - { + else if (Mode == eOctal) { while (isOctalDigit(s[n])) ++n; - } - else if (Mode == eDefault) - { + } else if (Mode == eDefault) { // starts with digit bool bStartsWithDigit=false; - while (std::isdigit(s[n])) - { + while (std::isdigit(s[n])) { bStartsWithDigit=true; ++n; }; @@ -211,8 +195,7 @@ bool MathLib::isInt(const std::string & s) std::string MathLib::add(const std::string & first, const std::string & second) { - if (MathLib::isInt(first) && MathLib::isInt(second)) - { + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) + toLongNumber(second)); } return toString(toDoubleNumber(first) + toDoubleNumber(second)); @@ -220,8 +203,7 @@ std::string MathLib::add(const std::string & first, const std::string & second) std::string MathLib::subtract(const std::string &first, const std::string &second) { - if (MathLib::isInt(first) && MathLib::isInt(second)) - { + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) - toLongNumber(second)); } return toString(toDoubleNumber(first) - toDoubleNumber(second)); @@ -229,8 +211,7 @@ std::string MathLib::subtract(const std::string &first, const std::string &secon std::string MathLib::divide(const std::string &first, const std::string &second) { - if (MathLib::isInt(first) && MathLib::isInt(second)) - { + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) / toLongNumber(second)); } return toString(toDoubleNumber(first) / toDoubleNumber(second)); @@ -238,8 +219,7 @@ std::string MathLib::divide(const std::string &first, const std::string &second) std::string MathLib::multiply(const std::string &first, const std::string &second) { - if (MathLib::isInt(first) && MathLib::isInt(second)) - { + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) * toLongNumber(second)); } return toString(toDoubleNumber(first) * toDoubleNumber(second)); @@ -249,8 +229,7 @@ std::string MathLib::calculate(const std::string &first, const std::string &seco { std::string result("0"); - switch (action) - { + switch (action) { case '+': result = MathLib::add(first, second); break; diff --git a/lib/mathlib.h b/lib/mathlib.h index 4c01eff2a..516fbe616 100644 --- a/lib/mathlib.h +++ b/lib/mathlib.h @@ -30,8 +30,7 @@ class Tokenizer; -class MathLib -{ +class MathLib { public: typedef long long bigint; @@ -39,8 +38,7 @@ public: static double toDoubleNumber(const std::string & str); template - static std::string toString(const T &d) - { + static std::string toString(const T &d) { std::ostringstream result; result << d; std::string strResult(result.str()); diff --git a/lib/path.cpp b/lib/path.cpp index ffea4e17b..f31bfd665 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -49,57 +49,45 @@ std::string Path::simplifyPath(const char *originalPath) { // Skip ./ at the beginning if (strlen(originalPath) > 2 && originalPath[0] == '.' && - originalPath[1] == '/') - { + originalPath[1] == '/') { originalPath += 2; } std::string subPath = ""; std::vector pathParts; - for (; *originalPath; ++originalPath) - { - if (*originalPath == '/' || *originalPath == '\\') - { - if (subPath.length() > 0) - { + for (; *originalPath; ++originalPath) { + if (*originalPath == '/' || *originalPath == '\\') { + if (subPath.length() > 0) { pathParts.push_back(subPath); subPath = ""; } pathParts.push_back(std::string(1 , *originalPath)); - } - else + } else subPath.append(1, *originalPath); } if (subPath.length() > 0) pathParts.push_back(subPath); - for (unsigned int i = 0; i < pathParts.size(); ++i) - { - if (i > 1 && pathParts[i-2] != ".." && pathParts[i] == ".." && pathParts.size() > i + 1) - { + for (unsigned int i = 0; i < pathParts.size(); ++i) { + if (i > 1 && pathParts[i-2] != ".." && pathParts[i] == ".." && pathParts.size() > i + 1) { pathParts.erase(pathParts.begin() + static_cast(i) + 1); pathParts.erase(pathParts.begin() + static_cast(i)); pathParts.erase(pathParts.begin() + static_cast(i) - 1); pathParts.erase(pathParts.begin() + static_cast(i) - 2); i = 0; - } - else if (i > 0 && pathParts[i] == ".") - { + } else if (i > 0 && pathParts[i] == ".") { pathParts.erase(pathParts.begin() + static_cast(i)); i = 0; - } - else if (pathParts[i] == "/" && i > 0 && pathParts[i-1] == "/") - { + } else if (pathParts[i] == "/" && i > 0 && pathParts[i-1] == "/") { pathParts.erase(pathParts.begin() + static_cast(i) - 1); i = 0; } } std::ostringstream oss; - for (std::vector::size_type i = 0; i < pathParts.size(); ++i) - { + for (std::vector::size_type i = 0; i < pathParts.size(); ++i) { oss << pathParts[i]; } diff --git a/lib/path.h b/lib/path.h index bc1ca293d..274bfe6c9 100644 --- a/lib/path.h +++ b/lib/path.h @@ -31,8 +31,7 @@ * native separator for Unix-derived systems. When giving path to user * or for other functions we convert path separators back to native type. */ -class Path -{ +class Path { public: /** * Convert path to use native separators. diff --git a/lib/preprocessor.cpp b/lib/preprocessor.cpp index c1d38808c..f153c06f9 100644 --- a/lib/preprocessor.cpp +++ b/lib/preprocessor.cpp @@ -64,8 +64,7 @@ static unsigned char readChar(std::istream &istr) unsigned char ch = (unsigned char)istr.get(); // Handling of newlines.. - if (ch == '\r') - { + if (ch == '\r') { ch = '\n'; if ((char)istr.peek() == '\n') (void)istr.get(); @@ -80,10 +79,8 @@ static std::list split(const std::string &s, char separator) std::list parts; std::string::size_type prevPos = 0; - for (std::string::size_type pos = 0; pos < s.length(); ++pos) - { - if (s[pos] == separator) - { + for (std::string::size_type pos = 0; pos < s.length(); ++pos) { + if (s[pos] == separator) { if (pos > prevPos) parts.push_back(s.substr(prevPos, pos - prevPos)); prevPos = pos + 1; @@ -99,8 +96,7 @@ static std::list split(const std::string &s, char separator) static std::string join(const std::list &list, char separator) { std::string s; - for (std::list::const_iterator it = list.begin(); it != list.end(); ++it) - { + for (std::list::const_iterator it = list.begin(); it != list.end(); ++it) { if (!s.empty()) s += separator; @@ -119,8 +115,7 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, // on the next , extra newlines will be added std::ostringstream code; unsigned int newlines = 0; - for (unsigned char ch = readChar(istr); istr.good(); ch = readChar(istr)) - { + for (unsigned char ch = readChar(istr); istr.good(); ch = readChar(istr)) { // Replace assorted special chars with spaces.. if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch))) ch = ' '; @@ -130,18 +125,15 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, // for vs-compatibility the trailing spaces should be kept // See tickets #640 and #1869 // The solution for now is to have a compiler-dependent behaviour. - if (ch == '\\') - { + if (ch == '\\') { unsigned char chNext; #ifdef __GNUC__ // gcc-compatibility: ignore spaces - for (;;) - { + for (;;) { chNext = (unsigned char)istr.peek(); if (chNext != '\n' && chNext != '\r' && - (std::isspace(chNext) || std::iscntrl(chNext))) - { + (std::isspace(chNext) || std::iscntrl(chNext))) { // Skip whitespace between and (void)readChar(istr); continue; @@ -153,21 +145,16 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, // keep spaces chNext = (unsigned char)istr.peek(); #endif - if (chNext == '\n' || chNext == '\r') - { + if (chNext == '\n' || chNext == '\r') { ++newlines; (void)readChar(istr); // Skip the "" - } - else + } else code << "\\"; - } - else - { + } else { code << char(ch); // if there has been sequences, add extra newlines.. - if (ch == '\n' && newlines > 0) - { + if (ch == '\n' && newlines > 0) { code << std::string(newlines, '\n'); newlines = 0; } @@ -204,8 +191,7 @@ std::string Preprocessor::preprocessCleanupDirectives(const std::string &process std::istringstream sstr(processedFile); std::string line; - while (std::getline(sstr, line)) - { + while (std::getline(sstr, line)) { // Trim lines.. if (!line.empty() && line[0] == ' ') line.erase(0, line.find_first_not_of(" ")); @@ -213,10 +199,8 @@ std::string Preprocessor::preprocessCleanupDirectives(const std::string &process line.erase(line.find_last_not_of(" ") + 1); // Preprocessor - if (!line.empty() && line[0] == '#') - { - enum - { + if (!line.empty() && line[0] == '#') { + enum { ESC_NONE, ESC_SINGLE, ESC_DOUBLE @@ -229,22 +213,16 @@ std::string Preprocessor::preprocessCleanupDirectives(const std::string &process // need space.. #if( => #if ( bool needSpace = true; - while (i != line.end()) - { + while (i != line.end()) { // disable esc-mode - if (escapeStatus != ESC_NONE) - { - if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') - { + if (escapeStatus != ESC_NONE) { + if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') { escapeStatus = ESC_NONE; } - if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') - { + if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') { escapeStatus = ESC_NONE; } - } - else - { + } else { // enable esc-mode if (escapeStatus == ESC_NONE && *i == '"') escapeStatus = ESC_DOUBLE; @@ -252,16 +230,13 @@ std::string Preprocessor::preprocessCleanupDirectives(const std::string &process escapeStatus = ESC_SINGLE; } // skip double whitespace between arguments - if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') - { + if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') { ++i; continue; } // Convert #if( to "#if (" - if (escapeStatus == ESC_NONE) - { - if (needSpace) - { + if (escapeStatus == ESC_NONE) { + if (needSpace) { if (*i == '(' || *i == '!') code << " "; else if (!std::isalpha(*i)) @@ -271,23 +246,17 @@ std::string Preprocessor::preprocessCleanupDirectives(const std::string &process needSpace = true; } code << *i; - if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') - { + if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') { prev = ' '; - } - else - { + } else { prev = *i; } ++i; } - if (escapeStatus != ESC_NONE) - { + if (escapeStatus != ESC_NONE) { // unmatched quotes.. compiler should probably complain about this.. } - } - else - { + } else { // Do not mess with regular code.. code << line; } @@ -318,8 +287,7 @@ static bool isFallThroughComment(std::string comment) { // convert comment to lower case without whitespace std::transform(comment.begin(), comment.end(), comment.begin(), tolowerWrapper); - for (std::string::iterator i = comment.begin(); i != comment.end();) - { + for (std::string::iterator i = comment.begin(); i != comment.end();) { if (::isspace(static_cast(*i))) i = comment.erase(i); else @@ -350,11 +318,9 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri std::vector suppressionIDs; bool fallThroughComment = false; - for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) - { + for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) { unsigned char ch = static_cast(str[i]); - if (ch & 0x80) - { + if (ch & 0x80) { std::ostringstream errmsg; errmsg << "The code contains characters that are unhandled. " << "Neither unicode nor extended ASCII are supported. " @@ -363,8 +329,7 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } if ((str.compare(i, 6, "#error") == 0 && (!_settings || _settings->userDefines.empty())) || - str.compare(i, 8, "#warning") == 0) - { + str.compare(i, 8, "#warning") == 0) { if (str.compare(i, 6, "#error") == 0) code << "#error"; @@ -377,26 +342,20 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } // First skip over any whitespace that may be present - if (std::isspace(ch)) - { - if (ch == ' ' && previous == ' ') - { + if (std::isspace(ch)) { + if (ch == ' ' && previous == ' ') { // Skip double white space - } - else - { + } else { code << char(ch); previous = ch; } // if there has been sequences, add extra newlines.. - if (ch == '\n') - { + if (ch == '\n') { if (previous != '\\') inPreprocessorLine = false; ++lineno; - if (newlines > 0) - { + if (newlines > 0) { code << std::string(newlines, '\n'); newlines = 0; previous = '\n'; @@ -407,107 +366,86 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } // Remove comments.. - if (str.compare(i, 2, "//", 0, 2) == 0) - { + if (str.compare(i, 2, "//", 0, 2) == 0) { size_t commentStart = i + 2; i = str.find('\n', i); if (i == std::string::npos) break; std::string comment(str, commentStart, i - commentStart); - if (settings && settings->_inlineSuppressions) - { + if (settings && settings->_inlineSuppressions) { std::istringstream iss(comment); std::string word; iss >> word; - if (word == "cppcheck-suppress") - { + if (word == "cppcheck-suppress") { iss >> word; if (iss) suppressionIDs.push_back(word); } } - if (isFallThroughComment(comment)) - { + if (isFallThroughComment(comment)) { fallThroughComment = true; } code << "\n"; previous = '\n'; ++lineno; - } - else if (str.compare(i, 2, "/*", 0, 2) == 0) - { + } else if (str.compare(i, 2, "/*", 0, 2) == 0) { size_t commentStart = i + 2; unsigned char chPrev = 0; ++i; - while (i < str.length() && (chPrev != '*' || ch != '/')) - { + while (i < str.length() && (chPrev != '*' || ch != '/')) { chPrev = ch; ++i; ch = static_cast(str[i]); - if (ch == '\n') - { + if (ch == '\n') { ++newlines; ++lineno; } } std::string comment(str, commentStart, i - commentStart - 1); - if (isFallThroughComment(comment)) - { + if (isFallThroughComment(comment)) { fallThroughComment = true; } - if (settings && settings->_inlineSuppressions) - { + if (settings && settings->_inlineSuppressions) { std::istringstream iss(comment); std::string word; iss >> word; - if (word == "cppcheck-suppress") - { + if (word == "cppcheck-suppress") { iss >> word; if (iss) suppressionIDs.push_back(word); } } - } - else if (ch == '#' && previous == '\n') - { + } else if (ch == '#' && previous == '\n') { code << ch; previous = ch; inPreprocessorLine = true; // Add any pending inline suppressions that have accumulated. - if (!suppressionIDs.empty()) - { - if (settings != NULL) - { + if (!suppressionIDs.empty()) { + if (settings != NULL) { // Add the suppressions. - for (size_t j(0); j < suppressionIDs.size(); ++j) - { + for (size_t j(0); j < suppressionIDs.size(); ++j) { const std::string errmsg(settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg); } } } suppressionIDs.clear(); } - } - else - { - if (!inPreprocessorLine) - { + } else { + if (!inPreprocessorLine) { // Not whitespace, not a comment, and not preprocessor. // Must be code here! // First check for a "fall through" comment match, but only // add a suppression if the next token is 'case' or 'default' - if (_settings->isEnabled("style") && _settings->experimental && fallThroughComment) - { + if (_settings->isEnabled("style") && _settings->experimental && fallThroughComment) { std::string::size_type j = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz", i); std::string tok = str.substr(i, j - i); if (tok == "case" || tok == "default") @@ -516,16 +454,12 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } // Add any pending inline suppressions that have accumulated. - if (!suppressionIDs.empty()) - { - if (settings != NULL) - { + if (!suppressionIDs.empty()) { + if (settings != NULL) { // Add the suppressions. - for (size_t j(0); j < suppressionIDs.size(); ++j) - { + for (size_t j(0); j < suppressionIDs.size(); ++j) { const std::string errmsg(settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno)); - if (!errmsg.empty()) - { + if (!errmsg.empty()) { writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg); } } @@ -535,83 +469,61 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } // String or char constants.. - if (ch == '\"' || ch == '\'') - { + if (ch == '\"' || ch == '\'') { code << char(ch); char chNext; - do - { + do { ++i; chNext = str[i]; - if (chNext == '\\') - { + if (chNext == '\\') { ++i; char chSeq = str[i]; if (chSeq == '\n') ++newlines; - else - { + else { code << chNext; code << chSeq; previous = static_cast(chSeq); } - } - else - { + } else { code << chNext; previous = static_cast(chNext); } - } - while (i < str.length() && chNext != ch && chNext != '\n'); + } while (i < str.length() && chNext != ch && chNext != '\n'); } // Rawstring.. - else if (str.compare(i,2,"R\"")==0) - { + else if (str.compare(i,2,"R\"")==0) { std::string delim; - for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) - { + for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) { if (i2 > 16 || std::isspace(str[i2]) || std::iscntrl(str[i2]) || str[i2] == ')' || - str[i2] == '\\') - { + str[i2] == '\\') { delim = " "; break; - } - else if (str[i2] == '(') + } else if (str[i2] == '(') break; delim += str[i2]; } const std::string::size_type endpos = str.find(")" + delim + "\"", i); - if (delim != " " && endpos != std::string::npos) - { + if (delim != " " && endpos != std::string::npos) { unsigned int rawstringnewlines = 0; code << '\"'; - for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) - { - if (str[p] == '\n') - { + for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) { + if (str[p] == '\n') { rawstringnewlines++; code << "\\n"; - } - else if (std::iscntrl((unsigned char)str[p]) || - std::isspace((unsigned char)str[p])) - { + } else if (std::iscntrl((unsigned char)str[p]) || + std::isspace((unsigned char)str[p])) { code << " "; - } - else if (str[p] == '\\') - { + } else if (str[p] == '\\') { code << "\\"; - } - else if (str[p] == '\"' || str[p] == '\'') - { + } else if (str[p] == '\"' || str[p] == '\'') { code << "\\" << (char)str[p]; - } - else - { + } else { code << (char)str[p]; } } @@ -619,15 +531,11 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri if (rawstringnewlines > 0) code << std::string(rawstringnewlines, '\n'); i = endpos + delim.size() + 2; - } - else - { + } else { code << "R"; previous = 'R'; } - } - else - { + } else { code << char(ch); previous = ch; } @@ -642,31 +550,25 @@ std::string Preprocessor::removeIf0(const std::string &code) std::ostringstream ret; std::istringstream istr(code); std::string line; - while (std::getline(istr,line)) - { + while (std::getline(istr,line)) { if (line != "#if 0") ret << line << "\n"; - else - { + else { // replace '#if 0' with empty line ret << line << "\n"; // goto the end of the '#if 0' block unsigned int level = 1; bool in = false; - while (level > 0 && std::getline(istr,line)) - { + while (level > 0 && std::getline(istr,line)) { if (line.compare(0,3,"#if") == 0) ++level; else if (line == "#endif") --level; - else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) - { + else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) { if (level == 1) in = true; - } - else - { + } else { if (in) ret << line << "\n"; else @@ -691,10 +593,8 @@ std::string Preprocessor::removeParentheses(const std::string &str) std::istringstream istr(str.c_str()); std::ostringstream ret; std::string line; - while (std::getline(istr, line)) - { - if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) - { + while (std::getline(istr, line)) { + if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) { std::string::size_type pos; pos = 0; while ((pos = line.find(" (", pos)) != std::string::npos) @@ -711,12 +611,10 @@ std::string Preprocessor::removeParentheses(const std::string &str) // Remove inner parenthesis "((..))".. pos = 0; - while ((pos = line.find("((", pos)) != std::string::npos) - { + while ((pos = line.find("((", pos)) != std::string::npos) { ++pos; std::string::size_type pos2 = line.find_first_of("()", pos + 1); - if (pos2 != std::string::npos && line[pos2] == ')') - { + if (pos2 != std::string::npos && line[pos2] == ')') { line.erase(pos2, 1); line.erase(pos, 1); } @@ -724,20 +622,15 @@ std::string Preprocessor::removeParentheses(const std::string &str) // "#if(A) => #if A", but avoid "#if (defined A) || defined (B)" if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) && - line[line.length() - 1] == ')') - { + line[line.length() - 1] == ')') { int ind = 0; - for (std::string::size_type i = 0; i < line.length(); ++i) - { + for (std::string::size_type i = 0; i < line.length(); ++i) { if (line[i] == '(') ++ind; - else if (line[i] == ')') - { + else if (line[i] == ')') { --ind; - if (ind == 0) - { - if (i == line.length() - 1) - { + if (ind == 0) { + if (i == line.length() - 1) { line[line.find('(')] = ' '; line.erase(line.length() - 1); } @@ -766,20 +659,17 @@ static void _removeAsm(std::string &str, const std::string::size_type pos) bool instr = false; int parlevel = 0; std::string::size_type pos2 = pos + 1; - while (pos2 < str.length()) - { + while (pos2 < str.length()) { if (str[pos2] == '\"') instr = !instr; else if (str[pos2] == '\n') ++newlines; - else if (!instr) - { + else if (!instr) { if (str[pos2] == '(') ++parlevel; - else if (str[pos2] == ')') - { + else if (str[pos2] == ')') { if (parlevel <= 1) break; --parlevel; @@ -795,15 +685,13 @@ static void _removeAsm(std::string &str, const std::string::size_type pos) void Preprocessor::removeAsm(std::string &str) { std::string::size_type pos = 0; - while ((pos = str.find("\nasm(", pos)) != std::string::npos) - { + while ((pos = str.find("\nasm(", pos)) != std::string::npos) { _removeAsm(str, pos++); str.insert(pos, "asm()"); } pos = 0; - while ((pos = str.find("\nasm (", pos)) != std::string::npos) - { + while ((pos = str.find("\nasm (", pos)) != std::string::npos) { _removeAsm(str, pos++); str.insert(pos, "asm()"); } @@ -817,8 +705,7 @@ void Preprocessor::removeAsm(std::string &str) _removeAsm(str, pos); pos = 0; - while ((pos = str.find("#asm\n", pos)) != std::string::npos) - { + while ((pos = str.find("#asm\n", pos)) != std::string::npos) { const std::string::size_type pos1 = pos; ++pos; @@ -826,8 +713,7 @@ void Preprocessor::removeAsm(std::string &str) continue; const std::string::size_type endpos = str.find("\n#endasm", pos1); - if (endpos != std::string::npos) - { + if (endpos != std::string::npos) { if (endpos + 8U < str.size() && str[endpos+8U] != '\n') break; @@ -835,8 +721,7 @@ void Preprocessor::removeAsm(std::string &str) str.erase(endpos+1, 7); // Remove non-newline characters between pos1 and endpos - for (std::string::size_type p = endpos; p > pos1; --p) - { + for (std::string::size_type p = endpos; p > pos1; --p) { if (str[p] != '\n') str.erase(p,1); } @@ -862,18 +747,14 @@ std::string Preprocessor::removeSpaceNearNL(const std::string &str) { std::string tmp; char prev = 0; - for (unsigned int i = 0; i < str.size(); i++) - { + for (unsigned int i = 0; i < str.size(); i++) { if (str[i] == ' ' && ((i > 0 && prev == '\n') || (i + 1 < str.size() && str[i+1] == '\n') ) - ) - { + ) { // Ignore space that has new line in either side of it - } - else - { + } else { tmp.append(1, str[i]); prev = str[i]; } @@ -888,13 +769,11 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) std::string::size_type pos; pos = 0; - while ((pos = ret.find("#if defined(", pos)) != std::string::npos) - { + while ((pos = ret.find("#if defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); if (pos2 > ret.length() - 1) break; - if (ret[pos2+1] == '\n') - { + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 3, 9); ret.insert(pos + 3, "def "); @@ -903,13 +782,11 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) } pos = 0; - while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) - { + while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); if (pos2 > ret.length() - 1) break; - if (ret[pos2+1] == '\n') - { + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 3, 10); ret.insert(pos + 3, "ndef "); @@ -918,13 +795,11 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) } pos = 0; - while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) - { + while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); if (pos2 > ret.length() - 1) break; - if (ret[pos2+1] == '\n') - { + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 6, 8); } @@ -962,13 +837,10 @@ void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processe std::istringstream istr(processedFile.c_str()); std::ostringstream ostr; std::string line; - while (std::getline(istr, line)) - { - if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) - { + while (std::getline(istr, line)) { + if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) { std::string::size_type pos = 0; - while ((pos = line.find(" defined ")) != std::string::npos) - { + while ((pos = line.find(" defined ")) != std::string::npos) { line[pos+8] = '('; pos = line.find_first_of(" |&", pos + 8); if (pos == std::string::npos) @@ -1001,22 +873,19 @@ std::string Preprocessor::getdef(std::string line, bool def) // If def is true, the line must start with "#ifdef" if (def && line.compare(0, 7, "#ifdef ") != 0 && line.compare(0, 4, "#if ") != 0 - && (line.compare(0, 6, "#elif ") != 0 || line.compare(0, 7, "#elif !") == 0)) - { + && (line.compare(0, 6, "#elif ") != 0 || line.compare(0, 7, "#elif !") == 0)) { return ""; } // If def is false, the line must start with "#ifndef" - if (!def && line.compare(0, 8, "#ifndef ") != 0 && line.compare(0, 7, "#elif !") != 0) - { + if (!def && line.compare(0, 8, "#ifndef ") != 0 && line.compare(0, 7, "#elif !") != 0) { return ""; } // Remove the "#ifdef" or "#ifndef" if (line.compare(0, 12, "#if defined ") == 0) line.erase(0, 11); - else if (line.compare(0, 15, "#elif !defined(") == 0) - { + else if (line.compare(0, 15, "#elif !defined(") == 0) { std::string::size_type pos = 0; line.erase(0, 15); @@ -1025,14 +894,12 @@ std::string Preprocessor::getdef(std::string line, bool def) // about the mismatch if (pos != std::string::npos) line.erase(pos, 1); - } - else + } else line.erase(0, line.find(" ")); // Remove all spaces. std::string::size_type pos = 0; - while ((pos = line.find(" ", pos)) != std::string::npos) - { + while ((pos = line.find(" ", pos)) != std::string::npos) { const unsigned char chprev(static_cast((pos > 0) ? line[pos-1] : 0)); const unsigned char chnext(static_cast((pos + 1 < line.length()) ? line[pos+1] : 0)); if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_')) @@ -1066,8 +933,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const unsigned int linenr = 0; std::istringstream istr(filedata); std::string line; - while (getline(istr, line)) - { + while (getline(istr, line)) { ++linenr; if (_errorLogger) @@ -1076,26 +942,22 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const if (line.empty()) continue; - if (line.compare(0, 6, "#file ") == 0) - { + if (line.compare(0, 6, "#file ") == 0) { includeguard = true; ++filelevel; continue; } - else if (line == "#endfile") - { + else if (line == "#endfile") { includeguard = false; if (filelevel > 0) --filelevel; continue; } - if (line.compare(0, 8, "#define ") == 0) - { + if (line.compare(0, 8, "#define ") == 0) { bool valid = true; - for (std::string::size_type pos = 8; pos < line.size() && line[pos] != ' '; ++pos) - { + for (std::string::size_type pos = 8; pos < line.size() && line[pos] != ' '; ++pos) { char ch = line[pos]; if (ch=='_' || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (pos>8 && ch>='0' && ch<='9')) continue; @@ -1106,8 +968,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const line.clear(); else if (line.find(" ", 8) == std::string::npos) defines.insert(line.substr(8)); - else - { + else { std::string s = line.substr(8); s[s.find(" ")] = '='; defines.insert(s); @@ -1126,30 +987,25 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const bool from_negation = false; std::string def = getdef(line, true); - if (def.empty()) - { + if (def.empty()) { def = getdef(line, false); // sub conditionals of ndef blocks need to be // constructed _without_ the negated define if (!def.empty()) from_negation = true; } - if (!def.empty()) - { + if (!def.empty()) { int par = 0; - for (std::string::size_type pos = 0; pos < def.length(); ++pos) - { + for (std::string::size_type pos = 0; pos < def.length(); ++pos) { if (def[pos] == '(') ++par; - else if (def[pos] == ')') - { + else if (def[pos] == ')') { --par; if (par < 0) break; } } - if (par != 0) - { + if (par != 0) { std::ostringstream lineStream; lineStream << __LINE__; @@ -1169,8 +1025,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const // Replace defined constants { std::map varmap; - for (std::set::const_iterator it = defines.begin(); it != defines.end(); ++it) - { + for (std::set::const_iterator it = defines.begin(); it != defines.end(); ++it) { std::string::size_type pos = it->find("="); if (pos == std::string::npos) continue; @@ -1187,8 +1042,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const deflist.push_back(def); def = ""; - for (std::list::const_iterator it = deflist.begin(); it != deflist.end(); ++it) - { + for (std::list::const_iterator it = deflist.begin(); it != deflist.end(); ++it) { if (*it == "0") break; if (*it == "1" || *it == "!") @@ -1196,8 +1050,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const // don't add "T;T": // treat two and more similar nested conditions as one - if (def != *it) - { + if (def != *it) { if (! def.empty()) def += ";"; def += *it; @@ -1221,38 +1074,31 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } */ } - if (from_negation) - { + if (from_negation) { ndeflist.push_back(deflist.back()); deflist.pop_back(); std::string nmark("!"); deflist.push_back(nmark); } - if (std::find(ret.begin(), ret.end(), def) == ret.end()) - { + if (std::find(ret.begin(), ret.end(), def) == ret.end()) { ret.push_back(def); } } - else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) - { - if (deflist.back() == "!") - { + else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) { + if (deflist.back() == "!") { deflist.pop_back(); deflist.push_back(ndeflist.back()); ndeflist.pop_back(); - } - else - { + } else { std::string tempDef((deflist.back() == "1") ? "0" : "1"); deflist.pop_back(); deflist.push_back(tempDef); } } - else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) - { + else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) { if (deflist.back() == "!") ndeflist.pop_back(); deflist.pop_back(); @@ -1261,14 +1107,12 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const // Remove defined constants from ifdef configurations.. unsigned int count = 0; - for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) - { + for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) { if (_errorLogger) _errorLogger->reportProgress(filename, "Preprocessing (get configurations 2)", (100 * count++) / ret.size()); std::string cfg(*it); - for (std::set::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) - { + for (std::set::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) { std::string::size_type pos = 0; // Get name of define @@ -1277,8 +1121,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const defineName.erase(defineName.find("=")); // Remove ifdef configurations that match the defineName - while ((pos = cfg.find(defineName, pos)) != std::string::npos) - { + while ((pos = cfg.find(defineName, pos)) != std::string::npos) { std::string::size_type pos1 = pos; ++pos; if (pos1 > 0 && cfg[pos1-1] != ';') @@ -1290,8 +1133,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const cfg.erase(pos, defineName.length()); } } - if (cfg.length() != it->length()) - { + if (cfg.length() != it->length()) { while (cfg.length() > 0 && cfg[0] == ';') cfg.erase(0, 1); @@ -1307,16 +1149,13 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } // convert configurations: "defined(A) && defined(B)" => "A;B" - for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) - { + for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) { std::string s(*it); - if (s.find("&&") != std::string::npos) - { + if (s.find("&&") != std::string::npos) { Tokenizer tokenizer(_settings, _errorLogger); std::istringstream tempIstr(s.c_str()); - if (!tokenizer.tokenize(tempIstr, filename.c_str(), "", true)) - { + if (!tokenizer.tokenize(tempIstr, filename.c_str(), "", true)) { std::ostringstream lineStream; lineStream << __LINE__; @@ -1334,24 +1173,17 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const const Token *tok = tokenizer.tokens(); std::list varList; - while (tok) - { - if (Token::Match(tok, "defined ( %var% )")) - { + while (tok) { + if (Token::Match(tok, "defined ( %var% )")) { varList.push_back(tok->strAt(2)); tok = tok->tokAt(4); - if (tok && tok->str() == "&&") - { + if (tok && tok->str() == "&&") { tok = tok->next(); } - } - else if (Token::Match(tok, "%var% ;")) - { + } else if (Token::Match(tok, "%var% ;")) { varList.push_back(tok->str()); tok = tok->tokAt(2); - } - else - { + } else { break; } } @@ -1365,8 +1197,7 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } // Convert configurations into a canonical form: B;C;A or C;A;B => A;B;C - for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) - { + for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) { // Split the configuration into a list of defines std::list defs = split(*it, ';'); @@ -1381,14 +1212,12 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const ret.unique(); // cleanup unhandled configurations.. - for (std::list::iterator it = ret.begin(); it != ret.end();) - { + for (std::list::iterator it = ret.begin(); it != ret.end();) { const std::string s(*it + ";"); bool unhandled = false; - for (std::string::size_type pos = 0; pos < s.length(); ++pos) - { + for (std::string::size_type pos = 0; pos < s.length(); ++pos) { const unsigned char c = static_cast(s[pos]); // ok with ";" @@ -1396,17 +1225,14 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const continue; // identifier.. - if (std::isalpha(c) || c == '_') - { + if (std::isalpha(c) || c == '_') { while (std::isalnum(s[pos]) || s[pos] == '_') ++pos; - if (s[pos] == '=') - { + if (s[pos] == '=') { ++pos; while (std::isdigit(s[pos])) ++pos; - if (s[pos] != ';') - { + if (s[pos] != ';') { unhandled = true; break; } @@ -1417,27 +1243,22 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } // not ok.. - else - { + else { unhandled = true; break; } } - if (unhandled) - { + if (unhandled) { // unhandled ifdef configuration.. - if (_errorLogger && _settings && _settings->debugwarnings) - { + if (_errorLogger && _settings && _settings->debugwarnings) { std::list locationList; const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug, "unhandled configuration: " + *it, "debug", false); _errorLogger->reportErr(errmsg); } ret.erase(it++); - } - else - { + } else { ++it; } } @@ -1451,28 +1272,23 @@ void Preprocessor::simplifyCondition(const std::map &c Settings settings; Tokenizer tokenizer(&settings, NULL); std::istringstream istr(("(" + condition + ")").c_str()); - if (!tokenizer.tokenize(istr, "", "", true)) - { + if (!tokenizer.tokenize(istr, "", "", true)) { // If tokenize returns false, then there is syntax error in the // code which we can't handle. So stop here. return; } - if (Token::Match(tokenizer.tokens(), "( %var% )")) - { + if (Token::Match(tokenizer.tokens(), "( %var% )")) { std::map::const_iterator var = cfg.find(tokenizer.tokens()->strAt(1)); - if (var != cfg.end()) - { + if (var != cfg.end()) { const std::string &value = (*var).second; condition = (value == "0") ? "0" : "1"; - } - else if (match) + } else if (match) condition = "0"; return; } - if (Token::Match(tokenizer.tokens(), "( ! %var% )")) - { + if (Token::Match(tokenizer.tokens(), "( ! %var% )")) { if (cfg.find(tokenizer.tokens()->strAt(2)) == cfg.end()) condition = "1"; else if (match) @@ -1481,13 +1297,11 @@ void Preprocessor::simplifyCondition(const std::map &c } // replace variable names with values.. - for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) - { + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { if (!tok->isName()) continue; - if (Token::Match(tok, "defined ( %var% )")) - { + if (Token::Match(tok, "defined ( %var% )")) { if (cfg.find(tok->strAt(2)) != cfg.end()) tok->str("1"); else if (match) @@ -1500,8 +1314,7 @@ void Preprocessor::simplifyCondition(const std::map &c continue; } - if (Token::Match(tok, "defined %var%")) - { + if (Token::Match(tok, "defined %var%")) { if (cfg.find(tok->strAt(1)) != cfg.end()) tok->str("1"); else if (match) @@ -1513,10 +1326,8 @@ void Preprocessor::simplifyCondition(const std::map &c } const std::map::const_iterator it = cfg.find(tok->str()); - if (it != cfg.end()) - { - if (!it->second.empty()) - { + if (it != cfg.end()) { + if (!it->second.empty()) { // Tokenize the value Tokenizer tokenizer2(&settings,NULL); std::istringstream istr2(it->second); @@ -1524,27 +1335,23 @@ void Preprocessor::simplifyCondition(const std::map &c // Copy the value tokens std::stack link; - for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) { tok->str(tok2->str()); if (Token::Match(tok2,"[{([]")) link.push(tok); - else if (!link.empty() && Token::Match(tok2,"[})]]")) - { + else if (!link.empty() && Token::Match(tok2,"[})]]")) { Token::createMutualLinks(link.top(), tok); link.pop(); } - if (tok2->next()) - { + if (tok2->next()) { tok->insertToken(""); tok = tok->next(); } } - } - else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) && - (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)"))) + } else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) && + (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)"))) tok->str("1"); else tok->deleteThis(); @@ -1553,15 +1360,12 @@ void Preprocessor::simplifyCondition(const std::map &c // simplify calculations.. bool modified = true; - while (modified) - { + while (modified) { modified = false; modified |= tokenizer.simplifyCalculations(); modified |= tokenizer.simplifyRedundantParenthesis(); - for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) - { - if (Token::Match(tok, "! %num%")) - { + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { + if (Token::Match(tok, "! %num%")) { tok->deleteThis(); tok->str(tok->str() == "0" ? "1" : "0"); modified = true; @@ -1569,21 +1373,16 @@ void Preprocessor::simplifyCondition(const std::map &c } } - for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) - { - if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) - { - if (tok->next()->str() != "0") - { + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { + if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) { + if (tok->next()->str() != "0") { tok->next()->str("1"); } } } - for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) - { - while (Token::Match(tok, "(|%oror% %any% %oror% 1")) - { + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { + while (Token::Match(tok, "(|%oror% %any% %oror% 1")) { tok->deleteNext(); tok->deleteNext(); if (tok->tokAt(-3)) @@ -1643,29 +1442,21 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string std::map cfgmap; { std::string::size_type pos = 0; - for (;;) - { + for (;;) { std::string::size_type pos2 = cfg.find_first_of(";=", pos); - if (pos2 == std::string::npos) - { + if (pos2 == std::string::npos) { cfgmap[cfg.substr(pos)] = ""; break; } - if (cfg[pos2] == ';') - { + if (cfg[pos2] == ';') { cfgmap[cfg.substr(pos, pos2-pos)] = ""; - } - else - { + } else { std::string::size_type pos3 = pos2; pos2 = cfg.find(";", pos2); - if (pos2 == std::string::npos) - { + if (pos2 == std::string::npos) { cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1); break; - } - else - { + } else { cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1, pos2 - pos3 - 1); } } @@ -1678,18 +1469,14 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string std::stack lineNumbers; std::istringstream istr(filedata); std::string line; - while (getline(istr, line)) - { + while (getline(istr, line)) { ++lineno; - if (line.compare(0, 11, "#pragma asm") == 0) - { + if (line.compare(0, 11, "#pragma asm") == 0) { ret << "\n"; bool found_end = false; - while (getline(istr, line)) - { - if (line.compare(0, 14, "#pragma endasm") == 0) - { + while (getline(istr, line)) { + if (line.compare(0, 14, "#pragma endasm") == 0) { found_end = true; break; } @@ -1699,14 +1486,12 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string if (!found_end) break; - if (line.find("=") != std::string::npos) - { + if (line.find("=") != std::string::npos) { Tokenizer tokenizer(settings, NULL); line.erase(0, sizeof("#pragma endasm")); std::istringstream tempIstr(line.c_str()); tokenizer.tokenize(tempIstr, ""); - if (Token::Match(tokenizer.tokens(), "( %var% = %any% )")) - { + if (Token::Match(tokenizer.tokens(), "( %var% = %any% )")) { ret << "asm(" << tokenizer.tokens()->strAt(1) << ");"; } } @@ -1721,99 +1506,78 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string const bool emptymatch = matching_ifdef.empty() | matched_ifdef.empty(); - if (line.compare(0, 8, "#define ") == 0) - { + if (line.compare(0, 8, "#define ") == 0) { match = true; for (std::list::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) match &= bool(*it); - if (match) - { + if (match) { std::string::size_type pos = line.find_first_of(" (", 8); if (pos == std::string::npos) cfgmap[line.substr(8)] = ""; - else if (line[pos] == ' ') - { + else if (line[pos] == ' ') { std::string value(line.substr(pos + 1)); if (cfgmap.find(value) != cfgmap.end()) value = cfgmap[value]; cfgmap[line.substr(8, pos - 8)] = value; - } - else + } else cfgmap[line.substr(8, pos - 8)] = ""; } } - else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) - { - if (matched_ifdef.back()) - { + else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) { + if (matched_ifdef.back()) { matching_ifdef.back() = false; - } - else - { - if (!match_cfg_def(cfgmap, ndef)) - { + } else { + if (!match_cfg_def(cfgmap, ndef)) { matching_ifdef.back() = true; matched_ifdef.back() = true; } } } - else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) - { - if (matched_ifdef.back()) - { + else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) { + if (matched_ifdef.back()) { matching_ifdef.back() = false; - } - else - { - if (match_cfg_def(cfgmap, def)) - { + } else { + if (match_cfg_def(cfgmap, def)) { matching_ifdef.back() = true; matched_ifdef.back() = true; } } } - else if (! def.empty()) - { + else if (! def.empty()) { matching_ifdef.push_back(match_cfg_def(cfgmap, def)); matched_ifdef.push_back(matching_ifdef.back()); } - else if (! ndef.empty()) - { + else if (! ndef.empty()) { matching_ifdef.push_back(! match_cfg_def(cfgmap, ndef)); matched_ifdef.push_back(matching_ifdef.back()); } - else if (!emptymatch && line == "#else") - { + else if (!emptymatch && line == "#else") { if (! matched_ifdef.empty()) matching_ifdef.back() = ! matched_ifdef.back(); } - else if (line.compare(0, 6, "#endif") == 0) - { + else if (line.compare(0, 6, "#endif") == 0) { if (! matched_ifdef.empty()) matched_ifdef.pop_back(); if (! matching_ifdef.empty()) matching_ifdef.pop_back(); } - if (!line.empty() && line[0] == '#') - { + if (!line.empty() && line[0] == '#') { match = true; for (std::list::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) match &= bool(*it); } // #error => return "" - if (match && line.compare(0, 6, "#error") == 0) - { - if (settings && !settings->userDefines.empty()) - { + if (match && line.compare(0, 6, "#error") == 0) { + if (settings && !settings->userDefines.empty()) { Settings settings2(*settings); Preprocessor preprocessor(&settings2, errorLogger); preprocessor.error(filenames.top(), lineno, line); @@ -1822,40 +1586,31 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string } if (!match && (line.compare(0, 8, "#define ") == 0 || - line.compare(0, 6, "#undef") == 0)) - { + line.compare(0, 6, "#undef") == 0)) { // Remove define that is not part of this configuration line = ""; - } - else if (line.compare(0, 7, "#file \"") == 0 || - line.compare(0, 8, "#endfile") == 0 || - line.compare(0, 8, "#define ") == 0 || - line.compare(0, 6, "#undef") == 0) - { + } else if (line.compare(0, 7, "#file \"") == 0 || + line.compare(0, 8, "#endfile") == 0 || + line.compare(0, 8, "#define ") == 0 || + line.compare(0, 6, "#undef") == 0) { // We must not remove #file tags or line numbers // are corrupted. File tags are removed by the tokenizer. // Keep location info updated - if (line.compare(0, 7, "#file \"") == 0) - { + if (line.compare(0, 7, "#file \"") == 0) { filenames.push(line.substr(7, line.size() - 8)); lineNumbers.push(lineno); lineno = 0; - } - else if (line.compare(0, 8, "#endfile") == 0) - { + } else if (line.compare(0, 8, "#endfile") == 0) { if (filenames.size() > 1U) filenames.pop(); - if (!lineNumbers.empty()) - { + if (!lineNumbers.empty()) { lineno = lineNumbers.top(); lineNumbers.pop(); } } - } - else if (!match || line.compare(0, 1, "#") == 0) - { + } else if (!match || line.compare(0, 1, "#") == 0) { // Remove #if, #else, #pragma etc, leaving only // #define, #undef, #file and #endfile. and also lines // which are not part of this configuration. @@ -1871,8 +1626,7 @@ std::string Preprocessor::getcode(const std::string &filedata, const std::string void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg) { std::list locationList; - if (!filename.empty()) - { + if (!filename.empty()) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = linenr; loc.setfile(filename); @@ -1889,8 +1643,7 @@ Preprocessor::HeaderTypes Preprocessor::getHeaderFileName(std::string &str) { std::string result; std::string::size_type i = str.find_first_of("<\""); - if (i == std::string::npos) - { + if (i == std::string::npos) { str = ""; return NoHeader; } @@ -1899,8 +1652,7 @@ Preprocessor::HeaderTypes Preprocessor::getHeaderFileName(std::string &str) if (c == '<') c = '>'; - for (i = i + 1; i < str.length(); ++i) - { + for (i = i + 1; i < str.length(); ++i) { if (str[i] == c) break; @@ -1929,19 +1681,16 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath std::string::size_type endfilePos = 0; std::set handledFiles; endfilePos = pos; - while ((pos = code.find("#include", pos)) != std::string::npos) - { + while ((pos = code.find("#include", pos)) != std::string::npos) { // Accept only includes that are at the start of a line - if (pos > 0 && code[pos-1] != '\n') - { + if (pos > 0 && code[pos-1] != '\n') { pos += 8; // length of "#include" continue; } // If endfile is encountered, we have moved to a next file in our stack, // so remove last path in our list. - while ((endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) - { + while ((endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) { paths.pop_back(); endfilePos += 9; // size of #endfile } @@ -1964,12 +1713,10 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath { std::list includePaths2(includePaths); includePaths2.push_front(""); - for (std::list::const_iterator iter = includePaths2.begin(); iter != includePaths2.end(); ++iter) - { + for (std::list::const_iterator iter = includePaths2.begin(); iter != includePaths2.end(); ++iter) { const std::string nativePath(Path::toNativeSeparators(*iter)); fin.open((nativePath + filename).c_str()); - if (fin.is_open()) - { + if (fin.is_open()) { filename = nativePath + filename; fileOpened = true; break; @@ -1979,23 +1726,19 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath } } - if (headerType == UserHeader && !fileOpened) - { + if (headerType == UserHeader && !fileOpened) { fin.open((paths.back() + filename).c_str()); - if (fin.is_open()) - { + if (fin.is_open()) { filename = paths.back() + filename; fileOpened = true; } } - if (fileOpened) - { + if (fileOpened) { filename = Path::simplifyPath(filename.c_str()); std::string tempFile = filename; std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper); - if (handledFiles.find(tempFile) != handledFiles.end()) - { + if (handledFiles.find(tempFile) != handledFiles.end()) { // We have processed this file already once, skip // it this time to avoid eternal loop. fin.close(); @@ -2007,8 +1750,7 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath fin.close(); } - if (!processedFile.empty()) - { + if (!processedFile.empty()) { // Remove space characters that are after or before new line character processedFile = "#file \"" + filename + "\"\n" + processedFile + "\n#endfile"; code.insert(pos, processedFile); @@ -2016,31 +1758,23 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath path = filename; path.erase(1 + path.find_last_of("\\/")); paths.push_back(path); - } - else if (!fileOpened && _settings && (headerType == UserHeader || _settings->debugwarnings)) - { + } else if (!fileOpened && _settings && (headerType == UserHeader || _settings->debugwarnings)) { if (!_settings->nomsg.isSuppressed("missingInclude", "", 0)) missingIncludeFlag = true; - if (_errorLogger && _settings->checkConfiguration) - { + if (_errorLogger && _settings->checkConfiguration) { std::string f = filePath; // Determine line number of include unsigned int linenr = 1; unsigned int level = 0; - for (std::string::size_type p = 1; p <= pos; ++p) - { + for (std::string::size_type p = 1; p <= pos; ++p) { if (level == 0 && code[pos-p] == '\n') ++linenr; - else if (code.compare(pos-p, 9, "#endfile\n") == 0) - { + else if (code.compare(pos-p, 9, "#endfile\n") == 0) { ++level; - } - else if (code.compare(pos-p, 6, "#file ") == 0) - { - if (level == 0) - { + } else if (code.compare(pos-p, 6, "#file ") == 0) { + if (level == 0) { linenr--; const std::string::size_type pos1 = pos - p + 7; const std::string::size_type pos2 = code.find_first_of("\"\n", pos1); @@ -2051,8 +1785,7 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath } } - if (!_settings->nomsg.isSuppressed("missingInclude", f, linenr)) - { + if (!_settings->nomsg.isSuppressed("missingInclude", f, linenr)) { missingInclude(Path::toNativeSeparators(f), linenr, filename, @@ -2067,8 +1800,7 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filePath void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, bool userheader) { std::list locationList; - if (!filename.empty()) - { + if (!filename.empty()) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = linenr; loc.setfile(filename); @@ -2094,8 +1826,7 @@ static void skipstring(const std::string &line, std::string::size_type &pos) const char ch = line[pos]; ++pos; - while (pos < line.size() && line[pos] != ch) - { + while (pos < line.size() && line[pos] != ch) { if (line[pos] == '\\') ++pos; ++pos; @@ -2133,22 +1864,18 @@ static void getparams(const std::string &line, std::string par; // scan for parameters.. - for (; pos < line.length(); ++pos) - { + for (; pos < line.length(); ++pos) { // increase parenthesis level - if (line[pos] == '(') - { + if (line[pos] == '(') { ++parlevel; if (parlevel == 1) continue; } // decrease parenthesis level - else if (line[pos] == ')') - { + else if (line[pos] == ')') { --parlevel; - if (parlevel <= 0) - { + if (parlevel <= 0) { endFound = true; params.push_back(par); break; @@ -2156,8 +1883,7 @@ static void getparams(const std::string &line, } // string - else if (line[pos] == '\"' || line[pos] == '\'') - { + else if (line[pos] == '\"' || line[pos] == '\'') { const std::string::size_type p = pos; skipstring(line, pos); if (pos == line.length()) @@ -2167,40 +1893,34 @@ static void getparams(const std::string &line, } // count newlines. the expanded macro must have the same number of newlines - else if (line[pos] == '\n') - { + else if (line[pos] == '\n') { ++numberOfNewlines; continue; } // new parameter - if (parlevel == 1 && line[pos] == ',') - { + if (parlevel == 1 && line[pos] == ',') { params.push_back(par); par = ""; } // spaces are only added if needed - else if (line[pos] == ' ') - { + else if (line[pos] == ' ') { // Add space only if it is needed - if (par.size() && std::isalnum(par[par.length()-1])) - { + if (par.size() && std::isalnum(par[par.length()-1])) { par += ' '; } } // add character to current parameter - else if (parlevel >= 1) - { + else if (parlevel >= 1) { par.append(1, line[pos]); } } } /** @brief Class that the preprocessor uses when it expands macros. This class represents a preprocessor macro */ -class PreprocessorMacro -{ +class PreprocessorMacro { private: Settings settings; @@ -2230,8 +1950,7 @@ private: /** @brief expand inner macro */ std::vector expandInnerMacros(const std::vector ¶ms1, - const std::map ¯os) const - { + const std::map ¯os) const { std::string innerMacroName; // Is there an inner macro.. @@ -2242,8 +1961,7 @@ private: innerMacroName = tok->strAt(1); tok = tok->tokAt(3); unsigned int par = 0; - while (Token::Match(tok, "%var% ,|)")) - { + while (Token::Match(tok, "%var% ,|)")) { tok = tok->tokAt(2); par++; } @@ -2253,23 +1971,19 @@ private: std::vector params2(params1); - for (unsigned int ipar = 0; ipar < params1.size(); ++ipar) - { + for (unsigned int ipar = 0; ipar < params1.size(); ++ipar) { const std::string s(innerMacroName + "("); std::string param(params1[ipar]); - if (param.compare(0,s.length(),s)==0 && param[param.length()-1]==')') - { + if (param.compare(0,s.length(),s)==0 && param[param.length()-1]==')') { std::vector innerparams; std::string::size_type pos = s.length() - 1; unsigned int num = 0; bool endFound = false; getparams(param, pos, innerparams, num, endFound); - if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) - { + if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) { // Is inner macro defined? std::map::const_iterator it = macros.find(innerMacroName); - if (it != macros.end()) - { + if (it != macros.end()) { // expand the inner macro const PreprocessorMacro *innerMacro = it->second; @@ -2294,8 +2008,7 @@ public: * e.g. "A(x) foo(x);" */ PreprocessorMacro(const std::string ¯o) - : _macro(macro), _prefix("__cppcheck__") - { + : _macro(macro), _prefix("__cppcheck__") { tokenizer.setSettings(&settings); // Tokenize the macro to make it easier to handle @@ -2310,17 +2023,13 @@ public: _variadic = _nopar = false; std::string::size_type pos = macro.find_first_of(" ("); - if (pos != std::string::npos && macro[pos] == '(') - { + if (pos != std::string::npos && macro[pos] == '(') { // Extract macro parameters - if (Token::Match(tokens(), "%var% ( %var%")) - { - for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) - { + if (Token::Match(tokens(), "%var% ( %var%")) { + for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) { if (tok->str() == ")") break; - if (Token::simpleMatch(tok, ". . . )")) - { + if (Token::simpleMatch(tok, ". . . )")) { if (tok->previous()->str() == ",") _params.push_back("__VA_ARGS__"); _variadic = true; @@ -2340,32 +2049,27 @@ public: } /** return tokens of this macro */ - const Token *tokens() const - { + const Token *tokens() const { return tokenizer.tokens(); } /** read parameters of this macro */ - const std::vector ¶ms() const - { + const std::vector ¶ms() const { return _params; } /** check if this is macro has a variable number of parameters */ - bool variadic() const - { + bool variadic() const { return _variadic; } /** Check if this macro has parentheses but no parameters */ - bool nopar() const - { + bool nopar() const { return _nopar; } /** name of macro */ - const std::string &name() const - { + const std::string &name() const { return _name; } @@ -2376,10 +2080,8 @@ public: * @param macrocode output string * @return true if the expanding was successful */ - bool code(const std::vector ¶ms2, const std::map ¯os, std::string ¯ocode) const - { - if (_nopar || (_params.empty() && _variadic)) - { + bool code(const std::vector ¶ms2, const std::map ¯os, std::string ¯ocode) const { + if (_nopar || (_params.empty() && _variadic)) { macrocode = _macro.substr(1 + _macro.find(")")); if (macrocode.empty()) return true; @@ -2393,19 +2095,16 @@ public: macrocode.erase(pos); // Replace "__VA_ARGS__" with parameters - if (!_nopar) - { + if (!_nopar) { std::string s; - for (unsigned int i = 0; i < params2.size(); ++i) - { + for (unsigned int i = 0; i < params2.size(); ++i) { if (i > 0) s += ","; s += params2[i]; } pos = 0; - while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) - { + while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) { macrocode.erase(pos, 11); macrocode.insert(pos, s); pos += s.length(); @@ -2413,13 +2112,11 @@ public: } } - else if (_params.empty()) - { + else if (_params.empty()) { std::string::size_type pos = _macro.find_first_of(" \""); if (pos == std::string::npos) macrocode = ""; - else - { + else { if (_macro[pos] == ' ') pos++; macrocode = _macro.substr(pos); @@ -2428,65 +2125,50 @@ public: } } - else - { + else { const std::vector givenparams = expandInnerMacros(params2, macros); const Token *tok = tokens(); while (tok && tok->str() != ")") tok = tok->next(); - if (tok) - { + if (tok) { bool optcomma = false; - while ((tok = tok->next()) != NULL) - { + while ((tok = tok->next()) != NULL) { std::string str = tok->str(); if (str == "##") continue; - if (str[0] == '#' || tok->isName()) - { + if (str[0] == '#' || tok->isName()) { const bool stringify(str[0] == '#'); - if (stringify) - { + if (stringify) { str = str.erase(0, 1); } - for (unsigned int i = 0; i < _params.size(); ++i) - { - if (str == _params[i]) - { + for (unsigned int i = 0; i < _params.size(); ++i) { + if (str == _params[i]) { if (_variadic && (i == _params.size() - 1 || - (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) - { + (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) { str = ""; - for (unsigned int j = (unsigned int)_params.size() - 1; j < givenparams.size(); ++j) - { + for (unsigned int j = (unsigned int)_params.size() - 1; j < givenparams.size(); ++j) { if (optcomma || j > _params.size() - 1) str += ","; optcomma = false; str += givenparams[j]; } - } - else if (i >= givenparams.size()) - { + } else if (i >= givenparams.size()) { // Macro had more parameters than caller used. macrocode = ""; return false; - } - else if (stringify) - { + } else if (stringify) { const std::string &s(givenparams[i]); std::ostringstream ostr; ostr << "\""; - for (std::string::size_type j = 0; j < s.size(); ++j) - { + for (std::string::size_type j = 0; j < s.size(); ++j) { if (s[j] == '\\' || s[j] == '\"') ostr << '\\'; ostr << s[j]; } str = ostr.str() + "\""; - } - else + } else str = givenparams[i]; break; @@ -2494,11 +2176,9 @@ public: } // expand nopar macro - if (tok->strAt(-1) != "##") - { + if (tok->strAt(-1) != "##") { const std::map::const_iterator it = macros.find(str); - if (it != macros.end() && it->second->_macro.find("(") == std::string::npos) - { + if (it != macros.end() && it->second->_macro.find("(") == std::string::npos) { str = it->second->_macro; if (str.find(" ") != std::string::npos) str.erase(0, str.find(" ")); @@ -2507,8 +2187,7 @@ public: } } } - if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") - { + if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") { optcomma = true; continue; } @@ -2543,16 +2222,12 @@ static bool getlines(std::istream &istr, std::string &line) return false; line = ""; int parlevel = 0; - for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) - { - if (ch == '\'' || ch == '\"') - { + for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) { + if (ch == '\'' || ch == '\"') { line += ch; char c = 0; - while (istr.good() && c != ch) - { - if (c == '\\') - { + while (istr.good() && c != ch) { + if (c == '\\') { c = (char)istr.get(); if (!istr.good()) return true; @@ -2572,19 +2247,15 @@ static bool getlines(std::istream &istr, std::string &line) ++parlevel; else if (ch == ')') --parlevel; - else if (ch == '\n') - { + else if (ch == '\n') { if (line.compare(0, 1, "#") == 0) return true; - if (istr.peek() == '#') - { + if (istr.peek() == '#') { line += ch; return true; } - } - else if (line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') - { + } else if (line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') { line += ";"; return true; } @@ -2614,16 +2285,13 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // read code.. std::istringstream istr(code.c_str()); std::string line; - while (getlines(istr, line)) - { + while (getlines(istr, line)) { // defining a macro.. - if (line.compare(0, 8, "#define ") == 0) - { + if (line.compare(0, 8, "#define ") == 0) { PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8)); if (macro->name().empty()) delete macro; - else - { + else { std::map::iterator it; it = macros.find(macro->name()); if (it != macros.end()) @@ -2634,12 +2302,10 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // undefining a macro.. - else if (line.compare(0, 7, "#undef ") == 0) - { + else if (line.compare(0, 7, "#undef ") == 0) { std::map::iterator it; it = macros.find(line.substr(7)); - if (it != macros.end()) - { + if (it != macros.end()) { delete it->second; macros.erase(it); } @@ -2647,8 +2313,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // entering a file, update position.. - else if (line.compare(0, 7, "#file \"") == 0) - { + else if (line.compare(0, 7, "#file \"") == 0) { fileinfo.push(std::pair(linenr, filename)); filename = line.substr(7, line.length() - 8); linenr = 0; @@ -2656,10 +2321,8 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // leaving a file, update position.. - else if (line == "#endfile") - { - if (!fileinfo.empty()) - { + else if (line == "#endfile") { + if (!fileinfo.empty()) { linenr = fileinfo.top().first; filename = fileinfo.top().second; fileinfo.pop(); @@ -2668,14 +2331,12 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // all other preprocessor directives are just replaced with a newline - else if (line.compare(0, 1, "#") == 0) - { + else if (line.compare(0, 1, "#") == 0) { line += "\n"; } // expand macros.. - else - { + else { // Limit for each macro. // The limit specify a position in the "line" variable. // For a "recursive macro" where the expanded text contains @@ -2698,21 +2359,18 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // scan line to see if there are any macros to expand.. unsigned int tmpLinenr = 0; - while (pos < line.size()) - { + while (pos < line.size()) { if (line[pos] == '\n') ++tmpLinenr; // skip strings.. - if (line[pos] == '\"' || line[pos] == '\'') - { + if (line[pos] == '\"' || line[pos] == '\'') { const char ch = line[pos]; skipstring(line, pos); ++pos; - if (pos >= line.size()) - { + if (pos >= line.size()) { writeError(filename, linenr + tmpLinenr, errorLogger, @@ -2734,8 +2392,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // found an identifier.. // the "while" is used in case the expanded macro will immediately call another macro - while (pos < line.length() && (std::isalpha(line[pos]) || line[pos] == '_')) - { + while (pos < line.length() && (std::isalpha(line[pos]) || line[pos] == '_')) { // pos1 = start position of macro const std::string::size_type pos1 = pos++; @@ -2772,8 +2429,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file unsigned int numberOfNewlines = 0; // if the macro has parentheses, get parameters - if (macro->variadic() || macro->nopar() || macro->params().size()) - { + if (macro->variadic() || macro->nopar() || macro->params().size()) { // is the end parenthesis found? bool endFound = false; @@ -2795,8 +2451,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // Create macro code.. std::string tempMacro; - if (!macro->code(params, macros, tempMacro)) - { + if (!macro->code(params, macros, tempMacro)) { // Syntax error in code writeError(filename, linenr + tmpLinenr, @@ -2820,15 +2475,11 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // Remove old limits for (std::map::iterator iter = limits.begin(); - iter != limits.end();) - { - if ((line.length() - pos1) < iter->second) - { + iter != limits.end();) { + if ((line.length() - pos1) < iter->second) { // We have gone past this limit, so just delete it limits.erase(iter++); - } - else - { + } else { ++iter; } } @@ -2856,8 +2507,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file ostr << line; // update linenr - for (std::string::size_type p = 0; p < line.length(); ++p) - { + for (std::string::size_type p = 0; p < line.length(); ++p) { if (line[p] == '\n') ++linenr; } diff --git a/lib/preprocessor.h b/lib/preprocessor.h index d02dd5130..4d46f8396 100644 --- a/lib/preprocessor.h +++ b/lib/preprocessor.h @@ -37,15 +37,13 @@ class Settings; * The preprocessor has special functionality for extracting the various ifdef * configurations that exist in a source file. */ -class Preprocessor -{ +class Preprocessor { public: /** * Include file types. */ - enum HeaderTypes - { + enum HeaderTypes { NoHeader = 0, UserHeader, SystemHeader diff --git a/lib/settings.cpp b/lib/settings.cpp index b6760ce94..9c9333c41 100644 --- a/lib/settings.cpp +++ b/lib/settings.cpp @@ -65,12 +65,10 @@ Settings::Settings() std::string Settings::addEnabled(const std::string &str) { // Enable parameters may be comma separated... - if (str.find(",") != std::string::npos) - { + if (str.find(",") != std::string::npos) { std::string::size_type prevPos = 0; std::string::size_type pos = 0; - while ((pos = str.find(",", pos)) != std::string::npos) - { + while ((pos = str.find(",", pos)) != std::string::npos) { if (pos == prevPos) return std::string("cppcheck: --enable parameter is empty"); const std::string errmsg(addEnabled(str.substr(prevPos, pos - prevPos))); @@ -94,18 +92,13 @@ std::string Settings::addEnabled(const std::string &str) id.insert("missingInclude"); id.insert("unusedFunction"); - if (str == "all") - { + if (str == "all") { std::set::const_iterator it; for (it = id.begin(); it != id.end(); ++it) _enabled.insert(*it); - } - else if (id.find(str) != id.end()) - { + } else if (id.find(str) != id.end()) { _enabled.insert(str); - } - else if (!handled) - { + } else if (!handled) { if (str.empty()) return std::string("cppcheck: --enable parameter is empty"); else @@ -126,8 +119,7 @@ void Settings::append(const std::string &filename) _append = "\n"; std::ifstream fin(filename.c_str()); std::string line; - while (std::getline(fin, line)) - { + while (std::getline(fin, line)) { _append += line + "\n"; } } @@ -139,8 +131,7 @@ std::string Settings::append() const bool Settings::platform(PlatformType type) { - switch (type) - { + switch (type) { case Unspecified: // same as system this code was compile on platformType = type; sizeof_bool = sizeof(bool); diff --git a/lib/settings.h b/lib/settings.h index 0af04fe6a..e47b862de 100644 --- a/lib/settings.h +++ b/lib/settings.h @@ -34,8 +34,7 @@ * to pass individual values to functions or constructors now or in the * future when we might have even more detailed settings. */ -class Settings -{ +class Settings { private: /** @brief Code to append in the checks */ std::string _append; @@ -79,14 +78,12 @@ public: bool _verbose; /** @brief Request termination of checking */ - void terminate() - { + void terminate() { _terminate = true; } /** @brief termination requested? */ - bool terminated() const - { + bool terminated() const { return _terminate; } @@ -162,11 +159,9 @@ public: bool ifcfg; /** Rule */ - class Rule - { + class Rule { public: - Rule() - { + Rule() { // default id id = "rule"; @@ -206,8 +201,7 @@ public: unsigned int sizeof_size_t; unsigned int sizeof_pointer; - enum PlatformType - { + enum PlatformType { Unspecified, // whatever system this code was compiled on Win32A, Win32W, diff --git a/lib/suppressions.cpp b/lib/suppressions.cpp index 1b0e13480..137bb0ff8 100644 --- a/lib/suppressions.cpp +++ b/lib/suppressions.cpp @@ -37,8 +37,7 @@ std::string Suppressions::parseFile(std::istream &istr) // Parse filedata.. std::istringstream istr2(filedata); - while (std::getline(istr2, line)) - { + while (std::getline(istr2, line)) { // Skip empty lines if (line.empty()) continue; @@ -61,10 +60,8 @@ std::string Suppressions::addSuppressionLine(const std::string &line) std::string id; std::string file; unsigned int lineNumber = 0; - if (std::getline(lineStream, id, ':')) - { - if (std::getline(lineStream, file)) - { + if (std::getline(lineStream, id, ':')) { + if (std::getline(lineStream, file)) { // If there is not a dot after the last colon in "file" then // the colon is a separator and the contents after the colon // is a line number.. @@ -74,21 +71,16 @@ std::string Suppressions::addSuppressionLine(const std::string &line) // if a colon is found and there is no dot after it.. if (pos != std::string::npos && - file.find(".", pos) == std::string::npos) - { + file.find(".", pos) == std::string::npos) { // Try to parse out the line number - try - { + try { std::istringstream istr1(file.substr(pos+1)); istr1 >> lineNumber; - } - catch (...) - { + } catch (...) { lineNumber = 0; } - if (lineNumber > 0) - { + if (lineNumber > 0) { file.erase(pos); } } @@ -109,44 +101,33 @@ bool Suppressions::FileMatcher::match(const std::string &pattern, const std::str const char *n = name.c_str(); std::stack > backtrack; - for (;;) - { + for (;;) { bool matching = true; - while (*p != '\0' && matching) - { - switch (*p) - { + while (*p != '\0' && matching) { + switch (*p) { case '*': // Step forward until we match the next character after * - while (*n != '\0' && *n != p[1]) - { + while (*n != '\0' && *n != p[1]) { n++; } - if (*n != '\0') - { + if (*n != '\0') { // If this isn't the last possibility, save it for later backtrack.push(std::make_pair(p, n)); } break; case '?': // Any character matches unless we're at the end of the name - if (*n != '\0') - { + if (*n != '\0') { n++; - } - else - { + } else { matching = false; } break; default: // Non-wildcard characters match literally - if (*n == *p) - { + if (*n == *p) { n++; - } - else - { + } else { matching = false; } break; @@ -155,14 +136,12 @@ bool Suppressions::FileMatcher::match(const std::string &pattern, const std::str } // If we haven't failed matching and we've reached the end of the name, then success - if (matching && *n == '\0') - { + if (matching && *n == '\0') { return true; } // If there are no other paths to tray, then fail - if (backtrack.empty()) - { + if (backtrack.empty()) { return false; } @@ -178,27 +157,19 @@ bool Suppressions::FileMatcher::match(const std::string &pattern, const std::str std::string Suppressions::FileMatcher::addFile(const std::string &name, unsigned int line) { - if (name.find_first_of("*?") != std::string::npos) - { - for (std::string::const_iterator i = name.begin(); i != name.end(); ++i) - { - if (*i == '*') - { + if (name.find_first_of("*?") != std::string::npos) { + for (std::string::const_iterator i = name.begin(); i != name.end(); ++i) { + if (*i == '*') { std::string::const_iterator j = i + 1; - if (j != name.end() && (*j == '*' || *j == '?')) - { + if (j != name.end() && (*j == '*' || *j == '?')) { return "Failed to add suppression. Syntax error in glob."; } } } _globs[name][line] = false; - } - else if (name.empty()) - { + } else if (name.empty()) { _globs["*"][0U] = false; - } - else - { + } else { _files[Path::simplifyPath(name.c_str())][line] = false; } return ""; @@ -209,18 +180,14 @@ bool Suppressions::FileMatcher::isSuppressed(const std::string &file, unsigned i if (isSuppressedLocal(file, line)) return true; - for (std::map >::iterator g = _globs.begin(); g != _globs.end(); ++g) - { - if (match(g->first, file)) - { - if (g->second.find(0U) != g->second.end()) - { + for (std::map >::iterator g = _globs.begin(); g != _globs.end(); ++g) { + if (match(g->first, file)) { + if (g->second.find(0U) != g->second.end()) { g->second[0U] = true; return true; } std::map::iterator l = g->second.find(line); - if (l != g->second.end()) - { + if (l != g->second.end()) { l->second = true; return true; } @@ -233,16 +200,13 @@ bool Suppressions::FileMatcher::isSuppressed(const std::string &file, unsigned i bool Suppressions::FileMatcher::isSuppressedLocal(const std::string &file, unsigned int line) { std::map >::iterator f = _files.find(file); - if (f != _files.end()) - { - if (f->second.find(0U) != f->second.end()) - { + if (f != _files.end()) { + if (f->second.find(0U) != f->second.end()) { f->second[0U] = true; return true; } std::map::iterator l = f->second.find(line); - if (l != f->second.end()) - { + if (l != f->second.end()) { l->second = true; return true; } @@ -254,20 +218,15 @@ bool Suppressions::FileMatcher::isSuppressedLocal(const std::string &file, unsig std::string Suppressions::addSuppression(const std::string &errorId, const std::string &file, unsigned int line) { // Check that errorId is valid.. - if (errorId.empty()) - { + if (errorId.empty()) { return "Failed to add suppression. No id."; } - if (errorId != "*") - { - for (std::string::size_type pos = 0; pos < errorId.length(); ++pos) - { - if (errorId[pos] < 0 || !std::isalnum(errorId[pos])) - { + if (errorId != "*") { + for (std::string::size_type pos = 0; pos < errorId.length(); ++pos) { + if (errorId[pos] < 0 || !std::isalnum(errorId[pos])) { return "Failed to add suppression. Invalid id \"" + errorId + "\""; } - if (pos == 0 && std::isdigit(errorId[pos])) - { + if (pos == 0 && std::isdigit(errorId[pos])) { return "Failed to add suppression. Invalid id \"" + errorId + "\""; } } @@ -303,15 +262,11 @@ bool Suppressions::isSuppressedLocal(const std::string &errorId, const std::stri std::list Suppressions::getUnmatchedLocalSuppressions(const std::string &file) const { std::list r; - for (std::map::const_iterator i = _suppressions.begin(); i != _suppressions.end(); ++i) - { + for (std::map::const_iterator i = _suppressions.begin(); i != _suppressions.end(); ++i) { std::map >::const_iterator f = i->second._files.find(file); - if (f != i->second._files.end()) - { - for (std::map::const_iterator l = f->second.begin(); l != f->second.end(); ++l) - { - if (!l->second) - { + if (f != i->second._files.end()) { + for (std::map::const_iterator l = f->second.begin(); l != f->second.end(); ++l) { + if (!l->second) { r.push_back(SuppressionEntry(i->first, f->first, l->first)); } } @@ -323,14 +278,10 @@ std::list Suppressions::getUnmatchedLocalSuppres std::list Suppressions::getUnmatchedGlobalSuppressions() const { std::list r; - for (std::map::const_iterator i = _suppressions.begin(); i != _suppressions.end(); ++i) - { - for (std::map >::const_iterator g = i->second._globs.begin(); g != i->second._globs.end(); ++g) - { - for (std::map::const_iterator l = g->second.begin(); l != g->second.end(); ++l) - { - if (!l->second) - { + for (std::map::const_iterator i = _suppressions.begin(); i != _suppressions.end(); ++i) { + for (std::map >::const_iterator g = i->second._globs.begin(); g != i->second._globs.end(); ++g) { + for (std::map::const_iterator l = g->second.begin(); l != g->second.end(); ++l) { + if (!l->second) { r.push_back(SuppressionEntry(i->first, g->first, l->first)); } } diff --git a/lib/suppressions.h b/lib/suppressions.h index 09fb66be5..1bdf1f5ba 100644 --- a/lib/suppressions.h +++ b/lib/suppressions.h @@ -28,11 +28,9 @@ /// @{ /** @brief class for handling suppressions */ -class Suppressions -{ +class Suppressions { private: - class FileMatcher - { + class FileMatcher { friend class Suppressions; private: /** @brief List of filenames suppressed, bool flag indicates whether suppression matched. */ @@ -119,8 +117,7 @@ public: */ bool isSuppressedLocal(const std::string &errorId, const std::string &file, unsigned int line); - struct SuppressionEntry - { + struct SuppressionEntry { SuppressionEntry(const std::string &aid, const std::string &afile, const unsigned int &aline) : id(aid), file(afile), line(aline) { } diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index 118cba76e..ca482c15a 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -46,25 +46,21 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti Scope *scope = &scopeList.back(); // find all scopes - for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) - { + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Locate next class - if (Token::Match(tok, "class|struct|union|namespace %var% [{:]")) - { + if (Token::Match(tok, "class|struct|union|namespace %var% [{:]")) { scopeList.push_back(Scope(this, tok, scope)); Scope *new_scope = &scopeList.back(); const Token *tok2 = tok->tokAt(2); // only create base list for classes and structures - if (new_scope->isClassOrStruct()) - { + if (new_scope->isClassOrStruct()) { // goto initial '{' tok2 = initBaseInfo(new_scope, tok); // make sure we have valid code - if (!tok2) - { + if (!tok2) { scopeList.pop_back(); break; } @@ -74,8 +70,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti new_scope->classEnd = tok2->link(); // make sure we have valid code - if (!new_scope->classEnd) - { + if (!new_scope->classEnd) { scopeList.pop_back(); break; } @@ -92,8 +87,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // forward declaration - else if (Token::Match(tok, "class|struct %var% ;")) - { + else if (Token::Match(tok, "class|struct %var% ;")) { // fill the classAndStructTypes set.. classAndStructTypes.insert(tok->next()->str()); @@ -103,8 +97,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // using namespace - else if (Token::Match(tok, "using namespace %type% ;|::")) - { + else if (Token::Match(tok, "using namespace %type% ;|::")) { // save location scope->usingList.push_back(tok); @@ -113,8 +106,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // unnamed struct and union else if (Token::Match(tok, "struct|union {") && - Token::Match(tok->next()->link(), "} %var% ;|[")) - { + Token::Match(tok->next()->link(), "} %var% ;|[")) { scopeList.push_back(Scope(this, tok, scope)); Scope *new_scope = &scopeList.back(); @@ -134,8 +126,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti new_scope->classEnd = tok2->link(); // make sure we have valid code - if (!new_scope->classEnd) - { + if (!new_scope->classEnd) { scopeList.pop_back(); break; } @@ -149,8 +140,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // anonymous struct and union else if (Token::Match(tok, "struct|union {") && - Token::simpleMatch(tok->next()->link(), "} ;")) - { + Token::simpleMatch(tok->next()->link(), "} ;")) { scopeList.push_back(Scope(this, tok, scope)); Scope *new_scope = &scopeList.back(); @@ -161,8 +151,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti new_scope->classEnd = tok2->link(); // make sure we have valid code - if (!new_scope->classEnd) - { + if (!new_scope->classEnd) { scopeList.pop_back(); break; } @@ -174,18 +163,15 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti tok = tok2; } - else - { + else { // check for end of scope - if (tok == scope->classEnd) - { + if (tok == scope->classEnd) { scope = scope->nestedIn; continue; } // check if in class or structure - else if (scope->type == Scope::eClass || scope->type == Scope::eStruct) - { + else if (scope->type == Scope::eClass || scope->type == Scope::eStruct) { const Token *funcStart = 0; const Token *argStart = 0; @@ -196,8 +182,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti scope->access = Protected; else if (tok->str() == "public:") scope->access = Public; - else if (Token::Match(tok, "public|protected|private %var% :")) - { + else if (Token::Match(tok, "public|protected|private %var% :")) { if (tok->str() == "private") scope->access = Private; else if (tok->str() == "protected") @@ -209,8 +194,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // class function? - else if (tok->previous()->str() != "::" && isFunction(tok, &funcStart, &argStart)) - { + else if (tok->previous()->str() != "::" && isFunction(tok, &funcStart, &argStart)) { Function function; // save the function definition argument start '(' @@ -223,8 +207,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti function.tokenDef = funcStart; // operator function - if (function.tokenDef->str().find("operator") == 0) - { + if (function.tokenDef->str().find("operator") == 0) { function.isOperator = true; // 'operator =' is special @@ -233,8 +216,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // class constructor/destructor - else if (function.tokenDef->str() == scope->className) - { + else if (function.tokenDef->str() == scope->className) { // destructor if (function.tokenDef->previous()->str() == "~") function.type = Function::eDestructor; @@ -260,33 +242,28 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // function returning function pointer - else if (tok->str() == "(") - { + else if (tok->str() == "(") { function.retFuncPtr = true; } const Token *tok1 = tok; // look for end of previous statement - while (tok1->previous() && !Token::Match(tok1->previous(), ";|}|{|public:|protected:|private:")) - { + while (tok1->previous() && !Token::Match(tok1->previous(), ";|}|{|public:|protected:|private:")) { // virtual function - if (tok1->previous()->str() == "virtual") - { + if (tok1->previous()->str() == "virtual") { function.isVirtual = true; break; } // static function - else if (tok1->previous()->str() == "static") - { + else if (tok1->previous()->str() == "static") { function.isStatic = true; break; } // friend function - else if (tok1->previous()->str() == "friend") - { + else if (tok1->previous()->str() == "friend") { function.isFriend = true; break; } @@ -320,8 +297,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // out of line function if (Token::Match(end, ") const| ;") || - Token::Match(end, ") const| = %any%")) - { + Token::Match(end, ") const| = %any%")) { // find the function implementation later tok = end->next(); @@ -329,8 +305,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // inline function - else - { + else { function.isInline = true; function.hasBody = true; @@ -347,8 +322,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti Scope *functionOf = scope; addNewFunction(&scope, &tok2); - if (scope) - { + if (scope) { scope->functionOf = functionOf; scope->function = &functionOf->functionList.back(); scope->function->functionScope = scope; @@ -359,22 +333,19 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // nested class or friend function? - else if (tok->previous()->str() == "::" && isFunction(tok, &funcStart, &argStart)) - { + else if (tok->previous()->str() == "::" && isFunction(tok, &funcStart, &argStart)) { /** @todo check entire qualification for match */ Scope * nested = scope->findInNestedListRecursive(tok->strAt(-2)); if (nested) addFunction(&scope, &tok, argStart); - else - { + else { /** @todo handle friend functions */ } } // friend class declaration? - else if (Token::Match(tok, "friend class| %any% ;")) - { + else if (Token::Match(tok, "friend class| %any% ;")) { Scope::FriendInfo friendInfo; friendInfo.name = tok->strAt(1) == "class" ? tok->strAt(2) : tok->strAt(1); @@ -383,18 +354,14 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti scope->friendList.push_back(friendInfo); } - } - else if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal) - { + } else if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal) { const Token *funcStart = 0; const Token *argStart = 0; // function? - if (isFunction(tok, &funcStart, &argStart)) - { + if (isFunction(tok, &funcStart, &argStart)) { // has body? - if (Token::Match(argStart->link(), ") const| {|:")) - { + if (Token::Match(argStart->link(), ") const| {|:")) { Scope *old_scope = scope; // class function @@ -407,8 +374,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti addFunction(&scope, &tok, argStart); // regular function - else - { + else { Function function; // save the function definition argument start '(' @@ -441,8 +407,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // syntax error - if (!scope) - { + if (!scope) { scope = old_scope; break; } @@ -450,8 +415,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // function returning function pointer with body else if (Token::simpleMatch(argStart->link(), ") ) (") && - Token::Match(argStart->link()->tokAt(2)->link(), ") const| {")) - { + Token::Match(argStart->link()->tokAt(2)->link(), ") const| {")) { const Token *tok1 = funcStart; Scope *old_scope = scope; @@ -460,8 +424,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti addFunction(&scope, &tok1, argStart); // regular function - else - { + else { Function function; // save the function definition argument start '(' @@ -495,8 +458,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // syntax error? - if (!scope) - { + if (!scope) { scope = old_scope; break; } @@ -505,8 +467,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // function prototype - else if (Token::simpleMatch(argStart->link(), ") ;")) - { + else if (Token::simpleMatch(argStart->link(), ") ;")) { /** @todo save function prototypes in database someday */ tok = argStart->link()->next(); continue; @@ -514,45 +475,35 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // function returning function pointer prototype else if (Token::simpleMatch(argStart->link(), ") ) (") && - Token::simpleMatch(argStart->link()->tokAt(2)->link(), ") ;")) - { + Token::simpleMatch(argStart->link()->tokAt(2)->link(), ") ;")) { /** @todo save function prototypes in database someday */ tok = argStart->link()->tokAt(2)->link()->next(); continue; } } - } - else if (scope->type == Scope::eFunction || scope->isLocal()) - { + } else if (scope->type == Scope::eFunction || scope->isLocal()) { if (Token::simpleMatch(tok, "if (") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + Token::simpleMatch(tok->next()->link(), ") {")) { const Token *tok1 = tok->next()->link()->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eIf, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (Token::simpleMatch(tok, "else {")) - { + } else if (Token::simpleMatch(tok, "else {")) { const Token *tok1 = tok->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eElse, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (Token::simpleMatch(tok, "else if (") && - Token::simpleMatch(tok->next()->next()->link(), ") {")) - { + } else if (Token::simpleMatch(tok, "else if (") && + Token::simpleMatch(tok->next()->next()->link(), ") {")) { const Token *tok1 = tok->next()->next()->link()->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eElseIf, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (Token::simpleMatch(tok, "for (") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + } else if (Token::simpleMatch(tok, "for (") && + Token::simpleMatch(tok->next()->link(), ") {")) { // save location of initialization const Token *tok1 = tok->next()->link()->next(); const Token *tok2 = tok->tokAt(2); @@ -562,43 +513,32 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti scope->nestedIn->nestedList.push_back(scope); // check for variable declaration and add it to new scope if found scope->checkVariable(tok2, Local); - } - else if (Token::simpleMatch(tok, "while (") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + } else if (Token::simpleMatch(tok, "while (") && + Token::simpleMatch(tok->next()->link(), ") {")) { const Token *tok1 = tok->next()->link()->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eWhile, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (Token::simpleMatch(tok, "do {")) - { + } else if (Token::simpleMatch(tok, "do {")) { const Token *tok1 = tok->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eDo, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (Token::simpleMatch(tok, "switch (") && - Token::simpleMatch(tok->next()->link(), ") {")) - { + } else if (Token::simpleMatch(tok, "switch (") && + Token::simpleMatch(tok->next()->link(), ") {")) { const Token *tok1 = tok->next()->link()->next(); scopeList.push_back(Scope(this, tok, scope, Scope::eSwitch, tok1)); tok = tok1; scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else if (tok->str() == "{") - { - if (!Token::Match(tok->previous(), "=|,")) - { + } else if (tok->str() == "{") { + if (!Token::Match(tok->previous(), "=|,")) { scopeList.push_back(Scope(this, tok, scope, Scope::eUnconditional, tok)); scope = &scopeList.back(); scope->nestedIn->nestedList.push_back(scope); - } - else - { + } else { tok = tok->link(); } } @@ -609,8 +549,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti std::list::iterator it; // fill in base class info - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); // skip namespaces and functions @@ -618,19 +557,16 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti continue; // finish filling in base class info - for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) - { + for (unsigned int i = 0; i < scope->derivedFrom.size(); ++i) { std::list::const_iterator it1; // check all scopes for match - for (it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) - { + for (it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) { // check scope for match const Scope *scope1 = it1->findQualifiedScope(scope->derivedFrom[i].name); // found match? - if (scope1) - { + if (scope1) { // set found scope scope->derivedFrom[i].scope = const_cast(scope1); break; @@ -640,8 +576,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // fill in variable info - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); // find variables @@ -649,14 +584,12 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // fill in function arguments - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); std::list::iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { // add arguments func->addArguments(this, &*func, scope); } @@ -666,35 +599,28 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti unsigned int unknowns = 0; // stop checking when there are no unknowns unsigned int retry = 0; // bail if we don't resolve all the variable types for some reason - do - { + do { unknowns = 0; - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); - if (scope->isClassOrStruct() && scope->needInitialization == Scope::Unknown) - { + if (scope->isClassOrStruct() && scope->needInitialization == Scope::Unknown) { // check for default constructor bool hasDefaultConstructor = false; std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { - if (func->type == Function::eConstructor) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { + if (func->type == Function::eConstructor) { // check for no arguments: func ( ) - if (func->argCount() == 0) - { + if (func->argCount() == 0) { hasDefaultConstructor = true; break; } /** check for arguments with default values */ - else if (func->argCount() == func->initializedArgCount()) - { + else if (func->argCount() == func->initializedArgCount()) { hasDefaultConstructor = true; break; } @@ -708,31 +634,25 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti scope->needInitialization = Scope::False; // check each member variable to see if it needs initialization - else - { + else { bool needInitialization = false; bool unknown = false; std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { - if (var->isClass()) - { - if (var->type()) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { + if (var->isClass()) { + if (var->type()) { // does this type need initialization? if (var->type()->needInitialization == Scope::True) needInitialization = true; else if (var->type()->needInitialization == Scope::Unknown) unknown = true; } - } - else + } else needInitialization = true; } - if (!unknown) - { + if (!unknown) { if (needInitialization) scope->needInitialization = Scope::True; else @@ -742,20 +662,16 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti if (scope->needInitialization == Scope::Unknown) unknowns++; } - } - else if (scope->type == Scope::eUnion && scope->needInitialization == Scope::Unknown) + } else if (scope->type == Scope::eUnion && scope->needInitialization == Scope::Unknown) scope->needInitialization = Scope::True; } retry++; - } - while (unknowns && retry < 100); + } while (unknowns && retry < 100); // this shouldn't happen so output a debug warning - if (retry == 100 && _settings->debugwarnings) - { - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + if (retry == 100 && _settings->debugwarnings) { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); if (scope->isClassOrStruct() && scope->needInitialization == Scope::Unknown) @@ -768,14 +684,12 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti fill_n(_variableList.begin(), _variableList.size(), (const Variable*)NULL); // check all scopes for variables - for (it = scopeList.begin(); it != scopeList.end(); ++it) - { + for (it = scopeList.begin(); it != scopeList.end(); ++it) { scope = &(*it); // add all variables std::list::const_iterator var; - for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) - { + for (var = scope->varlist.begin(); var != scope->varlist.end(); ++var) { unsigned int varId = var->varId(); if (varId) _variableList[varId] = &(*var); @@ -783,18 +697,15 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // add all function paramaters std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { // ignore function without implementations if (!func->hasBody) continue; std::list::const_iterator arg; - for (arg = func->argumentList.begin(); arg != func->argumentList.end(); ++arg) - { + for (arg = func->argumentList.begin(); arg != func->argumentList.end(); ++arg) { // check for named parameters - if (arg->nameToken() && arg->varId()) - { + if (arg->nameToken() && arg->varId()) { unsigned int varId = arg->varId(); if (varId) _variableList[varId] = &(*arg); @@ -804,19 +715,15 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } /* set all unknown array dimensions that are set by a variable to the maximum size of that variable type */ - for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) - { + for (size_t i = 1; i <= _tokenizer->varIdCount(); i++) { // check each array variable - if (_variableList[i] && _variableList[i]->isArray()) - { + if (_variableList[i] && _variableList[i]->isArray()) { // check each array dimension - for (size_t j = 0; j < _variableList[i]->dimensions().size(); j++) - { + for (size_t j = 0; j < _variableList[i]->dimensions().size(); j++) { // check for a single token dimension that is a variable if (_variableList[i]->dimensions()[j].start && (_variableList[i]->dimensions()[j].start == _variableList[i]->dimensions()[j].end) && - _variableList[i]->dimensions()[j].start->varId()) - { + _variableList[i]->dimensions()[j].start->varId()) { Dimension &dimension = const_cast(_variableList[i]->dimensions()[j]); // get maximum size from type @@ -830,17 +737,14 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti // get type token const Token *index_type = var->typeEndToken(); - if (index_type->str() == "char") - { + if (index_type->str() == "char") { if (index_type->isUnsigned()) dimension.num = UCHAR_MAX + 1; else if (index_type->isSigned()) dimension.num = SCHAR_MAX + 1; else dimension.num = CHAR_MAX + 1; - } - else if (index_type->str() == "short") - { + } else if (index_type->str() == "short") { if (index_type->isUnsigned()) dimension.num = USHRT_MAX + 1; else @@ -848,24 +752,18 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti } // checkScope assumes size is signed int so we limit the following sizes to INT_MAX - else if (index_type->str() == "int") - { + else if (index_type->str() == "int") { if (index_type->isUnsigned()) dimension.num = UINT_MAX + 1ULL; else dimension.num = INT_MAX + 1ULL; - } - else if (index_type->str() == "long") - { - if (index_type->isUnsigned()) - { + } else if (index_type->str() == "long") { + if (index_type->isUnsigned()) { if (index_type->isLong()) dimension.num = ULLONG_MAX; // should be ULLONG_MAX + 1ULL else dimension.num = ULONG_MAX; // should be ULONG_MAX + 1ULL - } - else - { + } else { if (index_type->isLong()) dimension.num = LLONG_MAX; // should be LLONG_MAX + 1LL else @@ -886,8 +784,7 @@ bool SymbolDatabase::isFunction(const Token *tok, const Token **funcStart, const tok->link()->next() && tok->link()->next()->str() == "(" && tok->link()->next()->link()->next() && - Token::Match(tok->link()->next()->link()->next(), "{|;|const|=")) - { + Token::Match(tok->link()->next()->link()->next(), "{|;|const|=")) { *funcStart = tok->link()->previous()->link()->previous(); *argStart = tok->link()->previous()->link(); return true; @@ -896,8 +793,7 @@ bool SymbolDatabase::isFunction(const Token *tok, const Token **funcStart, const // regular function? else if (Token::Match(tok, "%var% (") && (Token::Match(tok->next()->link(), ") const| ;|{|=") || - Token::Match(tok->next()->link(), ") : %var% (|::"))) - { + Token::Match(tok->next()->link(), ") : %var% (|::"))) { *funcStart = tok; *argStart = tok->next(); return true; @@ -909,18 +805,15 @@ bool SymbolDatabase::isFunction(const Token *tok, const Token **funcStart, const bool SymbolDatabase::argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, unsigned int depth) const { bool match = false; - while (first->str() == second->str()) - { + while (first->str() == second->str()) { // at end of argument list - if (first->str() == ")") - { + if (first->str() == ")") { match = true; break; } // skip default value assignment - else if (first->next()->str() == "=") - { + else if (first->next()->str() == "=") { first = first->tokAt(2); if (second->next()->str() == "=") @@ -946,8 +839,7 @@ bool SymbolDatabase::argsMatch(const Scope *scope, const Token *first, const Tok // variable names are different else if ((Token::Match(first->next(), "%var% ,|)|=") && Token::Match(second->next(), "%var% ,|)")) && - (first->next()->str() != second->next()->str())) - { + (first->next()->str() != second->next()->str())) { // skip variable names first = first->next(); second = second->next(); @@ -958,16 +850,12 @@ bool SymbolDatabase::argsMatch(const Scope *scope, const Token *first, const Tok } // variable with class path - else if (depth && Token::Match(first->next(), "%var%")) - { + else if (depth && Token::Match(first->next(), "%var%")) { std::string param = path + first->next()->str(); - if (Token::Match(second->next(), param.c_str())) - { + if (Token::Match(second->next(), param.c_str())) { second = second->tokAt(int(depth) * 2); - } - else if (depth > 1) - { + } else if (depth > 1) { std::string short_path = path; // remove last " :: " @@ -978,8 +866,7 @@ bool SymbolDatabase::argsMatch(const Scope *scope, const Token *first, const Tok short_path.resize(short_path.size() - 1); param = short_path + first->next()->str(); - if (Token::Match(second->next(), param.c_str())) - { + if (Token::Match(second->next(), param.c_str())) { second = second->tokAt((int(depth) - 1) * 2); } } @@ -988,8 +875,7 @@ bool SymbolDatabase::argsMatch(const Scope *scope, const Token *first, const Tok // nested class variable else if (depth == 0 && Token::Match(first->next(), "%var%") && second->next()->str() == scope->className && second->strAt(2) == "::" && - first->next()->str() == second->strAt(3)) - { + first->next()->str() == second->strAt(3)) { second = second->tokAt(2); } @@ -1019,16 +905,14 @@ void SymbolDatabase::addFunction(Scope **scope, const Token **tok, const Token * return; // back up to head of path - while (tok1 && tok1->previous() && tok1->previous()->str() == "::") - { + while (tok1 && tok1->previous() && tok1->previous()->str() == "::") { path = tok1->str() + " :: " + path; tok1 = tok1->tokAt(-2); count++; path_length++; } - if (count) - { + if (count) { path = tok1->str() + " :: " + path; path_length++; } @@ -1036,50 +920,40 @@ void SymbolDatabase::addFunction(Scope **scope, const Token **tok, const Token * std::list::iterator it1; // search for match - for (it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) - { + for (it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) { Scope *scope1 = &(*it1); bool match = false; - if (scope1->className == tok1->str() && (scope1->type != Scope::eFunction)) - { + if (scope1->className == tok1->str() && (scope1->type != Scope::eFunction)) { // do the scopes match (same scope) or do their names match (multiple namespaces) if ((*scope == scope1->nestedIn) || (*scope && scope1 && (*scope)->className == scope1->nestedIn->className && !(*scope)->className.empty() && - (*scope)->type == scope1->nestedIn->type)) - { + (*scope)->type == scope1->nestedIn->type)) { Scope *scope2 = scope1; - while (scope2 && count > 0) - { + while (scope2 && count > 0) { count--; tok1 = tok1->tokAt(2); scope2 = scope2->findInNestedList(tok1->str()); } - if (count == 0 && scope2) - { + if (count == 0 && scope2) { match = true; scope1 = scope2; } } } - if (match) - { + if (match) { std::list::iterator func; - for (func = scope1->functionList.begin(); func != scope1->functionList.end(); ++func) - { - if (!func->hasBody) - { + for (func = scope1->functionList.begin(); func != scope1->functionList.end(); ++func) { + if (!func->hasBody) { if (func->type == Function::eDestructor && (*tok)->previous()->str() == "~" && - func->tokenDef->str() == (*tok)->str()) - { - if (argsMatch(scope1, func->tokenDef->next(), (*tok)->next(), path, path_length)) - { + func->tokenDef->str() == (*tok)->str()) { + if (argsMatch(scope1, func->tokenDef->next(), (*tok)->next(), path, path_length)) { func->hasBody = true; func->token = *tok; func->arg = argStart; @@ -1088,17 +962,12 @@ void SymbolDatabase::addFunction(Scope **scope, const Token **tok, const Token * start = start->next(); func->start = start; } - } - else if (func->tokenDef->str() == (*tok)->str() && (*tok)->previous()->str() != "~") - { - if (argsMatch(scope1, func->tokenDef->next(), (*tok)->next(), path, path_length)) - { + } else if (func->tokenDef->str() == (*tok)->str() && (*tok)->previous()->str() != "~") { + if (argsMatch(scope1, func->tokenDef->next(), (*tok)->next(), path, path_length)) { // normal function? - if (!func->retFuncPtr && (*tok)->next()->link()) - { + if (!func->retFuncPtr && (*tok)->next()->link()) { if ((func->isConst && (*tok)->next()->link()->next()->str() == "const") || - (!func->isConst && (*tok)->next()->link()->next()->str() != "const")) - { + (!func->isConst && (*tok)->next()->link()->next()->str() != "const")) { func->hasBody = true; func->token = *tok; func->arg = argStart; @@ -1110,8 +979,7 @@ void SymbolDatabase::addFunction(Scope **scope, const Token **tok, const Token * } // function returning function pointer? - else if (func->retFuncPtr) - { + else if (func->retFuncPtr) { // todo check for const func->hasBody = true; func->token = *tok; @@ -1124,11 +992,9 @@ void SymbolDatabase::addFunction(Scope **scope, const Token **tok, const Token * } } - if (func->hasBody) - { + if (func->hasBody) { addNewFunction(scope, tok); - if (*scope) - { + if (*scope) { (*scope)->functionOf = scope1; (*scope)->function = &*func; (*scope)->function->functionScope = *scope; @@ -1157,14 +1023,12 @@ void SymbolDatabase::addNewFunction(Scope **scope, const Token **tok) while (tok1 && tok1->str() != "{") tok1 = tok1->next(); - if (tok1) - { + if (tok1) { new_scope->classStart = tok1; new_scope->classEnd = tok1->link(); // syntax error? - if (!new_scope->classEnd) - { + if (!new_scope->classEnd) { scopeList.pop_back(); while (tok1->next()) tok1 = tok1->next(); @@ -1176,9 +1040,7 @@ void SymbolDatabase::addNewFunction(Scope **scope, const Token **tok) *scope = new_scope; *tok = tok1; (*scope)->nestedIn->nestedList.push_back(*scope); - } - else - { + } else { scopeList.pop_back(); *scope = NULL; *tok = NULL; @@ -1190,8 +1052,7 @@ const Token *SymbolDatabase::initBaseInfo(Scope *scope, const Token *tok) // goto initial '{' const Token *tok2 = tok->tokAt(2); int level = 0; - while (tok2 && tok2->str() != "{") - { + while (tok2 && tok2->str() != "{") { // skip unsupported templates if (tok2->str() == "<") level++; @@ -1199,8 +1060,7 @@ const Token *SymbolDatabase::initBaseInfo(Scope *scope, const Token *tok) level--; // check for base classes - else if (level == 0 && Token::Match(tok2, ":|,")) - { + else if (level == 0 && Token::Match(tok2, ":|,")) { Scope::BaseInfo base; base.isVirtual = false; @@ -1211,51 +1071,40 @@ const Token *SymbolDatabase::initBaseInfo(Scope *scope, const Token *tok) if (!tok2 || !tok2->next()) return NULL; - if (tok2->str() == "virtual") - { + if (tok2->str() == "virtual") { base.isVirtual = true; tok2 = tok2->next(); } - if (tok2->str() == "public") - { + if (tok2->str() == "public") { base.access = Public; tok2 = tok2->next(); - } - else if (tok2->str() == "protected") - { + } else if (tok2->str() == "protected") { base.access = Protected; tok2 = tok2->next(); - } - else if (tok2->str() == "private") - { + } else if (tok2->str() == "private") { base.access = Private; tok2 = tok2->next(); - } - else - { + } else { if (tok->str() == "class") base.access = Private; else if (tok->str() == "struct") base.access = Public; } - if (tok2->str() == "virtual") - { + if (tok2->str() == "virtual") { base.isVirtual = true; tok2 = tok2->next(); } // handle global namespace - if (tok2->str() == "::") - { + if (tok2->str() == "::") { base.name = ":: "; tok2 = tok2->next(); } // handle derived base classes - while (Token::Match(tok2, "%var% ::")) - { + while (Token::Match(tok2, "%var% ::")) { base.name += tok2->str(); base.name += " :: "; tok2 = tok2->tokAt(2); @@ -1265,23 +1114,19 @@ const Token *SymbolDatabase::initBaseInfo(Scope *scope, const Token *tok) base.scope = NULL; // add unhandled templates - if (tok2->next() && tok2->next()->str() == "<") - { + if (tok2->next() && tok2->next()->str() == "<") { tok2 = tok2->next(); base.name += tok2->str(); int level1 = 1; - while (tok2->next()) - { + while (tok2->next()) { base.name += tok2->next()->str(); - if (tok2->next()->str() == ">") - { + if (tok2->next()->str() == ">") { level1--; if (level1 == 0) break; - } - else if (tok2->next()->str() == "<") + } else if (tok2->next()->str() == "<") level1++; tok2 = tok2->next(); @@ -1299,8 +1144,7 @@ const Token *SymbolDatabase::initBaseInfo(Scope *scope, const Token *tok) void SymbolDatabase::debugMessage(const Token *tok, const std::string &msg) const { - if (tok && _settings->debugwarnings) - { + if (tok && _settings->debugwarnings) { std::list locationList; ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); @@ -1325,12 +1169,10 @@ bool SymbolDatabase::arrayDimensions(std::vector &dimensions, const T const Token *dim = tok; - while (dim && dim->next() && dim->str() == "[") - { + while (dim && dim->next() && dim->str() == "[") { Dimension dimension; // check for empty array dimension [] - if (dim->next()->str() != "]") - { + if (dim->next()->str() != "]") { dimension.start = dim->next(); dimension.end = dim->link()->previous(); if (dimension.start == dimension.end && dimension.start->isNumber()) @@ -1350,8 +1192,7 @@ unsigned int Function::initializedArgCount() const unsigned int count = 0; std::list::const_iterator var; - for (var = argumentList.begin(); var != argumentList.end(); ++var) - { + for (var = argumentList.begin(); var != argumentList.end(); ++var) { if (var->hasDefault()) ++count; } @@ -1362,8 +1203,7 @@ unsigned int Function::initializedArgCount() const void Function::addArguments(const SymbolDatabase *symbolDatabase, const Function *func, const Scope *scope) { // check for non-empty argument list "( ... )" - if (arg->link() != arg->next() && !Token::simpleMatch(arg, "( void )")) - { + if (arg->link() != arg->next() && !Token::simpleMatch(arg, "( void )")) { unsigned int count = 0; const Token *startTok; const Token *endTok; @@ -1372,8 +1212,7 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Function bool isArrayVar; bool hasDefault; const Token *tok = arg->next(); - for (;;) - { + for (;;) { startTok = tok; endTok = NULL; nameTok = NULL; @@ -1382,35 +1221,26 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Function hasDefault = false; std::vector dimensions; - while (tok->str() != "," && tok->str() != ")" && tok->str() != "=") - { - if (tok->varId() != 0) - { + while (tok->str() != "," && tok->str() != ")" && tok->str() != "=") { + if (tok->varId() != 0) { nameTok = tok; endTok = tok->previous(); - } - else if (tok->str() == "[") - { + } else if (tok->str() == "[") { isArrayVar = symbolDatabase->arrayDimensions(dimensions, tok); // skip array dimension(s) tok = tok->link(); while (tok->next()->str() == "[") tok = tok->next()->link(); - } - else if (tok->str() == "<") - { + } else if (tok->str() == "<") { int level = 1; - while (tok && tok->next()) - { + while (tok && tok->next()) { tok = tok->next(); - if (tok->str() == ">") - { + if (tok->str() == ">") { --level; if (level == 0) break; - } - else if (tok->str() == "<") + } else if (tok->str() == "<") level++; } } @@ -1422,22 +1252,17 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Function } // check for argument with no name or missing varid - if (!endTok) - { - if (tok->previous()->isName()) - { - if (tok->previous() != startTok->tokAt(isConstVar ? 1 : 0)) - { + if (!endTok) { + if (tok->previous()->isName()) { + if (tok->previous() != startTok->tokAt(isConstVar ? 1 : 0)) { nameTok = tok->previous(); endTok = nameTok->previous(); if (func->hasBody) symbolDatabase->debugMessage(nameTok, "Function::addArguments found argument \'" + nameTok->str() + "\' with varid 0."); - } - else + } else endTok = startTok; - } - else + } else endTok = tok->previous(); } @@ -1452,8 +1277,7 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Function bool isClassVar = startTok == endTok && !startTok->isStandardType(); // skip default values - if (tok->str() == "=") - { + if (tok->str() == "=") { hasDefault = true; while (tok->str() != "," && tok->str() != ")") @@ -1498,41 +1322,30 @@ Scope::Scope(SymbolDatabase *check_, const Token *classDef_, Scope *nestedIn_) : functionOf(NULL), function(NULL) { - if (!classDef) - { + if (!classDef) { type = Scope::eGlobal; access = Public; - } - else if (classDef->str() == "class") - { + } else if (classDef->str() == "class") { type = Scope::eClass; className = classDef->next()->str(); access = Private; - } - else if (classDef->str() == "struct") - { + } else if (classDef->str() == "struct") { type = Scope::eStruct; // anonymous and unnamed structs don't have a name if (classDef->next()->str() != "{") className = classDef->next()->str(); access = Public; - } - else if (classDef->str() == "union") - { + } else if (classDef->str() == "union") { type = Scope::eUnion; // anonymous and unnamed unions don't have a name if (classDef->next()->str() != "{") className = classDef->next()->str(); access = Public; - } - else if (classDef->str() == "namespace") - { + } else if (classDef->str() == "namespace") { type = Scope::eNamespace; className = classDef->next()->str(); access = Public; - } - else - { + } else { type = Scope::eFunction; className = classDef->str(); access = Public; @@ -1542,12 +1355,10 @@ Scope::Scope(SymbolDatabase *check_, const Token *classDef_, Scope *nestedIn_) : bool Scope::hasDefaultConstructor() const { - if (numConstructors) - { + if (numConstructors) { std::list::const_iterator func; - for (func = functionList.begin(); func != functionList.end(); ++func) - { + for (func = functionList.begin(); func != functionList.end(); ++func) { if (func->type == Function::eConstructor && func->argCount() == 0) return true; } @@ -1557,8 +1368,7 @@ Scope::hasDefaultConstructor() const AccessControl Scope::defaultAccess() const { - switch (type) - { + switch (type) { case eGlobal: return Global; case eClass: @@ -1588,11 +1398,9 @@ void Scope::getVariableList() else start = check->_tokenizer->tokens(); - for (const Token *tok = start; tok; tok = tok->next()) - { + for (const Token *tok = start; tok; tok = tok->next()) { // end of scope? - if (tok->str() == "}") - { + if (tok->str() == "}") { level--; if (level == 0) break; @@ -1603,8 +1411,7 @@ void Scope::getVariableList() break; // Is it a function? - else if (tok->str() == "{") - { + else if (tok->str() == "{") { tok = tok->link(); // syntax error? if (!tok) @@ -1613,27 +1420,20 @@ void Scope::getVariableList() } // Is it a nested class or structure? - else if (Token::Match(tok, "class|struct|union|namespace %type% :|{")) - { + else if (Token::Match(tok, "class|struct|union|namespace %type% :|{")) { tok = tok->tokAt(2); while (tok && tok->str() != "{") tok = tok->next(); - if (tok) - { + if (tok) { // skip implementation tok = tok->link(); continue; - } - else + } else break; - } - else if (Token::Match(tok, "struct|union {") && Token::Match(tok->next()->link(), "} %var% ;|[")) - { + } else if (Token::Match(tok, "struct|union {") && Token::Match(tok->next()->link(), "} %var% ;|[")) { tok = tok->next()->link()->next()->next(); continue; - } - else if (Token::Match(tok, "struct|union {") && Token::Match(tok->next()->link(), "} ;")) - { + } else if (Token::Match(tok, "struct|union {") && Token::Match(tok->next()->link(), "} ;")) { level++; tok = tok->next(); continue; @@ -1641,10 +1441,8 @@ void Scope::getVariableList() // Borland C++: Skip all variables in the __published section. // These are automatically initialized. - else if (tok->str() == "__published:") - { - for (; tok; tok = tok->next()) - { + else if (tok->str() == "__published:") { + for (; tok; tok = tok->next()) { if (tok->str() == "{") tok = tok->link(); if (Token::Match(tok->next(), "private:|protected:|public:")) @@ -1657,25 +1455,19 @@ void Scope::getVariableList() } // "private:" "public:" "protected:" etc - else if (tok->str() == "public:") - { + else if (tok->str() == "public:") { varaccess = Public; continue; - } - else if (tok->str() == "protected:") - { + } else if (tok->str() == "protected:") { varaccess = Protected; continue; - } - else if (tok->str() == "private:") - { + } else if (tok->str() == "private:") { varaccess = Private; continue; } // Is it a forward declaration? - else if (Token::Match(tok, "class|struct|union %var% ;")) - { + else if (Token::Match(tok, "class|struct|union %var% ;")) { tok = tok->tokAt(2); continue; } @@ -1685,8 +1477,7 @@ void Scope::getVariableList() continue; // skip return and delete - else if (Token::Match(tok, "return|delete")) - { + else if (Token::Match(tok, "return|delete")) { while (tok->next() && tok->next()->str() != ";") tok = tok->next(); continue; @@ -1697,8 +1488,7 @@ void Scope::getVariableList() continue; else if (Token::Match(tok, ";|{|}")) continue; - else if (Token::Match(tok, "goto %var% ;")) - { + else if (Token::Match(tok, "goto %var% ;")) { tok = tok->next()->next(); continue; } @@ -1718,29 +1508,25 @@ const Token *Scope::checkVariable(const Token *tok, AccessControl varaccess) // Is it const..? bool isConst = false; - if (tok->str() == "const") - { + if (tok->str() == "const") { tok = tok->next(); isConst = true; } // Is it a static variable? const bool isStatic(Token::simpleMatch(tok, "static")); - if (isStatic) - { + if (isStatic) { tok = tok->next(); } // Is it a mutable variable? const bool isMutable(Token::simpleMatch(tok, "mutable")); - if (isMutable) - { + if (isMutable) { tok = tok->next(); } // Is it const..? - if (tok->str() == "const") - { + if (tok->str() == "const") { tok = tok->next(); isConst = true; } @@ -1750,31 +1536,26 @@ const Token *Scope::checkVariable(const Token *tok, AccessControl varaccess) bool isClass = false; - if (Token::Match(tok, "struct|union")) - { + if (Token::Match(tok, "struct|union")) { tok = tok->next(); } bool isArray = false; std::vector dimensions; - if (tok && isVariableDeclaration(tok, vartok, typetok, isArray)) - { + if (tok && isVariableDeclaration(tok, vartok, typetok, isArray)) { isClass = (!typetok->isStandardType() && vartok->previous()->str() != "*"); - if (isArray) - { + if (isArray) { isArray = check->arrayDimensions(dimensions, vartok->next()); tok = vartok->next(); while (tok && tok->str() == "[") tok = tok->link()->next(); - } - else + } else tok = vartok->next(); } // If the vartok was set in the if-blocks above, create a entry for this variable.. - if (vartok && vartok->str() != "operator") - { + if (vartok && vartok->str() != "operator") { if (vartok->varId() == 0 && !vartok->isBoolean()) check->debugMessage(vartok, "Scope::checkVariable found variable \'" + vartok->str() + "\' with varid 0."); @@ -1793,8 +1574,7 @@ const Variable *Scope::getVariable(const std::string &varname) const { std::list::const_iterator iter; - for (iter = varlist.begin(); iter != varlist.end(); ++iter) - { + for (iter = varlist.begin(); iter != varlist.end(); ++iter) { if (iter->name() == varname) return &*iter; } @@ -1806,12 +1586,10 @@ const Token* skipScopeIdentifiers(const Token* tok) { const Token* ret = tok; - if (Token::simpleMatch(ret, "::")) - { + if (Token::simpleMatch(ret, "::")) { ret = ret->next(); } - while (Token::Match(ret, "%type% ::")) - { + while (Token::Match(ret, "%type% ::")) { ret = ret->tokAt(2); } @@ -1822,8 +1600,7 @@ const Token* skipPointers(const Token* tok) { const Token* ret = tok; - while (Token::simpleMatch(ret, "*")) - { + while (Token::simpleMatch(ret, "*")) { ret = ret->next(); } @@ -1835,42 +1612,32 @@ bool Scope::isVariableDeclaration(const Token* tok, const Token*& vartok, const const Token* localTypeTok = skipScopeIdentifiers(tok); const Token* localVarTok = NULL; - if (Token::Match(localTypeTok, "%type% <")) - { + if (Token::Match(localTypeTok, "%type% <")) { const Token* closeTok = NULL; bool found = findClosingBracket(localTypeTok->next(), closeTok); - if (found) - { + if (found) { localVarTok = skipPointers(closeTok->next()); - if (Token::Match(localVarTok, ":: %type% %var% ;|=")) - { + if (Token::Match(localVarTok, ":: %type% %var% ;|=")) { localTypeTok = localVarTok->next(); localVarTok = localVarTok->tokAt(2); } } - } - else if (Token::Match(localTypeTok, "%type%")) - { + } else if (Token::Match(localTypeTok, "%type%")) { localVarTok = skipPointers(localTypeTok->next()); } - if (isSimpleVariable(localVarTok)) - { + if (isSimpleVariable(localVarTok)) { vartok = localVarTok; typetok = localTypeTok; isArray = false; - } - else if (isArrayVariable(localVarTok)) - { + } else if (isArrayVariable(localVarTok)) { vartok = localVarTok; typetok = localTypeTok; isArray = true; - } - else if ((isLocal() || type == Scope::eFunction) && - Token::Match(localVarTok, "%var% (") && - Token::simpleMatch(localVarTok->next()->link(), ") ;")) - { + } else if ((isLocal() || type == Scope::eFunction) && + Token::Match(localVarTok, "%var% (") && + Token::simpleMatch(localVarTok->next()->link(), ") ;")) { vartok = localVarTok; typetok = localTypeTok; isArray = false; @@ -1892,19 +1659,13 @@ bool Scope::isArrayVariable(const Token* tok) const bool Scope::findClosingBracket(const Token* tok, const Token*& close) const { bool found = false; - if (NULL != tok && tok->str() == "<") - { + if (NULL != tok && tok->str() == "<") { unsigned int depth = 0; - for (close = tok; (close != NULL) && (close->str() != ";") && (close->str() != "="); close = close->next()) - { - if (close->str() == "<") - { + for (close = tok; (close != NULL) && (close->str() != ";") && (close->str() != "="); close = close->next()) { + if (close->str() == "<") { ++depth; - } - else if (close->str() == ">") - { - if (--depth == 0) - { + } else if (close->str() == ">") { + if (--depth == 0) { found = true; break; } @@ -1922,23 +1683,19 @@ const Scope *SymbolDatabase::findVariableType(const Scope *start, const Token *t { std::list::const_iterator scope; - for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) - { + for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) { // skip namespaces and functions if (scope->type == Scope::eNamespace || scope->type == Scope::eFunction || scope->type == Scope::eGlobal) continue; // do the names match? - if (scope->className == type->str()) - { + if (scope->className == type->str()) { // check if type does not have a namespace - if (type->previous()->str() != "::") - { + if (type->previous()->str() != "::") { const Scope *parent = start; // check if in same namespace - while (parent) - { + while (parent) { // out of line class function belongs to class if (parent->type == Scope::eFunction && parent->functionOf) parent = parent->functionOf; @@ -1953,8 +1710,7 @@ const Scope *SymbolDatabase::findVariableType(const Scope *start, const Token *t } // type has a namespace - else - { + else { // FIXME check if namespace path matches supplied path return &(*scope); } @@ -1970,10 +1726,8 @@ const Scope *SymbolDatabase::findFunctionScopeByToken(const Token *tok) const { std::list::const_iterator scope; - for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) - { - if (scope->type == Scope::eFunction) - { + for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) { + if (scope->type == Scope::eFunction) { if (scope->classDef == tok) return &(*scope); } @@ -1987,12 +1741,10 @@ const Function *SymbolDatabase::findFunctionByToken(const Token *tok) const { std::list::const_iterator scope; - for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) - { + for (scope = scopeList.begin(); scope != scopeList.end(); ++scope) { std::list::const_iterator func; - for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) - { + for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { if (func->token == tok) return &(*func); } @@ -2006,8 +1758,7 @@ Scope * Scope::findInNestedList(const std::string & name) { std::list::iterator it; - for (it = nestedList.begin(); it != nestedList.end(); ++it) - { + for (it = nestedList.begin(); it != nestedList.end(); ++it) { if ((*it)->className == name) return (*it); } @@ -2020,14 +1771,12 @@ Scope * Scope::findInNestedListRecursive(const std::string & name) { std::list::iterator it; - for (it = nestedList.begin(); it != nestedList.end(); ++it) - { + for (it = nestedList.begin(); it != nestedList.end(); ++it) { if ((*it)->className == name) return (*it); } - for (it = nestedList.begin(); it != nestedList.end(); ++it) - { + for (it = nestedList.begin(); it != nestedList.end(); ++it) { Scope *child = (*it)->findInNestedListRecursive(name); if (child) return child; @@ -2039,10 +1788,8 @@ Scope * Scope::findInNestedListRecursive(const std::string & name) const Scope * Scope::findQualifiedScope(const std::string & name) const { - if (type == Scope::eClass || type == Scope::eStruct || type == Scope::eNamespace) - { - if (name.compare(0, className.size(), className) == 0) - { + if (type == Scope::eClass || type == Scope::eStruct || type == Scope::eNamespace) { + if (name.compare(0, className.size(), className) == 0) { std::string path = name; path.erase(0, className.size()); if (path.compare(0, 4, " :: ") == 0) @@ -2052,8 +1799,7 @@ const Scope * Scope::findQualifiedScope(const std::string & name) const std::list::const_iterator it; - for (it = nestedList.begin() ; it != nestedList.end(); ++it) - { + for (it = nestedList.begin() ; it != nestedList.end(); ++it) { const Scope *scope1 = (*it)->findQualifiedScope(path); if (scope1) return scope1; @@ -2068,8 +1814,7 @@ const Scope * Scope::findQualifiedScope(const std::string & name) const const Function *Scope::getDestructor() const { std::list::const_iterator it; - for (it = functionList.begin(); it != functionList.end(); ++it) - { + for (it = functionList.begin(); it != functionList.end(); ++it) { if (it->type == Function::eDestructor) return &(*it); } @@ -2082,8 +1827,7 @@ unsigned int Scope::getNestedNonFunctions() const { unsigned int nested = 0; std::list::const_iterator ni; - for (ni = nestedList.begin(); ni != nestedList.end(); ++ni) - { + for (ni = nestedList.begin(); ni != nestedList.end(); ++ni) { if ((*ni)->type != Scope::eFunction) nested++; } diff --git a/lib/symboldatabase.h b/lib/symboldatabase.h index 75df8c8ea..8edc4e690 100644 --- a/lib/symboldatabase.h +++ b/lib/symboldatabase.h @@ -44,8 +44,7 @@ enum AccessControl { Public, Protected, Private, Global, Namespace, Argument, Lo /** * @brief Array dimension information. */ -struct Dimension -{ +struct Dimension { Dimension() : start(NULL), end(NULL), num(0) { } const Token *start; // size start token @@ -54,11 +53,9 @@ struct Dimension }; /** @brief Information about a member variable. */ -class Variable -{ +class Variable { /** @brief flags mask used to access specific bit. */ - enum - { + enum { fIsMutable = (1 << 0), /** @brief mutable variable */ fIsStatic = (1 << 1), /** @brief static variable */ fIsConst = (1 << 2), /** @brief const variable */ @@ -72,8 +69,7 @@ class Variable * @param flag_ flag to get state of * @return true if flag set or false in flag not set */ - bool getFlag(int flag_) const - { + bool getFlag(int flag_) const { return bool((_flags & flag_) != 0); } @@ -82,8 +78,7 @@ class Variable * @param flag_ flag to set state * @param state_ new state of flag */ - void setFlag(int flag_, bool state_) - { + void setFlag(int flag_, bool state_) { _flags = state_ ? _flags | flag_ : _flags & ~flag_; } @@ -100,8 +95,7 @@ public: _access(access_), _flags(0), _type(type_), - _scope(scope_) - { + _scope(scope_) { setFlag(fIsMutable, mutable_); setFlag(fIsStatic, static_); setFlag(fIsConst, const_); @@ -115,8 +109,7 @@ public: * Get name token. * @return name token */ - const Token *nameToken() const - { + const Token *nameToken() const { return _name; } @@ -124,8 +117,7 @@ public: * Get type start token. * @return type start token */ - const Token *typeStartToken() const - { + const Token *typeStartToken() const { return _start; } @@ -133,8 +125,7 @@ public: * Get type end token. * @return type end token */ - const Token *typeEndToken() const - { + const Token *typeEndToken() const { return _end; } @@ -142,8 +133,7 @@ public: * Get name string. * @return name string */ - const std::string &name() const - { + const std::string &name() const { static const std::string noname; // name may not exist for function arguments @@ -157,8 +147,7 @@ public: * Get variable ID. * @return variable ID */ - unsigned int varId() const - { + unsigned int varId() const { // name may not exist for function arguments if (_name) return _name->varId(); @@ -170,8 +159,7 @@ public: * Get index of variable in declared order. * @return varaible index */ - std::size_t index() const - { + std::size_t index() const { return _index; } @@ -179,8 +167,7 @@ public: * Is variable public. * @return true if public, false if not */ - bool isPublic() const - { + bool isPublic() const { return _access == Public; } @@ -188,8 +175,7 @@ public: * Is variable protected. * @return true if protected, false if not */ - bool isProtected() const - { + bool isProtected() const { return _access == Protected; } @@ -197,8 +183,7 @@ public: * Is variable private. * @return true if private, false if not */ - bool isPrivate() const - { + bool isPrivate() const { return _access == Private; } @@ -206,8 +191,7 @@ public: * Is variable global. * @return true if global, false if not */ - bool isGlobal() const - { + bool isGlobal() const { return _access == Global; } @@ -215,8 +199,7 @@ public: * Is variable in a namespace. * @return true if in a namespace, false if not */ - bool isNamespace() const - { + bool isNamespace() const { return _access == Namespace; } @@ -224,8 +207,7 @@ public: * Is variable a function argument. * @return true if a function argument, false if not */ - bool isArgument() const - { + bool isArgument() const { return _access == Argument; } @@ -233,8 +215,7 @@ public: * Is variable local. * @return true if local, false if not */ - bool isLocal() const - { + bool isLocal() const { return _access == Local; } @@ -242,8 +223,7 @@ public: * Is variable mutable. * @return true if mutable, false if not */ - bool isMutable() const - { + bool isMutable() const { return getFlag(fIsMutable); } @@ -251,8 +231,7 @@ public: * Is variable static. * @return true if static, false if not */ - bool isStatic() const - { + bool isStatic() const { return getFlag(fIsStatic); } @@ -260,8 +239,7 @@ public: * Is variable const. * @return true if const, false if not */ - bool isConst() const - { + bool isConst() const { return getFlag(fIsConst); } @@ -269,8 +247,7 @@ public: * Is variable a user defined (or unknown) type. * @return true if user defined type, false if not */ - bool isClass() const - { + bool isClass() const { return getFlag(fIsClass); } @@ -278,8 +255,7 @@ public: * Is variable an array. * @return true if array, false if not */ - bool isArray() const - { + bool isArray() const { return getFlag(fIsArray); } @@ -287,8 +263,7 @@ public: * Does variable have a default value. * @return true if has a default falue, false if not */ - bool hasDefault() const - { + bool hasDefault() const { return getFlag(fHasDefault); } @@ -296,8 +271,7 @@ public: * Get Scope pointer of known type. * @return pointer to type if known, NULL if not known */ - const Scope *type() const - { + const Scope *type() const { return _type; } @@ -305,8 +279,7 @@ public: * Get Scope pointer of enclosing scope. * @return pointer to enclosing scope */ - const Scope *scope() const - { + const Scope *scope() const { return _scope; } @@ -314,8 +287,7 @@ public: * Get array dimensions. * @return array dimensions vector */ - const std::vector &dimensions() const - { + const std::vector &dimensions() const { return _dimensions; } @@ -323,8 +295,7 @@ public: * Get array dimension length. * @return length of dimension */ - MathLib::bigint dimension(size_t index_) const - { + MathLib::bigint dimension(size_t index_) const { return _dimensions[index_].num; } @@ -357,8 +328,7 @@ private: std::vector _dimensions; }; -class Function -{ +class Function { public: enum Type { eConstructor, eCopyConstructor, eOperatorEqual, eDestructor, eFunction }; @@ -380,12 +350,10 @@ public: isOperator(false), retFuncPtr(false), type(eFunction), - functionScope(NULL) - { + functionScope(NULL) { } - unsigned int argCount() const - { + unsigned int argCount() const { return argumentList.size(); } unsigned int initializedArgCount() const; @@ -412,22 +380,19 @@ public: std::list argumentList; // argument list }; -class Scope -{ +class Scope { // let tests access private function for testing friend class TestSymbolDatabase; public: - struct BaseInfo - { + struct BaseInfo { AccessControl access; // public/protected/private bool isVirtual; std::string name; Scope *scope; }; - struct FriendInfo - { + struct FriendInfo { std::string name; Scope *scope; }; @@ -459,13 +424,11 @@ public: Scope *functionOf; // scope this function belongs to Function *function; // function info for this function - bool isClassOrStruct() const - { + bool isClassOrStruct() const { return (type == eClass || type == eStruct); } - bool isLocal() const - { + bool isLocal() const { return (type == eIf || type == eElse || type == eElseIf || type == eFor || type == eWhile || type == eDo || type == eSwitch || type == eUnconditional); @@ -489,8 +452,7 @@ public: const Token *end_, AccessControl access_, bool mutable_, bool static_, bool const_, bool class_, const Scope *type_, const Scope *scope_, bool array_, - const std::vector &dimensions_) - { + const std::vector &dimensions_) { varlist.push_back(Variable(token_, start_, end_, varlist.size(), access_, mutable_, static_, const_, class_, type_, scope_, array_, false, dimensions_)); @@ -543,8 +505,7 @@ private: bool findClosingBracket(const Token* tok, const Token*& close) const; }; -class SymbolDatabase -{ +class SymbolDatabase { public: SymbolDatabase(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger); @@ -565,13 +526,11 @@ public: bool argsMatch(const Scope *info, const Token *first, const Token *second, const std::string &path, unsigned int depth) const; - bool isClassOrStruct(const std::string &type) const - { + bool isClassOrStruct(const std::string &type) const { return bool(classAndStructTypes.find(type) != classAndStructTypes.end()); } - const Variable *getVariableFromVarId(unsigned int varId) const - { + const Variable *getVariableFromVarId(unsigned int varId) const { return _variableList[varId]; } diff --git a/lib/timer.cpp b/lib/timer.cpp index 08ae011ef..ff35f439b 100644 --- a/lib/timer.cpp +++ b/lib/timer.cpp @@ -38,8 +38,7 @@ void TimerResults::ShowResults() std::map::const_iterator I = _results.begin(); const std::map::const_iterator E = _results.end(); - while (I != E) - { + while (I != E) { const double sec = (double)I->second._clocks / CLOCKS_PER_SEC; const double secAverage = (double)(I->second._clocks / I->second._numberOfResults) / CLOCKS_PER_SEC; std::cout << I->first << ": " << sec << "s (avg. " << secAverage << "s - " << I->second._numberOfResults << " result(s))" << std::endl; @@ -77,18 +76,14 @@ Timer::~Timer() void Timer::Stop() { - if ((_showtimeMode != SHOWTIME_NONE) && !_stopped) - { + if ((_showtimeMode != SHOWTIME_NONE) && !_stopped) { const std::clock_t end = std::clock(); const std::clock_t diff = end - _start; - if (_showtimeMode == SHOWTIME_FILE) - { + if (_showtimeMode == SHOWTIME_FILE) { double sec = (double)diff / CLOCKS_PER_SEC; std::cout << _str << ": " << sec << "s" << std::endl; - } - else - { + } else { if (_timerResults) _timerResults->AddResults(_str, diff); } diff --git a/lib/timer.h b/lib/timer.h index 50a24ff60..c0c0bcdfb 100644 --- a/lib/timer.h +++ b/lib/timer.h @@ -23,39 +23,33 @@ #include #include -enum -{ +enum { SHOWTIME_NONE = 0, SHOWTIME_FILE, SHOWTIME_SUMMARY, SHOWTIME_TOP5 }; -class TimerResultsIntf -{ +class TimerResultsIntf { public: virtual ~TimerResultsIntf() { } virtual void AddResults(const std::string& str, std::clock_t clocks) = 0; }; -struct TimerResultsData -{ +struct TimerResultsData { std::clock_t _clocks; long _numberOfResults; TimerResultsData() : _clocks(0) - , _numberOfResults(0) - { + , _numberOfResults(0) { } }; -class TimerResults : public TimerResultsIntf -{ +class TimerResults : public TimerResultsIntf { public: - TimerResults() - { + TimerResults() { } void ShowResults(); @@ -65,8 +59,7 @@ private: std::map _results; }; -class Timer -{ +class Timer { public: Timer(const std::string& str, unsigned int showtimeMode, TimerResultsIntf* timerResults = NULL); ~Timer(); diff --git a/lib/token.cpp b/lib/token.cpp index b4dd2dced..38bb15325 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -58,8 +58,7 @@ void Token::str(const std::string &s) { _str = s; - if (!_str.empty()) - { + if (!_str.empty()) { _isName = bool(_str[0] == '_' || std::isalpha(_str[0])); if (std::isdigit(_str[0])) @@ -105,8 +104,7 @@ void Token::deleteNext() void Token::deleteThis() { - if (_next) - { + if (_next) { _str = _next->_str; _isName = _next->_isName; _isNumber = _next->_isNumber; @@ -124,15 +122,11 @@ void Token::deleteThis() _link->link(this); deleteNext(); - } - else if (_previous) - { + } else if (_previous) { // This should never be used for tokens // at the end of the list str(";"); - } - else - { + } else { // We are the last token in the list, we can't delete // ourselves, so just make us ; str(";"); @@ -158,8 +152,7 @@ void Token::replace(Token *replaceThis, Token *start, Token *end) start->previous(replaceThis->previous()); end->next(replaceThis->next()); - if (end->tokensBack && *(end->tokensBack) == end) - { + if (end->tokensBack && *(end->tokensBack) == end) { while (end->next()) end = end->next(); *(end->tokensBack) = end; @@ -173,8 +166,7 @@ const Token *Token::tokAt(int index) const { const Token *tok = this; int num = std::abs(index); - while (num > 0 && tok) - { + while (num > 0 && tok) { if (index > 0) tok = tok->next(); else @@ -188,8 +180,7 @@ Token *Token::tokAt(int index) { Token *tok = this; int num = std::abs(index); - while (num > 0 && tok) - { + while (num > 0 && tok) { if (index > 0) tok = tok->next(); else @@ -207,13 +198,10 @@ std::string Token::strAt(int index) const static bool strisop(const char str[]) { - if (str[1] == 0) - { + if (str[1] == 0) { if (strchr("+-*/%&|^~!<>", *str)) return true; - } - else if (str[2] == 0) - { + } else if (str[2] == 0) { if ((str[0] == '&' && str[1] == '&') || (str[0] == '|' && str[1] == '|') || (str[0] == '=' && str[1] == '=') || @@ -229,30 +217,24 @@ static bool strisop(const char str[]) int Token::multiCompare(const char *haystack, const char *needle) { - if (haystack[0] == '%' && haystack[1] == 'o') - { + if (haystack[0] == '%' && haystack[1] == 'o') { if (haystack[2] == 'p' && // "%op%|" haystack[3] == '%' && - haystack[4] == '|') - { + haystack[4] == '|') { haystack = haystack + 5; if (strisop(needle)) return 1; - } - else if (haystack[2] == 'r' && // "%or%|" - haystack[3] == '%' && - haystack[4] == '|') - { + } else if (haystack[2] == 'r' && // "%or%|" + haystack[3] == '%' && + haystack[4] == '|') { haystack = haystack + 5; if (*needle == '|') return 1; - } - else if (haystack[2] == 'r' && // "%oror%|" - haystack[3] == 'o' && - haystack[4] == 'r' && - haystack[5] == '%' && - haystack[6] == '|') - { + } else if (haystack[2] == 'r' && // "%oror%|" + haystack[3] == 'o' && + haystack[4] == 'r' && + haystack[5] == '%' && + haystack[6] == '|') { haystack = haystack + 7; if (needle[0] == '|' && needle[1] == '|') return 1; @@ -261,24 +243,17 @@ int Token::multiCompare(const char *haystack, const char *needle) bool emptyStringFound = false; const char *needlePointer = needle; - while (true) - { - if (*needlePointer == *haystack) - { + while (true) { + if (*needlePointer == *haystack) { if (*needlePointer == '\0') return 1; ++needlePointer; ++haystack; - } - else if (*haystack == '|') - { - if (*needlePointer == 0) - { + } else if (*haystack == '|') { + if (*needlePointer == 0) { // If needle is at the end, we have a match. return 1; - } - else if (needlePointer == needle) - { + } else if (needlePointer == needle) { // If needlePointer was not increased at all, we had a empty // string in the haystack emptyStringFound = true; @@ -286,56 +261,44 @@ int Token::multiCompare(const char *haystack, const char *needle) needlePointer = needle; ++haystack; - } - else if (*haystack == ' ' || *haystack == '\0') - { + } else if (*haystack == ' ' || *haystack == '\0') { if (needlePointer == needle) return 0; break; } // If haystack and needle don't share the same character, // find next '|' character. - else - { + else { needlePointer = needle; - do - { + do { ++haystack; - } - while (*haystack != ' ' && *haystack != '|' && *haystack); + } while (*haystack != ' ' && *haystack != '|' && *haystack); - if (*haystack == ' ' || *haystack == '\0') - { + if (*haystack == ' ' || *haystack == '\0') { return emptyStringFound ? 0 : -1; } ++haystack; - if (haystack[0] == '%' && haystack[1] != '|') - { + if (haystack[0] == '%' && haystack[1] != '|') { if (haystack[1] == 'o' && // "%op%" haystack[2] == 'p' && - haystack[3] == '%') - { + haystack[3] == '%') { if (strisop(needle)) return 1; haystack = haystack + 4; - } - else if (haystack[1] == 'o' && // "%or%" - haystack[2] == 'r' && - haystack[3] == '%') - { + } else if (haystack[1] == 'o' && // "%or%" + haystack[2] == 'r' && + haystack[3] == '%') { if (*needle == '|') return 1; haystack = haystack + 4; - } - else if (haystack[1] == 'o' && // "%oror%" - haystack[2] == 'r' && - haystack[3] == 'o' && - haystack[4] == 'r' && - haystack[5] == '%') - { + } else if (haystack[1] == 'o' && // "%oror%" + haystack[2] == 'r' && + haystack[3] == 'o' && + haystack[4] == 'r' && + haystack[5] == '%') { if (needle[0] == '|' && needle[1] == '|') return 1; haystack = haystack + 6; @@ -370,16 +333,14 @@ bool Token::simpleMatch(const Token *tok, const char pattern[]) if (!next) next = pattern + strlen(pattern); - while (*current) - { + while (*current) { size_t length = static_cast(next - current); if (!tok || length != tok->_str.length() || strncmp(current, tok->_str.c_str(), length)) return false; current = next; - if (*next) - { + if (*next) { next = strchr(++current, ' '); if (!next) next = current + strlen(current); @@ -392,15 +353,12 @@ bool Token::simpleMatch(const Token *tok, const char pattern[]) int Token::firstWordEquals(const char *str, const char *word) { - for (;;) - { - if (*str != *word) - { + for (;;) { + if (*str != *word) { if (*str == ' ' && *word == 0) return 0; return 1; - } - else if (*str == 0) + } else if (*str == 0) break; ++str; @@ -412,8 +370,7 @@ int Token::firstWordEquals(const char *str, const char *word) const char *Token::chrInFirstWord(const char *str, char c) { - for (;;) - { + for (;;) { if (*str == ' ' || *str == 0) return 0; @@ -427,8 +384,7 @@ const char *Token::chrInFirstWord(const char *str, char c) int Token::firstWordLen(const char *str) { int len = 0; - for (;;) - { + for (;;) { if (*str == ' ' || *str == 0) break; @@ -443,8 +399,7 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) { const char *p = pattern; bool firstpattern = true; - while (*p) - { + while (*p) { // Skip spaces in pattern.. while (*p == ' ') ++p; @@ -453,22 +408,18 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) if (*p == 0) return true; - if (!tok) - { + if (!tok) { // If we have no tokens, pattern "!!else" should return true - if (p[1] == '!' && p[0] == '!' && p[2] != '\0') - { + if (p[1] == '!' && p[0] == '!' && p[2] != '\0') { while (*p && *p != ' ') ++p; continue; - } - else + } else return false; } // If we are in the first token, we skip all initial !! patterns - if (firstpattern && !tok->previous() && tok->next() && p[1] == '!' && p[0] == '!' && p[2] != '\0') - { + if (firstpattern && !tok->previous() && tok->next() && p[1] == '!' && p[0] == '!' && p[2] != '\0') { while (*p && *p != ' ') ++p; continue; @@ -479,26 +430,20 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) // Compare the first character of the string for optimization reasons // before doing more detailed checks. bool patternUnderstood = false; - if (p[0] == '%') - { - switch (p[1]) - { + if (p[0] == '%') { + switch (p[1]) { case 'v': // TODO: %var% should match only for // variables that have varId != 0, but that needs a lot of // work, before that change can be made. // Any symbolname.. - if (p[4] == '%') // %var% - { + if (p[4] == '%') { // %var% if (!tok->isName()) return false; p += 5; patternUnderstood = true; - } - else // %varid% - { - if (varid == 0) - { + } else { // %varid% + if (varid == 0) { std::list locationList; const ErrorLogger::ErrorMessage errmsg(locationList, Severity::error, @@ -567,13 +512,11 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) break; case 'o': // Or (%or%) and Op (%op%) - if (p[3] == '%') - { + if (p[3] == '%') { patternUnderstood = true; // multicompare.. - if (p[4] == '|') - { + if (p[4] == '|') { int result = multiCompare(p, tok->str().c_str()); if (result == -1) return false; // No match @@ -583,28 +526,22 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) } // single compare.. - else if (p[2] == 'r') - { + else if (p[2] == 'r') { if (tok->str() != "|") return false; p += 4; - } - else if (p[3] == 'p') - { + } else if (p[3] == 'p') { if (!tok->isOp()) return false; p += 4; - } - else + } else patternUnderstood = false; } // Oror (%oror%) - else if (p[5] == '%') - { + else if (p[5] == '%') { // multicompare.. - if (p[6] == '|') - { + if (p[6] == '|') { int result = multiCompare(p, tok->str().c_str()); if (result == -1) return false; // No match @@ -624,16 +561,14 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) } break; default: - if (firstWordEquals(p, tok->_str.c_str())) - { + if (firstWordEquals(p, tok->_str.c_str())) { p += tok->_str.length(); patternUnderstood = true; } break; } - if (!patternUnderstood) - { + if (!patternUnderstood) { return false; } @@ -642,25 +577,21 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) } // [.. => search for a one-character token.. - else if (p[0] == '[' && chrInFirstWord(p, ']')) - { + else if (p[0] == '[' && chrInFirstWord(p, ']')) { if (tok->_str.length() != 1) return false; const char *temp = p + 1; bool chrFound = false; int count = 0; - while (*temp && *temp != ' ') - { - if (*temp == ']') - { + while (*temp && *temp != ' ') { + if (*temp == ']') { ++count; ++temp; continue; } - if (*temp == tok->_str[0]) - { + if (*temp == tok->_str[0]) { chrFound = true; break; } @@ -668,8 +599,7 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) ++temp; } - if (count > 1) - { + if (count > 1) { if (tok->_str[0] == ']') chrFound = true; } @@ -679,32 +609,26 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) } // Parse multi options, such as void|int|char (accept token which is one of these 3) - else if (chrInFirstWord(p, '|') && (p[0] != '|' || firstWordLen(p) > 2)) - { + else if (chrInFirstWord(p, '|') && (p[0] != '|' || firstWordLen(p) > 2)) { int res = multiCompare(p, tok->_str.c_str()); - if (res == 0) - { + if (res == 0) { // Empty alternative matches, use the same token on next round while (*p && *p != ' ') ++p; continue; - } - else if (res == -1) - { + } else if (res == -1) { // No match return false; } } // Parse "not" options. Token can be anything except the given one - else if (p[1] == '!' && p[0] == '!' && p[2] != '\0') - { + else if (p[1] == '!' && p[0] == '!' && p[2] != '\0') { if (firstWordEquals(&(p[2]), tok->str().c_str()) == 0) return false; } - else if (firstWordEquals(p, tok->_str.c_str()) != 0) - { + else if (firstWordEquals(p, tok->_str.c_str()) != 0) { return false; } @@ -726,10 +650,8 @@ size_t Token::getStrLength(const Token *tok) const std::string strValue(tok->strValue()); const char *str = strValue.c_str(); - while (*str) - { - if (*str == '\\') - { + while (*str) { + if (*str == '\\') { ++str; // string ends at '\0' @@ -778,8 +700,7 @@ void Token::move(Token *srcStart, Token *srcEnd, Token *newLocation) const Token *Token::findmatch(const Token *tok, const char pattern[], unsigned int varId) { - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (Token::Match(tok, pattern, varId)) return tok; } @@ -788,8 +709,7 @@ const Token *Token::findmatch(const Token *tok, const char pattern[], unsigned i const Token *Token::findmatch(const Token *tok, const char pattern[], const Token *end, unsigned int varId) { - for (; tok && tok != end; tok = tok->next()) - { + for (; tok && tok != end; tok = tok->next()) { if (Token::Match(tok, pattern, varId)) return tok; } @@ -803,13 +723,10 @@ void Token::insertToken(const std::string &tokenStr) newToken->_linenr = _linenr; newToken->_fileIndex = _fileIndex; newToken->_progressValue = _progressValue; - if (this->next()) - { + if (this->next()) { newToken->next(this->next()); newToken->next()->previous(newToken); - } - else if (tokensBack) - { + } else if (tokensBack) { *tokensBack = newToken; } @@ -822,8 +739,7 @@ void Token::eraseTokens(Token *begin, const Token *end) if (! begin) return; - while (begin->next() && begin->next() != end) - { + while (begin->next() && begin->next() != end) { begin->deleteNext(); } } @@ -863,13 +779,10 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto unsigned int lineNumber = 0; int fileInd = -1; std::map lineNumbers; - for (const Token *tok = this; tok; tok = tok->next()) - { + for (const Token *tok = this; tok; tok = tok->next()) { bool fileChange = false; - if (static_cast(tok->_fileIndex) != fileInd) - { - if (fileInd != -1) - { + if (static_cast(tok->_fileIndex) != fileInd) { + if (fileInd != -1) { lineNumbers[fileInd] = tok->_fileIndex; } @@ -884,10 +797,8 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto fileChange = true; } - if (lineNumber != tok->linenr() || fileChange) - { - while (lineNumber < tok->linenr()) - { + if (lineNumber != tok->linenr() || fileChange) { + while (lineNumber < tok->linenr()) { ++lineNumber; ret << "\n" << lineNumber << ":"; } diff --git a/lib/token.h b/lib/token.h index 9f42be11e..19a88abec 100644 --- a/lib/token.h +++ b/lib/token.h @@ -35,8 +35,7 @@ * * The Token class also has other functions for management of token list, matching tokens, etc. */ -class Token -{ +class Token { private: Token **tokensBack; @@ -51,8 +50,7 @@ public: void concatStr(std::string const& b); - const std::string &str() const - { + const std::string &str() const { return _str; } @@ -137,28 +135,22 @@ public: **/ static size_t getStrLength(const Token *tok); - bool isName() const - { + bool isName() const { return _isName; } - void isName(bool name) - { + void isName(bool name) { _isName = name; } - bool isNumber() const - { + bool isNumber() const { return _isNumber; } - void isNumber(bool number) - { + void isNumber(bool number) { _isNumber = number; } - bool isArithmeticalOp() const - { + bool isArithmeticalOp() const { return (this && (_str=="<<" || _str==">>" || (_str.size()==1 && _str.find_first_of("+-*/%") != std::string::npos))); } - bool isOp() const - { + bool isOp() const { if (!this) return false; @@ -173,13 +165,11 @@ public: _str == ">=" || (_str.size() == 1 && _str.find_first_of("&|^~!") != std::string::npos)); } - bool isExtendedOp() const - { + bool isExtendedOp() const { return isOp() || (this && _str.size() == 1 && _str.find_first_of(",[]()?:") != std::string::npos); } - bool isAssignmentOp() const - { + bool isAssignmentOp() const { if (!this) return false; @@ -195,52 +185,40 @@ public: _str == "<<=" || _str == ">>="); } - bool isBoolean() const - { + bool isBoolean() const { return _isBoolean; } - void isBoolean(bool boolean) - { + void isBoolean(bool boolean) { _isBoolean = boolean; } - bool isUnsigned() const - { + bool isUnsigned() const { return _isUnsigned; } - void isUnsigned(bool sign) - { + void isUnsigned(bool sign) { _isUnsigned = sign; } - bool isSigned() const - { + bool isSigned() const { return _isSigned; } - void isSigned(bool sign) - { + void isSigned(bool sign) { _isSigned = sign; } - bool isPointerCompare() const - { + bool isPointerCompare() const { return _isPointerCompare; } - void isPointerCompare(bool b) - { + void isPointerCompare(bool b) { _isPointerCompare = b; } - bool isLong() const - { + bool isLong() const { return _isLong; } - void isLong(bool size) - { + void isLong(bool size) { _isLong = size; } - bool isUnused() const - { + bool isUnused() const { return _isUnused; } - void isUnused(bool used) - { + void isUnused(bool used) { _isUnused = used; } bool isStandardType() const; @@ -263,26 +241,21 @@ public: */ static int multiCompare(const char *haystack, const char *needle); - unsigned int linenr() const - { + unsigned int linenr() const { return _linenr; } - void linenr(unsigned int lineNumber) - { + void linenr(unsigned int lineNumber) { _linenr = lineNumber; } - unsigned int fileIndex() const - { + unsigned int fileIndex() const { return _fileIndex; } - void fileIndex(unsigned int indexOfFile) - { + void fileIndex(unsigned int indexOfFile) { _fileIndex = indexOfFile; } - Token *next() const - { + Token *next() const { return _next; } @@ -303,18 +276,15 @@ public: */ void insertToken(const std::string &tokenStr); - Token *previous() const - { + Token *previous() const { return _previous; } - unsigned int varId() const - { + unsigned int varId() const { return _varId; } - void varId(unsigned int id) - { + void varId(unsigned int id) { _varId = id; } @@ -361,8 +331,7 @@ public: * @param linkToToken The token where this token should link * to. */ - void link(Token *linkToToken) - { + void link(Token *linkToToken) { _link = linkToToken; } @@ -373,8 +342,7 @@ public: * * @return The token where this token links to. */ - Token *link() const - { + Token *link() const { return _link; } @@ -401,14 +369,12 @@ public: static void move(Token *srcStart, Token *srcEnd, Token *newLocation); /** Get progressValue */ - unsigned int progressValue() const - { + unsigned int progressValue() const { return _progressValue; } /** Calculate progress values for all tokens */ - void assignProgressValues() - { + void assignProgressValues() { unsigned int total_count = 0; for (Token *tok = this; tok; tok = tok->next()) ++total_count; @@ -418,12 +384,10 @@ public: } private: - void next(Token *nextToken) - { + void next(Token *nextToken) { _next = nextToken; } - void previous(Token *previousToken) - { + void previous(Token *previousToken) { _previous = previousToken; } diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index e32a75901..c589a1239 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -120,19 +120,15 @@ void Tokenizer::addtoken(const char str[], const unsigned int lineno, const unsi return; // If token contains # characters, split it up - if (split && strstr(str, "##")) - { + if (split && strstr(str, "##")) { std::string temp; - for (unsigned int i = 0; str[i]; ++i) - { - if (strncmp(&str[i], "##", 2) == 0) - { + for (unsigned int i = 0; str[i]; ++i) { + if (strncmp(&str[i], "##", 2) == 0) { addtoken(temp.c_str(), lineno, fileno, false); temp.clear(); addtoken("##", lineno, fileno, false); ++i; - } - else + } else temp += str[i]; } addtoken(temp.c_str(), lineno, fileno, false); @@ -141,25 +137,17 @@ void Tokenizer::addtoken(const char str[], const unsigned int lineno, const unsi // Replace hexadecimal value with decimal std::ostringstream str2; - if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0) - { + if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0) { str2 << std::strtoul(str + 2, NULL, 16); - } - else if (strncmp(str, "_Bool", 5) == 0) - { + } else if (strncmp(str, "_Bool", 5) == 0) { str2 << "bool"; - } - else - { + } else { str2 << str; } - if (_tokensBack) - { + if (_tokensBack) { _tokensBack->insertToken(str2.str().c_str()); - } - else - { + } else { _tokens = new Token(&_tokensBack); _tokensBack = _tokens; _tokensBack->str(str2.str()); @@ -176,21 +164,15 @@ void Tokenizer::addtoken(const Token * tok, const unsigned int lineno, const uns // Replace hexadecimal value with decimal std::ostringstream str2; - if (strncmp(tok->str().c_str(), "0x", 2) == 0) - { + if (strncmp(tok->str().c_str(), "0x", 2) == 0) { str2 << std::strtoul(tok->str().c_str() + 2, NULL, 16); - } - else - { + } else { str2 << tok->str(); } - if (_tokensBack) - { + if (_tokensBack) { _tokensBack->insertToken(str2.str().c_str()); - } - else - { + } else { _tokens = new Token(&_tokensBack); _tokensBack = _tokens; _tokensBack->str(str2.str()); @@ -222,8 +204,7 @@ unsigned int Tokenizer::sizeOfType(const Token *type) const std::map::const_iterator it = _typeSize.find(type->str()); if (it == _typeSize.end()) return 0; - else if (type->isLong()) - { + else if (type->isLong()) { if (type->str() == "double") return _settings->sizeof_long_double; else if (type->str() == "long") @@ -242,16 +223,14 @@ void Tokenizer::insertTokens(Token *dest, const Token *src, unsigned int n) { std::stack link; - while (n > 0) - { + while (n > 0) { dest->insertToken(src->str()); dest = dest->next(); // Set links if (Token::Match(dest, "(|[|{")) link.push(dest); - else if (!link.empty() && Token::Match(dest, ")|]|}")) - { + else if (!link.empty() && Token::Match(dest, ")|]|}")) { Token::createMutualLinks(dest, link.top()); link.pop(); } @@ -278,8 +257,7 @@ Token *Tokenizer::copyTokens(Token *dest, const Token *first, const Token *last) { std::stack links; Token *tok2 = dest; - for (const Token *tok = first; tok != last->next(); tok = tok->next()) - { + for (const Token *tok = first; tok != last->next(); tok = tok->next()) { tok2->insertToken(tok->str()); tok2 = tok2->next(); tok2->fileIndex(dest->fileIndex()); @@ -297,8 +275,7 @@ Token *Tokenizer::copyTokens(Token *dest, const Token *first, const Token *last) // Check for links and fix them up if (tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{") links.push(tok2); - else if (tok2->str() == ")" || tok2->str() == "]" || tok2->str() == "}") - { + else if (tok2->str() == ")" || tok2->str() == "]" || tok2->str() == "}") { Token * link = links.top(); tok2->link(link); @@ -336,19 +313,16 @@ void Tokenizer::createTokens(std::istream &code) unsigned int FileIndex = 0; // Read one byte at a time from code and create tokens - for (char ch = (char)code.get(); code.good(); ch = (char)code.get()) - { + for (char ch = (char)code.get(); code.good(); ch = (char)code.get()) { // char/string.. // multiline strings are not handled. The preprocessor should handle that for us. - if (ch == '\'' || ch == '\"') - { + if (ch == '\'' || ch == '\"') { std::string line; // read char bool special = false; char c = ch; - do - { + do { // Append token.. line += c; @@ -360,13 +334,11 @@ void Tokenizer::createTokens(std::istream &code) // Get next character c = (char)code.get(); - } - while (code.good() && (special || c != ch)); + } while (code.good() && (special || c != ch)); line += ch; // Handle #file "file.h" - if (CurrentToken == "#file") - { + if (CurrentToken == "#file") { // Extract the filename line = line.substr(1, line.length() - 2); @@ -374,18 +346,15 @@ void Tokenizer::createTokens(std::istream &code) ++lineno; bool foundOurfile = false; fileIndexes.push_back(FileIndex); - for (unsigned int i = 0; i < _files.size(); i++) - { - if (Path::sameFileName(_files[i].c_str(), line.c_str())) - { + for (unsigned int i = 0; i < _files.size(); i++) { + if (Path::sameFileName(_files[i].c_str(), line.c_str())) { // Use this index foundOurfile = true; FileIndex = i; } } - if (!foundOurfile) - { + if (!foundOurfile) { // The "_files" vector remembers what files have been tokenized.. _files.push_back(Path::simplifyPath(line.c_str())); FileIndex = static_cast(_files.size() - 1); @@ -393,9 +362,7 @@ void Tokenizer::createTokens(std::istream &code) lineNumbers.push_back(lineno); lineno = 0; - } - else - { + } else { // Add previous token addtoken(CurrentToken.c_str(), lineno, FileIndex); @@ -408,31 +375,22 @@ void Tokenizer::createTokens(std::istream &code) continue; } - if (strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch)) - { + if (strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch)) { if (ch == '.' && CurrentToken.length() > 0 && - std::isdigit(CurrentToken[0])) - { + std::isdigit(CurrentToken[0])) { // Don't separate doubles "5.4" - } - else if (strchr("+-", ch) && - CurrentToken.length() > 0 && - std::isdigit(CurrentToken[0]) && - (CurrentToken[CurrentToken.length()-1] == 'e' || - CurrentToken[CurrentToken.length()-1] == 'E')) - { + } else if (strchr("+-", ch) && + CurrentToken.length() > 0 && + std::isdigit(CurrentToken[0]) && + (CurrentToken[CurrentToken.length()-1] == 'e' || + CurrentToken[CurrentToken.length()-1] == 'E')) { // Don't separate doubles "4.2e+10" - } - else if (CurrentToken.empty() && ch == '.' && std::isdigit(code.peek())) - { + } else if (CurrentToken.empty() && ch == '.' && std::isdigit(code.peek())) { // tokenize .125 into 0.125 CurrentToken = "0"; - } - else if (ch=='&' && code.peek() == '&') - { - if (!CurrentToken.empty()) - { + } else if (ch=='&' && code.peek() == '&') { + if (!CurrentToken.empty()) { addtoken(CurrentToken.c_str(), lineno, FileIndex, true); CurrentToken.clear(); } @@ -441,33 +399,23 @@ void Tokenizer::createTokens(std::istream &code) ch = (char)code.get(); addtoken("&&", lineno, FileIndex, true); continue; - } - else if (ch==':' && CurrentToken.empty() && code.peek() == ' ') - { + } else if (ch==':' && CurrentToken.empty() && code.peek() == ' ') { // : addtoken(":", lineno, FileIndex, true); CurrentToken.clear(); continue; - } - else if (ch==':' && CurrentToken.empty() && code.peek() == ':') - { + } else if (ch==':' && CurrentToken.empty() && code.peek() == ':') { // :: ch = (char)code.get(); addtoken("::", lineno, FileIndex, true); CurrentToken.clear(); continue; - } - else - { - if (CurrentToken == "#file") - { + } else { + if (CurrentToken == "#file") { // Handle this where strings are handled continue; - } - else if (CurrentToken == "#endfile") - { - if (lineNumbers.empty() || fileIndexes.empty()) - { + } else if (CurrentToken == "#endfile") { + if (lineNumbers.empty() || fileIndexes.empty()) { cppcheckError(0); deallocateTokens(); return; @@ -485,13 +433,10 @@ void Tokenizer::createTokens(std::istream &code) CurrentToken.clear(); - if (ch == '\n') - { + if (ch == '\n') { ++lineno; continue; - } - else if (ch == ' ') - { + } else if (ch == ' ') { continue; } @@ -518,8 +463,7 @@ void Tokenizer::duplicateTypedefError(const Token *tok1, const Token *tok2, cons std::list locationList; std::string tok2_str; - if (tok1 && tok2) - { + if (tok1 && tok2) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok1->linenr(); loc.setfile(file(tok1)); @@ -528,8 +472,7 @@ void Tokenizer::duplicateTypedefError(const Token *tok1, const Token *tok2, cons loc.setfile(file(tok2)); locationList.push_back(loc); tok2_str = tok2->str(); - } - else + } else tok2_str = "name"; const ErrorLogger::ErrorMessage errmsg(locationList, @@ -552,8 +495,7 @@ void Tokenizer::duplicateDeclarationError(const Token *tok1, const Token *tok2, std::list locationList; std::string tok2_str; - if (tok1 && tok2) - { + if (tok1 && tok2) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok1->linenr(); loc.setfile(file(tok1)); @@ -562,8 +504,7 @@ void Tokenizer::duplicateDeclarationError(const Token *tok1, const Token *tok2, loc.setfile(file(tok2)); locationList.push_back(loc); tok2_str = tok2->str(); - } - else + } else tok2_str = "name"; const ErrorLogger::ErrorMessage errmsg(locationList, @@ -584,16 +525,12 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token { // check for an end of definition const Token * tok = *tokPtr; - if (tok && Token::Match(tok->next(), ";|,|[|=|)|>|(|{")) - { + if (tok && Token::Match(tok->next(), ";|,|[|=|)|>|(|{")) { const Token * end = tok->next(); - if (end->str() == "[") - { + if (end->str() == "[") { end = end->link()->next(); - } - else if (end->str() == ",") - { + } else if (end->str() == ",") { // check for derived class if (Token::Match(tok->previous(), "public|private|protected")) return false; @@ -601,8 +538,7 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token // find end of definition int level = 0; while (end && end->next() && (!Token::Match(end->next(), ";|)|>") || - (end->next()->str() == ")" && level == 0))) - { + (end->next()->str() == ")" && level == 0))) { if (end->next()->str() == "(") level++; else if (end->next()->str() == ")") @@ -612,25 +548,16 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token } if (end) end = end->next(); - } - else if (end->str() == "(") - { - if (tok->previous()->str().find("operator") == 0) - { + } else if (end->str() == "(") { + if (tok->previous()->str().find("operator") == 0) { // conversion operator return false; - } - else if (tok->previous()->str() == "typedef") - { + } else if (tok->previous()->str() == "typedef") { // typedef of function returning this type return false; - } - else if (Token::Match(tok->previous(), "public:|private:|protected:")) - { + } else if (Token::Match(tok->previous(), "public:|private:|protected:")) { return false; - } - else if (tok->previous()->str() == ">") - { + } else if (tok->previous()->str() == ">") { if (!Token::Match(tok->tokAt(-2), "%type%")) return false; @@ -640,11 +567,8 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token duplicateTypedefError(*tokPtr, name, "Template instantiation"); *tokPtr = end->link(); return true; - } - else if (Token::Match(tok->previous(), "%type%")) - { - if (end->link()->next()->str() == "{") - { + } else if (Token::Match(tok->previous(), "%type%")) { + if (end->link()->next()->str() == "{") { duplicateTypedefError(*tokPtr, name, "Function"); *tokPtr = end->link()->next()->link(); return true; @@ -652,128 +576,88 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token } } - if (end) - { - if (Token::simpleMatch(end, ") {")) // function parameter ? - { + if (end) { + if (Token::simpleMatch(end, ") {")) { // function parameter ? // look backwards if (Token::Match(tok->previous(), "%type%") && - !Token::Match(tok->previous(), "return|new|const")) - { + !Token::Match(tok->previous(), "return|new|const")) { duplicateTypedefError(*tokPtr, name, "Function parameter"); // duplicate definition so skip entire function *tokPtr = end->next()->link(); return true; } - } - else if (end->str() == ">") // template parameter ? - { + } else if (end->str() == ">") { // template parameter ? // look backwards if (Token::Match(tok->previous(), "%type%") && - !Token::Match(tok->previous(), "return|new|const|volatile")) - { + !Token::Match(tok->previous(), "return|new|const|volatile")) { // duplicate definition so skip entire template while (end && end->str() != "{") end = end->next(); - if (end) - { + if (end) { duplicateTypedefError(*tokPtr, name, "Template parameter"); *tokPtr = end->link(); return true; } } - } - else - { + } else { // look backwards if (Token::Match(tok->previous(), "typedef|}|>") || (tok->previous()->str() == "*" && tok->next()->str() != "(") || (Token::Match(tok->previous(), "%type%") && (!Token::Match(tok->previous(), "return|new|const|friend|public|private|protected|throw|extern") && - !Token::simpleMatch(tok->tokAt(-2), "friend class")))) - { + !Token::simpleMatch(tok->tokAt(-2), "friend class")))) { // scan backwards for the end of the previous statement int level = (tok->previous()->str() == "}") ? 1 : 0; - while (tok && tok->previous() && (!Token::Match(tok->previous(), ";|{") || (level != 0))) - { - if (tok->previous()->str() == "}") - { + while (tok && tok->previous() && (!Token::Match(tok->previous(), ";|{") || (level != 0))) { + if (tok->previous()->str() == "}") { tok = tok->previous()->link(); - } - else if (tok->previous()->str() == "typedef") - { + } else if (tok->previous()->str() == "typedef") { duplicateTypedefError(*tokPtr, name, "Typedef"); return true; - } - else if (tok->previous()->str() == "enum") - { + } else if (tok->previous()->str() == "enum") { duplicateTypedefError(*tokPtr, name, "Enum"); return true; - } - else if (tok->previous()->str() == "struct") - { + } else if (tok->previous()->str() == "struct") { if (tok->strAt(-2) == "typedef" && tok->next()->str() == "{" && - typeDef->strAt(3) != "{") - { + typeDef->strAt(3) != "{") { // declaration after forward declaration return true; - } - else if (tok->next()->str() == "{") - { + } else if (tok->next()->str() == "{") { if (!undefinedStruct) duplicateTypedefError(*tokPtr, name, "Struct"); return true; - } - else if (Token::Match(tok->next(), ")|*")) - { + } else if (Token::Match(tok->next(), ")|*")) { return true; - } - else if (tok->next()->str() == name->str()) - { + } else if (tok->next()->str() == name->str()) { return true; - } - else if (tok->next()->str() != ";") - { + } else if (tok->next()->str() != ";") { duplicateTypedefError(*tokPtr, name, "Struct"); return true; - } - else - { + } else { // forward declaration after declaration duplicateDeclarationError(*tokPtr, name, "Struct"); return false; } - } - else if (tok->previous()->str() == "union") - { - if (tok->next()->str() != ";") - { + } else if (tok->previous()->str() == "union") { + if (tok->next()->str() != ";") { duplicateTypedefError(*tokPtr, name, "Union"); return true; - } - else - { + } else { // forward declaration after declaration duplicateDeclarationError(*tokPtr, name, "Union"); return false; } - } - else if (tok->previous()->str() == "class") - { - if (tok->next()->str() != ";") - { + } else if (tok->previous()->str() == "class") { + if (tok->next()->str() != ";") { duplicateTypedefError(*tokPtr, name, "Class"); return true; - } - else - { + } else { // forward declaration after declaration duplicateDeclarationError(*tokPtr, name, "Class"); return false; } - } - else if (tok->previous()->str() == "{") + } else if (tok->previous()->str() == "{") level--; tok = tok->previous(); @@ -797,8 +681,7 @@ void Tokenizer::unsupportedTypedef(const Token *tok) const std::ostringstream str; const Token *tok1 = tok; int level = 0; - while (tok) - { + while (tok) { if (level == 0 && tok->str() == ";") break; else if (tok->str() == "{") @@ -837,8 +720,7 @@ Token * Tokenizer::deleteInvalidTypedef(Token *typeDef) int level = 0; // remove typedef but leave ; - while (typeDef->next()) - { + while (typeDef->next()) { if (level == 0 && typeDef->next()->str() == ";") break; else if (typeDef->next()->str() == "{") @@ -848,13 +730,10 @@ Token * Tokenizer::deleteInvalidTypedef(Token *typeDef) typeDef->deleteNext(); } - if (typeDef != _tokens) - { + if (typeDef != _tokens) { tok = typeDef->previous(); tok->deleteNext(); - } - else - { + } else { _tokens->deleteThis(); tok = _tokens; } @@ -862,8 +741,7 @@ Token * Tokenizer::deleteInvalidTypedef(Token *typeDef) return tok; } -struct Space -{ +struct Space { bool isNamespace; std::string className; const Token * classEnd; @@ -875,33 +753,26 @@ static Token *splitDefinitionFromTypedef(Token *tok) std::string name; bool isConst = false; - if (tok->next()->str() == "const") - { + if (tok->next()->str() == "const") { tok->next()->deleteThis(); isConst = true; } - if (tok->tokAt(2)->str() == "{") // unnamed - { + if (tok->tokAt(2)->str() == "{") { // unnamed tok1 = tok->tokAt(2)->link(); - if (tok1 && tok1->next()) - { + if (tok1 && tok1->next()) { // use typedef name if available if (Token::Match(tok1->next(), "%type%")) name = tok1->next()->str(); - else // create a unique name - { + else { // create a unique name static long count = 0; name = "Unnamed" + MathLib::toString(count++); } tok->tokAt(1)->insertToken(name.c_str()); - } - else + } else return NULL; - } - else if (tok->strAt(3) == ":") - { + } else if (tok->strAt(3) == ":") { tok1 = tok->tokAt(4); while (tok1 && tok1->str() != "{") tok1 = tok1->next(); @@ -911,9 +782,7 @@ static Token *splitDefinitionFromTypedef(Token *tok) tok1 = tok1->link(); name = tok->tokAt(2)->str(); - } - else // has a name - { + } else { // has a name tok1 = tok->tokAt(3)->link(); if (!tok1) @@ -925,19 +794,15 @@ static Token *splitDefinitionFromTypedef(Token *tok) tok1->insertToken(";"); tok1 = tok1->next(); - if (tok1->next() && tok1->next()->str() == ";" && tok1 && tok1->previous()->str() == "}") - { + if (tok1->next() && tok1->next()->str() == ";" && tok1 && tok1->previous()->str() == "}") { tok->deleteThis(); tok1->deleteThis(); return NULL; - } - else - { + } else { tok1->insertToken("typedef"); tok1 = tok1->next(); Token * tok3 = tok1; - if (isConst) - { + if (isConst) { tok1->insertToken("const"); tok1 = tok1->next(); } @@ -959,8 +824,7 @@ static Token *splitDefinitionFromTypedef(Token *tok) static Token *processFunc(Token *tok2, bool inOperator) { if (tok2->next() && tok2->next()->str() != ")" && - tok2->next()->str() != ",") - { + tok2->next()->str() != ",") { // skip over tokens for some types of canonicalization if (Token::Match(tok2->next(), "( * %type% ) (")) tok2 = tok2->tokAt(5)->link(); @@ -976,12 +840,10 @@ static Token *processFunc(Token *tok2, bool inOperator) else if (Token::Match(tok2->next(), "* [") && Token::simpleMatch(tok2->tokAt(2)->link(), "] ;")) tok2 = tok2->next(); - else - { + else { if (tok2->next()->str() == "(") tok2 = tok2->next()->link(); - else if (!inOperator && !Token::Match(tok2->next(), "[|>|;")) - { + else if (!inOperator && !Token::Match(tok2->next(), "[|>|;")) { tok2 = tok2->next(); while (Token::Match(tok2, "*|&") && @@ -993,8 +855,7 @@ static Token *processFunc(Token *tok2, bool inOperator) tok2 = tok2->tokAt(2); if (tok2->str() == "(" && - tok2->link()->next()->str() == "(") - { + tok2->link()->next()->str() == "(") { tok2 = tok2->link(); if (tok2->next()->str() == "(") @@ -1002,8 +863,7 @@ static Token *processFunc(Token *tok2, bool inOperator) } // skip over typedef parameter - if (tok2->next()->str() == "(") - { + if (tok2->next()->str() == "(") { tok2 = tok2->next()->link(); if (tok2->next()->str() == "(") @@ -1021,26 +881,20 @@ void Tokenizer::simplifyTypedef() bool isNamespace = false; std::string className; bool hasClass = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (_errorLogger && !_files.empty()) _errorLogger->reportProgress(_files[0], "Tokenize (typedef)", tok->progressValue()); if (Token::Match(tok, "class|struct|namespace %any%") && - (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) - { + (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) { isNamespace = (tok->str() == "namespace"); hasClass = true; className = tok->next()->str(); continue; - } - else if (hasClass && tok->str() == ";") - { + } else if (hasClass && tok->str() == ";") { hasClass = false; continue; - } - else if (hasClass && tok->str() == "{") - { + } else if (hasClass && tok->str() == "{") { Space info; info.isNamespace = isNamespace; info.className = className; @@ -1049,18 +903,14 @@ void Tokenizer::simplifyTypedef() hasClass = false; continue; - } - else if (!spaceInfo.empty() && tok->str() == "}" && spaceInfo.back().classEnd == tok) - { + } else if (!spaceInfo.empty() && tok->str() == "}" && spaceInfo.back().classEnd == tok) { spaceInfo.pop_back(); continue; - } - else if (tok->str() != "typedef") + } else if (tok->str() != "typedef") continue; // check for syntax errors - if (tok->previous() && tok->previous()->str() == "(") - { + if (tok->previous() && tok->previous()->str() == "(") { syntaxError(tok); continue; } @@ -1068,20 +918,16 @@ void Tokenizer::simplifyTypedef() // pull struct, union, enum or class definition out of typedef // use typedef name for unnamed struct, union, enum or class if (Token::Match(tok->next(), "const| struct|enum|union|class %type% {") || - Token::Match(tok->next(), "const| struct|enum|union|class {")) - { + Token::Match(tok->next(), "const| struct|enum|union|class {")) { Token *tok1 = splitDefinitionFromTypedef(tok); if (!tok1) continue; tok = tok1; - } - else if (Token::Match(tok->next(), "const| struct|class %type% :")) - { + } else if (Token::Match(tok->next(), "const| struct|class %type% :")) { Token *tok1 = tok; while (tok1 && tok1->str() != ";" && tok1->str() != "{") tok1 = tok1->next(); - if (tok1 && tok1->str() == "{") - { + if (tok1 && tok1->str() == "{") { tok1 = splitDefinitionFromTypedef(tok); if (!tok1) continue; @@ -1091,18 +937,14 @@ void Tokenizer::simplifyTypedef() /** @todo add support for union */ bool undefinedStruct = false; - if (Token::Match(tok, "typedef enum|struct %type% %type% ;") && tok->strAt(2) == tok->strAt(3)) - { - if (tok->strAt(1) == "enum") - { + if (Token::Match(tok, "typedef enum|struct %type% %type% ;") && tok->strAt(2) == tok->strAt(3)) { + if (tok->strAt(1) == "enum") { tok->deleteThis(); tok->deleteThis(); tok->deleteThis(); tok->deleteThis(); continue; - } - else - { + } else { const std::string pattern("struct " + tok->strAt(2) + " {|:"); const Token *tok2 = Token::findmatch(_tokens, pattern.c_str(), tok); if (!tok2) @@ -1139,15 +981,13 @@ void Tokenizer::simplifyTypedef() Token *namespaceEnd = 0; // check for invalid input - if (!tok->next()) - { + if (!tok->next()) { syntaxError(tok); return; } if (Token::simpleMatch(tok->next(), "::") || - Token::Match(tok->next(), "%type%")) - { + Token::Match(tok->next(), "%type%")) { typeStart = tok->next(); offset = 1; @@ -1158,56 +998,44 @@ void Tokenizer::simplifyTypedef() typeEnd = tok->tokAt(offset++); bool atEnd = false; - while (!atEnd) - { + while (!atEnd) { if (Token::simpleMatch(tok->tokAt(offset), "::")) typeEnd = tok->tokAt(offset++); if (Token::Match(tok->tokAt(offset), "%type%") && tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), "[|;|,|(")) typeEnd = tok->tokAt(offset++); - else if (Token::simpleMatch(tok->tokAt(offset), "const (")) - { + else if (Token::simpleMatch(tok->tokAt(offset), "const (")) { typeEnd = tok->tokAt(offset++); atEnd = true; - } - else + } else atEnd = true; } - } - else + } else continue; // invalid input // check for invalid input - if (!tok->tokAt(offset)) - { + if (!tok->tokAt(offset)) { syntaxError(tok); return; } // check for template - if (tok->tokAt(offset)->str() == "<") - { + if (tok->tokAt(offset)->str() == "<") { int level = 1; int paren = 0; typeEnd = tok->tokAt(offset + 1); - for (; typeEnd ; typeEnd = typeEnd->next()) - { - if (typeEnd->str() == ">") - { - if (paren == 0) - { + for (; typeEnd ; typeEnd = typeEnd->next()) { + if (typeEnd->str() == ">") { + if (paren == 0) { level--; if (level == 0) break; } - } - else if (typeEnd->str() == "<") - { + } else if (typeEnd->str() == "<") { if (paren == 0) level++; - } - else if (typeEnd->str() == "(") + } else if (typeEnd->str() == "(") paren++; else if (typeEnd->str() == ")") paren--; @@ -1216,8 +1044,7 @@ void Tokenizer::simplifyTypedef() while (typeEnd && Token::Match(typeEnd->next(), ":: %type%")) typeEnd = typeEnd->tokAt(2); - if (!typeEnd) - { + if (!typeEnd) { // internal error return; } @@ -1234,25 +1061,21 @@ void Tokenizer::simplifyTypedef() pointers.push_back(tok->tokAt(offset++)->str()); // check for invalid input - if (!tok->tokAt(offset)) - { + if (!tok->tokAt(offset)) { syntaxError(tok); return; } - if (Token::Match(tok->tokAt(offset), "%type%")) - { + if (Token::Match(tok->tokAt(offset), "%type%")) { // found the type name typeName = tok->tokAt(offset++); // check for array - if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") - { + if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") { arrayStart = tok->tokAt(offset); bool atEnd = false; - while (!atEnd) - { + while (!atEnd) { while (tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) offset++; @@ -1274,19 +1097,16 @@ void Tokenizer::simplifyTypedef() tok = tok->tokAt(offset); // or a function typedef - else if (Token::simpleMatch(tok->tokAt(offset), "(")) - { + else if (Token::simpleMatch(tok->tokAt(offset), "(")) { // unhandled typedef, skip it and continue - if (typeName->str() == "void") - { + if (typeName->str() == "void") { unsupportedTypedef(typeDef); tok = deleteInvalidTypedef(typeDef); continue; } // function pointer - else if (Token::Match(tok->tokAt(offset), "( * %var% ) (")) - { + else if (Token::Match(tok->tokAt(offset), "( * %var% ) (")) { // name token wasn't a name, it was part of the type typeEnd = typeEnd->next(); functionPtr = true; @@ -1299,11 +1119,9 @@ void Tokenizer::simplifyTypedef() } // function - else if (Token::Match(tok->tokAt(offset)->link(), ") const| ;|,")) - { + else if (Token::Match(tok->tokAt(offset)->link(), ") const| ;|,")) { function = true; - if (tok->tokAt(offset)->link()->next()->str() == "const") - { + if (tok->tokAt(offset)->link()->next()->str() == "const") { specStart = tok->tokAt(offset)->link()->next(); specEnd = specStart; } @@ -1315,16 +1133,14 @@ void Tokenizer::simplifyTypedef() } // syntax error - else - { + else { syntaxError(tok); return; } } // unhandled typedef, skip it and continue - else - { + else { unsupportedTypedef(typeDef); tok = deleteInvalidTypedef(typeDef); continue; @@ -1333,8 +1149,7 @@ void Tokenizer::simplifyTypedef() // typeof: typedef __typeof__ ( ... ) type; else if (Token::simpleMatch(tok->tokAt(offset - 1), "__typeof__ (") && - Token::Match(tok->tokAt(offset)->link(), ") %type% ;")) - { + Token::Match(tok->tokAt(offset)->link(), ") %type% ;")) { argStart = tok->tokAt(offset); argEnd = tok->tokAt(offset)->link(); typeName = tok->tokAt(offset)->link()->next(); @@ -1353,12 +1168,10 @@ void Tokenizer::simplifyTypedef() Token::Match(tok->tokAt(offset + 1)->link()->next()->link(), ") const|volatile| ) ;|,")) || (Token::simpleMatch(tok->tokAt(offset), "( * (") && Token::Match(tok->tokAt(offset + 2)->link()->previous(), "%type% ) (") && - Token::Match(tok->tokAt(offset + 2)->link()->next()->link(), ") const|volatile| ) ;|,"))) - { + Token::Match(tok->tokAt(offset + 2)->link()->next()->link(), ") const|volatile| ) ;|,"))) { if (tok->strAt(offset + 1) == "(") offset++; - else if (Token::simpleMatch(tok->tokAt(offset), "( * (")) - { + else if (Token::simpleMatch(tok->tokAt(offset), "( * (")) { pointers.push_back("*"); offset += 2; } @@ -1374,12 +1187,10 @@ void Tokenizer::simplifyTypedef() argEnd = tok->tokAt(offset)->link()->next()->link(); tok = argEnd->next(); Token *spec = tok; - if (Token::Match(spec, "const|volatile")) - { + if (Token::Match(spec, "const|volatile")) { specStart = spec; specEnd = spec; - while (Token::Match(spec->next(), "const|volatile")) - { + while (Token::Match(spec->next(), "const|volatile")) { specEnd = spec->next(); spec = specEnd; } @@ -1389,18 +1200,14 @@ void Tokenizer::simplifyTypedef() tok = tok->next(); } - else if (Token::Match(tok->tokAt(offset), "( %type% (")) - { + else if (Token::Match(tok->tokAt(offset), "( %type% (")) { function = true; - if (tok->tokAt(offset)->link()->next()) - { + if (tok->tokAt(offset)->link()->next()) { typeName = tok->tokAt(offset + 1); argStart = tok->tokAt(offset + 2); argEnd = tok->tokAt(offset + 2)->link(); tok = tok->tokAt(offset)->link()->next(); - } - else - { + } else { // internal error continue; } @@ -1409,8 +1216,7 @@ void Tokenizer::simplifyTypedef() // pointer to function returning pointer to function else if (Token::Match(tok->tokAt(offset), "( * ( * %type% ) (") && Token::Match(tok->tokAt(offset + 6)->link(), ") ) (") && - Token::Match(tok->tokAt(offset + 6)->link()->tokAt(2)->link(), ") ;|,")) - { + Token::Match(tok->tokAt(offset + 6)->link()->tokAt(2)->link(), ") ;|,")) { functionPtrRetFuncPtr = true; typeName = tok->tokAt(offset + 4); @@ -1426,8 +1232,7 @@ void Tokenizer::simplifyTypedef() // function returning pointer to function else if (Token::Match(tok->tokAt(offset), "( * %type% (") && Token::simpleMatch(tok->tokAt(offset + 3)->link(), ") ) (") && - Token::Match(tok->tokAt(offset + 3)->link()->tokAt(2)->link(), ") ;|,")) - { + Token::Match(tok->tokAt(offset + 3)->link()->tokAt(2)->link(), ") ;|,")) { functionRetFuncPtr = true; typeName = tok->tokAt(offset + 2); @@ -1438,9 +1243,7 @@ void Tokenizer::simplifyTypedef() argFuncRetEnd = argEnd->tokAt(2)->link(); tok = argFuncRetEnd->next(); - } - else if (Token::Match(tok->tokAt(offset), "( * ( %type% ) (")) - { + } else if (Token::Match(tok->tokAt(offset), "( * ( %type% ) (")) { functionRetFuncPtr = true; typeName = tok->tokAt(offset + 3); @@ -1454,8 +1257,7 @@ void Tokenizer::simplifyTypedef() } // pointer/reference to array - else if (Token::Match(tok->tokAt(offset), "( *|& %type% ) [")) - { + else if (Token::Match(tok->tokAt(offset), "( *|& %type% ) [")) { ptrToArray = (tok->tokAt(offset + 1)->str() == "*"); refToArray = (tok->tokAt(offset + 1)->str() == "&"); typeName = tok->tokAt(offset + 2); @@ -1465,8 +1267,7 @@ void Tokenizer::simplifyTypedef() } // pointer to class member - else if (Token::Match(tok->tokAt(offset), "( %type% :: * %type% ) ;")) - { + else if (Token::Match(tok->tokAt(offset), "( %type% :: * %type% ) ;")) { namespaceStart = tok->tokAt(offset + 1); namespaceEnd = tok->tokAt(offset + 2); ptrMember = true; @@ -1475,8 +1276,7 @@ void Tokenizer::simplifyTypedef() } // unhandled typedef, skip it and continue - else - { + else { unsupportedTypedef(typeDef); tok = deleteInvalidTypedef(typeDef); continue; @@ -1485,8 +1285,7 @@ void Tokenizer::simplifyTypedef() bool done = false; bool ok = true; - while (!done) - { + while (!done) { std::string pattern = typeName->str(); int scope = 0; bool inScope = true; @@ -1498,21 +1297,17 @@ void Tokenizer::simplifyTypedef() bool globalScope = false; std::size_t classLevel = spaceInfo.size(); - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { // check for end of scope - if (tok2->str() == "}") - { + if (tok2->str() == "}") { // check for end of member function - if (inMemberFunc) - { + if (inMemberFunc) { memberScope--; if (memberScope == 0) inMemberFunc = false; } - if (classLevel > 0 && tok2 == spaceInfo[classLevel - 1].classEnd) - { + if (classLevel > 0 && tok2 == spaceInfo[classLevel - 1].classEnd) { --classLevel; pattern.clear(); @@ -1520,15 +1315,12 @@ void Tokenizer::simplifyTypedef() pattern += (spaceInfo[i].className + " :: "); pattern += typeName->str(); - } - else - { + } else { scope--; if (scope < 0) inScope = false; - if (exitThisScope) - { + if (exitThisScope) { if (scope < exitScope) exitThisScope = false; } @@ -1540,15 +1332,12 @@ void Tokenizer::simplifyTypedef() else if (tok2->str() == "operator" && tok2->next()->str() == typeName->str() && tok2->strAt(2) == "(" && - Token::Match(tok2->tokAt(2)->link(), ") const| {")) - { + Token::Match(tok2->tokAt(2)->link(), ") const| {")) { // check for qualifier - if (tok2->previous()->str() == "::") - { + if (tok2->previous()->str() == "::") { // check for available and matching class name if (!spaceInfo.empty() && classLevel < spaceInfo.size() && - tok2->strAt(-2) == spaceInfo[classLevel].className) - { + tok2->strAt(-2) == spaceInfo[classLevel].className) { tok2 = tok2->next(); simplifyType = true; } @@ -1556,8 +1345,7 @@ void Tokenizer::simplifyTypedef() } // check for member functions - else if (Token::Match(tok2, ") const| {")) - { + else if (Token::Match(tok2, ") const| {")) { const Token *func = tok2->link()->previous(); /** @todo add support for multi-token operators */ @@ -1565,12 +1353,10 @@ void Tokenizer::simplifyTypedef() func = func->previous(); // check for qualifier - if (func->previous()->str() == "::") - { + if (func->previous()->str() == "::") { // check for available and matching class name if (!spaceInfo.empty() && classLevel < spaceInfo.size() && - func->strAt(-2) == spaceInfo[classLevel].className) - { + func->strAt(-2) == spaceInfo[classLevel].className) { memberScope = 0; inMemberFunc = true; } @@ -1578,12 +1364,10 @@ void Tokenizer::simplifyTypedef() } // check for entering a new namespace - else if (Token::Match(tok2, "namespace %any% {")) - { + else if (Token::Match(tok2, "namespace %any% {")) { if (classLevel < spaceInfo.size() && spaceInfo[classLevel].isNamespace && - spaceInfo[classLevel].className == tok2->next()->str()) - { + spaceInfo[classLevel].className == tok2->next()->str()) { classLevel++; pattern.clear(); for (std::size_t i = classLevel; i < spaceInfo.size(); i++) @@ -1595,8 +1379,7 @@ void Tokenizer::simplifyTypedef() } // check for entering a new scope - else if (tok2->str() == "{") - { + else if (tok2->str() == "{") { // keep track of scopes within member function if (inMemberFunc) memberScope++; @@ -1606,8 +1389,7 @@ void Tokenizer::simplifyTypedef() // check for typedef that can be substituted else if (Token::Match(tok2, pattern.c_str()) || - (inMemberFunc && tok2->str() == typeName->str())) - { + (inMemberFunc && tok2->str() == typeName->str())) { std::string pattern1; // member function class variables don't need qualification @@ -1616,49 +1398,36 @@ void Tokenizer::simplifyTypedef() else pattern1 = pattern; - if (pattern1.find("::") != std::string::npos) // has a "something ::" - { - if (Token::simpleMatch(tok2->previous(), "::")) - { + if (pattern1.find("::") != std::string::npos) { // has a "something ::" + if (Token::simpleMatch(tok2->previous(), "::")) { tok2->previous()->previous()->deleteNext(); globalScope = true; } - for (std::size_t i = classLevel; i < spaceInfo.size(); i++) - { + for (std::size_t i = classLevel; i < spaceInfo.size(); i++) { tok2->deleteNext(); tok2->deleteNext(); } simplifyType = true; - } - else if ((inScope && !exitThisScope) || inMemberFunc) - { - if (Token::simpleMatch(tok2->previous(), "::")) - { + } else if ((inScope && !exitThisScope) || inMemberFunc) { + if (Token::simpleMatch(tok2->previous(), "::")) { // Don't replace this typename if it's preceded by "::" unless it's a namespace - if (!spaceInfo.empty() && (tok2->tokAt(-2)->str() == spaceInfo[0].className) && spaceInfo[0].isNamespace) - { + if (!spaceInfo.empty() && (tok2->tokAt(-2)->str() == spaceInfo[0].className) && spaceInfo[0].isNamespace) { tok2 = tok2->tokAt(-3); tok2->deleteNext(); tok2->deleteNext(); tok2 = tok2->next(); simplifyType = true; } - } - else if (Token::Match(tok2->previous(), "case %type% :")) - { + } else if (Token::Match(tok2->previous(), "case %type% :")) { tok2 = tok2->next(); - } - else if (duplicateTypedef(&tok2, typeName, typeDef, undefinedStruct)) - { + } else if (duplicateTypedef(&tok2, typeName, typeDef, undefinedStruct)) { exitScope = scope; // skip to end of scope if not already there - if (tok2->str() != "}") - { + if (tok2->str() != "}") { int level = 0; - while (tok2->next() && (tok2->next()->str() != "}" || level)) - { + while (tok2->next() && (tok2->next()->str() != "}" || level)) { if (tok2->next()->str() == "{") level++; else if (tok2->next()->str() == "}") @@ -1667,20 +1436,16 @@ void Tokenizer::simplifyTypedef() tok2 = tok2->next(); } } - } - else if (tok2->previous()->str() != ".") - { + } else if (tok2->previous()->str() != ".") { simplifyType = true; } } } - if (simplifyType) - { + if (simplifyType) { // can't simplify 'operator functionPtr ()' and 'functionPtr operator ... ()' if (functionPtr && (tok2->previous()->str() == "operator" || - tok2->next()->str() == "operator")) - { + tok2->next()->str() == "operator")) { simplifyType = false; tok2 = tok2->next(); break; @@ -1723,8 +1488,7 @@ void Tokenizer::simplifyTypedef() // skip over class or struct in derived class declaration bool structRemoved = false; - if (isDerived && Token::Match(typeStart, "class|struct")) - { + if (isDerived && Token::Match(typeStart, "class|struct")) { if (typeStart->str() == "struct") structRemoved = true; typeStart = typeStart->next(); @@ -1734,19 +1498,16 @@ void Tokenizer::simplifyTypedef() tok2->str(typeStart->str()); // restore qualification if it was removed - if (typeStart->str() == "struct" || structRemoved) - { + if (typeStart->str() == "struct" || structRemoved) { if (structRemoved) tok2 = tok2->previous(); - if (globalScope) - { + if (globalScope) { tok2->insertToken("::"); tok2 = tok2->next(); } - for (std::size_t i = classLevel; i < spaceInfo.size(); i++) - { + for (std::size_t i = classLevel; i < spaceInfo.size(); i++) { tok2->insertToken(spaceInfo[i].className); tok2 = tok2->next(); tok2->insertToken("::"); @@ -1757,18 +1518,15 @@ void Tokenizer::simplifyTypedef() // add remainder of type tok2 = copyTokens(tok2, typeStart->next(), typeEnd); - if (!pointers.empty()) - { + if (!pointers.empty()) { std::list::const_iterator iter; - for (iter = pointers.begin(); iter != pointers.end(); ++iter) - { + for (iter = pointers.begin(); iter != pointers.end(); ++iter) { tok2->insertToken(*iter); tok2 = tok2->next(); } } - if (funcStart && funcEnd) - { + if (funcStart && funcEnd) { tok2->insertToken("("); tok2 = tok2->next(); Token *tok3 = tok2; @@ -1783,13 +1541,11 @@ void Tokenizer::simplifyTypedef() tok2 = copyTokens(tok2, argStart, argEnd); - if (specStart) - { + if (specStart) { Token *spec = specStart; tok2->insertToken(spec->str()); tok2 = tok2->next(); - while (spec != specEnd) - { + while (spec != specEnd) { spec = spec->next(); tok2->insertToken(spec->str()); tok2 = tok2->next(); @@ -1797,25 +1553,21 @@ void Tokenizer::simplifyTypedef() } } - else if (functionPtr || functionRef || function) - { + else if (functionPtr || functionRef || function) { // don't add parenthesis around function names because it // confuses other simplifications bool needParen = true; if (!inTemplate && function && tok2->next() && tok2->next()->str() != "*") needParen = false; - if (needParen) - { + if (needParen) { tok2->insertToken("("); tok2 = tok2->next(); } Token *tok3 = tok2; - if (namespaceStart) - { + if (namespaceStart) { const Token *tok4 = namespaceStart; - while (tok4 != namespaceEnd) - { + while (tok4 != namespaceEnd) { tok2->insertToken(tok4->str()); tok2 = tok2->next(); tok4 = tok4->next(); @@ -1823,13 +1575,10 @@ void Tokenizer::simplifyTypedef() tok2->insertToken(namespaceEnd->str()); tok2 = tok2->next(); } - if (functionPtr) - { + if (functionPtr) { tok2->insertToken("*"); tok2 = tok2->next(); - } - else if (functionRef) - { + } else if (functionRef) { tok2->insertToken("&"); tok2 = tok2->next(); } @@ -1837,8 +1586,7 @@ void Tokenizer::simplifyTypedef() if (!inCast) tok2 = processFunc(tok2, inOperator); - if (needParen) - { + if (needParen) { tok2->insertToken(")"); tok2 = tok2->next(); Token::createMutualLinks(tok2, tok3); @@ -1849,21 +1597,17 @@ void Tokenizer::simplifyTypedef() if (inTemplate) tok2 = tok2->next(); - if (specStart) - { + if (specStart) { Token *spec = specStart; tok2->insertToken(spec->str()); tok2 = tok2->next(); - while (spec != specEnd) - { + while (spec != specEnd) { spec = spec->next(); tok2->insertToken(spec->str()); tok2 = tok2->next(); } } - } - else if (functionRetFuncPtr || functionPtrRetFuncPtr) - { + } else if (functionRetFuncPtr || functionPtrRetFuncPtr) { tok2->insertToken("("); tok2 = tok2->next(); Token *tok3 = tok2; @@ -1871,8 +1615,7 @@ void Tokenizer::simplifyTypedef() tok2 = tok2->next(); Token * tok4 = 0; - if (functionPtrRetFuncPtr) - { + if (functionPtrRetFuncPtr) { tok2->insertToken("("); tok2 = tok2->next(); tok4 = tok2; @@ -1881,14 +1624,12 @@ void Tokenizer::simplifyTypedef() } // skip over variable name if there - if (!inCast) - { + if (!inCast) { if (tok2->next()->str() != ")") tok2 = tok2->next(); } - if (tok4 && functionPtrRetFuncPtr) - { + if (tok4 && functionPtrRetFuncPtr) { tok2->insertToken(")"); tok2 = tok2->next(); Token::createMutualLinks(tok2, tok4); @@ -1901,9 +1642,7 @@ void Tokenizer::simplifyTypedef() Token::createMutualLinks(tok2, tok3); tok2 = copyTokens(tok2, argFuncRetStart, argFuncRetEnd); - } - else if (ptrToArray || refToArray) - { + } else if (ptrToArray || refToArray) { tok2->insertToken("("); tok2 = tok2->next(); Token *tok3 = tok2; @@ -1915,8 +1654,7 @@ void Tokenizer::simplifyTypedef() tok2 = tok2->next(); // skip over name - if (tok2->next()->str() != ")") - { + if (tok2->next()->str() != ")") { if (tok2->next()->str() != "(") tok2 = tok2->next(); @@ -1927,32 +1665,24 @@ void Tokenizer::simplifyTypedef() // check for array if (tok2->next()->str() == "[") tok2 = tok2->next()->link(); - } - else - { + } else { // syntax error } tok2->insertToken(")"); Token::createMutualLinks(tok2->next(), tok3); - } - else if (ptrMember) - { - if (Token::simpleMatch(tok2, "* (")) - { + } else if (ptrMember) { + if (Token::simpleMatch(tok2, "* (")) { tok2->insertToken("*"); tok2 = tok2->next(); - } - else - { + } else { tok2->insertToken("("); tok2 = tok2->next(); Token *tok3 = tok2; const Token *tok4 = namespaceStart; - while (tok4 != namespaceEnd) - { + while (tok4 != namespaceEnd) { tok2->insertToken(tok4->str()); tok2 = tok2->next(); tok4 = tok4->next(); @@ -1970,23 +1700,16 @@ void Tokenizer::simplifyTypedef() tok2 = tok2->next(); Token::createMutualLinks(tok2, tok3); } - } - else if (typeOf) - { + } else if (typeOf) { tok2 = copyTokens(tok2, argStart, argEnd); - } - else if (tok2->tokAt(2) && tok2->tokAt(2)->str() == "[") - { + } else if (tok2->tokAt(2) && tok2->tokAt(2)->str() == "[") { while (tok2->tokAt(2) && tok2->tokAt(2)->str() == "[") tok2 = tok2->tokAt(2)->link()->previous(); } - if (arrayStart && arrayEnd) - { - do - { - if (!tok2->next()) - { + if (arrayStart && arrayEnd) { + do { + if (!tok2->next()) { syntaxError(tok2); return; // can't recover so quit } @@ -1995,8 +1718,7 @@ void Tokenizer::simplifyTypedef() tok2 = tok2->next(); // reference to array? - if (tok2->str() == "&") - { + if (tok2->str() == "&") { tok2 = tok2->previous(); tok2->insertToken("("); Token *tok3 = tok2->next(); @@ -2015,15 +1737,13 @@ void Tokenizer::simplifyTypedef() tok2 = copyTokens(tok2, arrayStart, arrayEnd); tok2 = tok2->next(); - if (tok2->str() == "=") - { + if (tok2->str() == "=") { if (tok2->next()->str() == "{") tok2 = tok2->next()->link()->next(); else if (tok2->next()->str().at(0) == '\"') tok2 = tok2->next()->next(); } - } - while (Token::Match(tok2, ", %var% ;|'|=|,")); + } while (Token::Match(tok2, ", %var% ;|'|=|,")); } simplifyType = false; @@ -2032,8 +1752,7 @@ void Tokenizer::simplifyTypedef() if (tok->str() == ";") done = true; - else if (tok->str() == ",") - { + else if (tok->str() == ",") { arrayStart = 0; arrayEnd = 0; offset = 1; @@ -2042,17 +1761,14 @@ void Tokenizer::simplifyTypedef() while (Token::Match(tok->tokAt(offset), "*|&")) pointers.push_back(tok->tokAt(offset++)->str()); - if (Token::Match(tok->tokAt(offset), "%type%")) - { + if (Token::Match(tok->tokAt(offset), "%type%")) { typeName = tok->tokAt(offset++); - if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") - { + if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") { arrayStart = tok->tokAt(offset); bool atEnd = false; - while (!atEnd) - { + while (!atEnd) { while (tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) offset++; @@ -2071,41 +1787,32 @@ void Tokenizer::simplifyTypedef() if (Token::Match(tok->tokAt(offset), ";|,")) tok = tok->tokAt(offset); - else - { + else { // we encountered a typedef we don't support yet so just continue done = true; ok = false; } - } - else - { + } else { // we encountered a typedef we don't support yet so just continue done = true; ok = false; } - } - else - { + } else { // something is really wrong (internal error) done = true; ok = false; } } - if (ok) - { + if (ok) { // remove typedef but leave ; while (typeDef->next() && typeDef->next() != tok) typeDef->deleteNext(); - if (typeDef != _tokens) - { + if (typeDef != _tokens) { tok = typeDef->previous(); tok->deleteNext(); - } - else - { + } else { _tokens->deleteThis(); tok = _tokens; } @@ -2115,19 +1822,15 @@ void Tokenizer::simplifyTypedef() void Tokenizer::simplifyMulAnd(void) { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] *")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] *")) { //fix Ticket #2784 - if (Token::Match(tok->next(), "* & %any% =")) - { + if (Token::Match(tok->next(), "* & %any% =")) { tok->deleteNext(); //del * tok->deleteNext(); //del & continue; } - if (Token::Match(tok->next(), "* ( & %any% ) =")) - { + if (Token::Match(tok->next(), "* ( & %any% ) =")) { tok->deleteNext(); //del * tok->deleteNext(); //del ( tok->deleteNext(); //del & @@ -2166,17 +1869,14 @@ bool Tokenizer::tokenize(std::istream &code, createTokens(code); // replace __LINE__ macro with line number - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "__LINE__") tok->str(MathLib::toString(tok->linenr())); } // token concatenation - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "%var%|%num% ## %var%|%num%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "%var%|%num% ## %var%|%num%")) { tok->str(tok->str() + tok->strAt(2)); tok->deleteNext(); tok->deleteNext(); @@ -2189,12 +1889,9 @@ bool Tokenizer::tokenize(std::istream &code, simplifyMulAnd(); // Convert C# code - if (_files[0].find(".cs")) - { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] %type% [ ] %var% [=;]")) - { + if (_files[0].find(".cs")) { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] %type% [ ] %var% [=;]")) { tok = tok->next()->next(); tok->str("*"); tok->deleteNext(); @@ -2203,21 +1900,17 @@ bool Tokenizer::tokenize(std::istream &code, } // if MACRO - for (const Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "if|for|while %var% (")) - { + for (const Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "if|for|while %var% (")) { syntaxError(tok); return false; } } // Simplify JAVA/C# code - if (isJavaOrCSharp()) - { + if (isJavaOrCSharp()) { const bool isJava(_files[0].find(".java") != std::string::npos); - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (isJava && Token::Match(tok, ") throws %var% {")) Token::eraseTokens(tok, tok->tokAt(3)); else if (tok->str() == "private") @@ -2230,35 +1923,28 @@ bool Tokenizer::tokenize(std::istream &code, } // Replace NULL with 0.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "NULL" || tok->str() == "__null" || - tok->str() == "'\\0'" || tok->str() == "'\\x0'") - { + tok->str() == "'\\0'" || tok->str() == "'\\x0'") { tok->str("0"); - } - else if (tok->isNumber() && - MathLib::isInt(tok->str()) && - MathLib::toLongNumber(tok->str()) == 0) - { + } else if (tok->isNumber() && + MathLib::isInt(tok->str()) && + MathLib::toLongNumber(tok->str()) == 0) { tok->str("0"); } } // replace inline SQL with "asm()" (Oracle PRO*C). Ticket: #1959 - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "EXEC SQL")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "EXEC SQL")) { // delete all tokens until ";" const Token *end = tok; while (end && end->str() != ";") end = end->next(); Token::eraseTokens(tok, end); - if (tok) - { + if (tok) { // insert "asm ( ) ;" tok->str("asm"); tok->insertToken("("); @@ -2268,18 +1954,15 @@ bool Tokenizer::tokenize(std::istream &code, } } - if (!createLinks()) - { + if (!createLinks()) { // Source has syntax errors, can't proceed return false; } // check for simple syntax errors.. - for (const Token *tok = _tokens; tok; tok = tok->next()) - { + for (const Token *tok = _tokens; tok; tok = tok->next()) { if (Token::simpleMatch(tok, "> struct {") && - Token::simpleMatch(tok->tokAt(2)->link(), "} ;")) - { + Token::simpleMatch(tok->tokAt(2)->link(), "} ;")) { syntaxError(tok); deallocateTokens(); return false; @@ -2298,31 +1981,25 @@ bool Tokenizer::tokenize(std::istream &code, return false; // Combine "- %num%" .. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "?|:|,|(|[|=|return|case|%op% - %num%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "?|:|,|(|[|=|return|case|%op% - %num%")) { tok->next()->str("-" + tok->strAt(2)); tok->next()->deleteNext(); } } // Combine tokens.. - for (Token *tok = _tokens; tok && tok->next(); tok = tok->next()) - { + for (Token *tok = _tokens; tok && tok->next(); tok = tok->next()) { const char c1 = tok->str()[0]; - if (tok->str().length() == 1 && tok->next()->str().length() == 1) - { + if (tok->str().length() == 1 && tok->next()->str().length() == 1) { const char c2 = tok->next()->str()[0]; // combine equal tokens.. - if (c1 == c2 && (c1 == '<' || c1 == '|' || c1 == ':')) - { + if (c1 == c2 && (c1 == '<' || c1 == '|' || c1 == ':')) { tok->str(tok->str() + c2); tok->deleteNext(); - if (c1 == '<' && Token::simpleMatch(tok->next(), "=")) - { + if (c1 == '<' && Token::simpleMatch(tok->next(), "=")) { tok->str("<<="); tok->deleteNext(); } @@ -2330,32 +2007,27 @@ bool Tokenizer::tokenize(std::istream &code, } // combine +-*/ and = - else if (c2 == '=' && (strchr("+-*/%&|^=!<>", c1))) - { + else if (c2 == '=' && (strchr("+-*/%&|^=!<>", c1))) { tok->str(tok->str() + c2); tok->deleteNext(); continue; } // replace "->" with "." - else if (c1 == '-' && c2 == '>') - { + else if (c1 == '-' && c2 == '>') { tok->str("."); tok->deleteNext(); continue; } } - else if (tok->str() == ">>" && tok->next()->str() == "=") - { + else if (tok->str() == ">>" && tok->next()->str() == "=") { tok->str(">>="); tok->deleteNext(); } - else if ((c1 == 'p' || c1 == '_') && tok->next()->str() == ":" && tok->strAt(2) != ":") - { - if (tok->str() == "private" || tok->str() == "protected" || tok->str() == "public" || tok->str() == "__published") - { + else if ((c1 == 'p' || c1 == '_') && tok->next()->str() == ":" && tok->strAt(2) != ":") { + if (tok->str() == "private" || tok->str() == "protected" || tok->str() == "public" || tok->str() == "__published") { tok->str(tok->str() + ":"); tok->deleteNext(); continue; @@ -2367,13 +2039,10 @@ bool Tokenizer::tokenize(std::istream &code, simplifyCompoundAssignment(); // check for more complicated syntax errors when using templates.. - if (!preprocessorCondition) - { - for (const Token *tok = _tokens; tok; tok = tok->next()) - { + if (!preprocessorCondition) { + for (const Token *tok = _tokens; tok; tok = tok->next()) { // skip executing scopes.. - if (Token::Match(tok, ") const| {") || Token::simpleMatch(tok, ", {")) - { + if (Token::Match(tok, ") const| {") || Token::simpleMatch(tok, ", {")) { while (tok->str() != "{") tok = tok->next(); tok = tok->link(); @@ -2382,27 +2051,23 @@ bool Tokenizer::tokenize(std::istream &code, } // skip executing scopes (ticket #1984).. - if (Token::simpleMatch(tok, "; {")) - { + if (Token::simpleMatch(tok, "; {")) { tok = tok->next()->link(); if (!tok) break; } // skip executing scopes (ticket #3183).. - if (Token::simpleMatch(tok, "( {")) - { + if (Token::simpleMatch(tok, "( {")) { tok = tok->next()->link(); if (!tok) break; } // skip executing scopes (ticket #1985).. - if (Token::simpleMatch(tok, "try {")) - { + if (Token::simpleMatch(tok, "try {")) { tok = tok->next()->link(); - while (Token::simpleMatch(tok, "} catch (")) - { + while (Token::simpleMatch(tok, "} catch (")) { tok = tok->tokAt(2)->link(); if (Token::simpleMatch(tok, ") {")) tok = tok->next()->link(); @@ -2426,19 +2091,16 @@ bool Tokenizer::tokenize(std::istream &code, break; // template variable or type.. - if (Token::Match(tok, "%type% <")) - { + if (Token::Match(tok, "%type% <")) { // these are used types.. std::set usedtypes; // parse this statement and see if the '<' and '>' are matching unsigned int level = 0; - for (const Token *tok2 = tok; tok2 && !Token::Match(tok2, "[;{}]"); tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2 && !Token::Match(tok2, "[;{}]"); tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); - else if (tok2->str() == "<") - { + else if (tok2->str() == "<") { bool inclevel = false; if (Token::simpleMatch(tok2->previous(), "operator <")) ; @@ -2452,8 +2114,7 @@ bool Tokenizer::tokenize(std::istream &code, inclevel = true; else if (Token::Match(tok2, "< %type%") && usedtypes.find(tok2->strAt(1)) != usedtypes.end()) inclevel = true; - else if (Token::Match(tok2, "< %type%")) - { + else if (Token::Match(tok2, "< %type%")) { // is the next token a type and not a variable/constant? // assume it's a type if there comes another "<" const Token *tok3 = tok2->next(); @@ -2463,28 +2124,22 @@ bool Tokenizer::tokenize(std::istream &code, inclevel = true; } - if (inclevel) - { + if (inclevel) { ++level; if (Token::Match(tok2->tokAt(-2), "<|, %type% <")) usedtypes.insert(tok2->strAt(-1)); } - } - else if (tok2->str() == ">") - { + } else if (tok2->str() == ">") { if (level > 0) --level; - } - else if (tok2->str() == ">>") - { + } else if (tok2->str() == ">>") { if (level > 0) --level; if (level > 0) --level; } } - if (level > 0) - { + if (level > 0) { syntaxError(tok); deallocateTokens(); return false; @@ -2496,23 +2151,17 @@ bool Tokenizer::tokenize(std::istream &code, // Remove "= default|delete" inside class|struct definitions // Todo: Remove it if it is used "externally" too. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "struct|class %var% :|{")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "struct|class %var% :|{")) { unsigned int indentlevel = 0; - for (Token * tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { + for (Token * tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; - } - else if (indentlevel == 1 && Token::Match(tok2, ") = delete|default ;")) - { + } else if (indentlevel == 1 && Token::Match(tok2, ") = delete|default ;")) { Token * const end = tok2->tokAt(4); tok2 = tok2->link()->previous(); @@ -2574,20 +2223,14 @@ bool Tokenizer::tokenize(std::istream &code, simplifyBuiltinExpect(); // #2449: syntax error: enum with typedef in it - for (const Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "enum %var% {")) - { - for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "typedef") - { + for (const Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "enum %var% {")) { + for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) { + if (tok2->str() == "typedef") { syntaxError(tok2); deallocateTokens(); return false; - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { break; } } @@ -2595,8 +2238,7 @@ bool Tokenizer::tokenize(std::istream &code, } // convert Microsoft DEBUG_NEW macro to new - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "DEBUG_NEW") tok->str("new"); } @@ -2609,8 +2251,7 @@ bool Tokenizer::tokenize(std::istream &code, // to reproduce bad typedef, download upx-ucl from: // http://packages.debian.org/sid/upx-ucl // analyse the file src/stub/src/i386-linux.elf.interp-main.c - if (!validate()) - { + if (!validate()) { // Source has syntax errors, can't proceed return false; } @@ -2622,12 +2263,10 @@ bool Tokenizer::tokenize(std::istream &code, simplifyAsm(); // When the assembly code has been cleaned up, no @ is allowed - for (const Token *tok = _tokens; tok; tok = tok->next()) - { + for (const Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "(") tok = tok->link(); - else if (tok->str()[0] == '@') - { + else if (tok->str()[0] == '@') { deallocateTokens(); return false; } @@ -2713,8 +2352,7 @@ bool Tokenizer::tokenize(std::istream &code, // Split up variable declarations. simplifyVarDecl(); - if (!preprocessorCondition) - { + if (!preprocessorCondition) { setVarId(); // Change initialisation of variable to assignment @@ -2725,34 +2363,23 @@ bool Tokenizer::tokenize(std::istream &code, simplifyMathFunctions(); // Convert + + into + and + - into - - for (Token *tok = _tokens; tok; tok = tok->next()) - { - while (tok->next()) - { - if (tok->str() == "+") - { - if (tok->next()->str() == "+") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + while (tok->next()) { + if (tok->str() == "+") { + if (tok->next()->str() == "+") { tok->deleteNext(); continue; - } - else if (tok->next()->str() == "-") - { + } else if (tok->next()->str() == "-") { tok->str("-"); tok->deleteNext(); continue; } - } - else if (tok->str() == "-") - { - if (tok->next()->str() == "-") - { + } else if (tok->str() == "-") { + if (tok->next()->str() == "-") { tok->str("+"); tok->deleteNext(); continue; - } - else if (tok->next()->str() == "+") - { + } else if (tok->next()->str() == "+") { tok->deleteNext(); continue; } @@ -2763,10 +2390,8 @@ bool Tokenizer::tokenize(std::istream &code, } // 0[a] -> a[0] - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "%num% [ %var% ]")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "%num% [ %var% ]")) { const std::string temp = tok->str(); tok->str(tok->tokAt(2)->str()); tok->tokAt(2)->str(temp); @@ -2785,20 +2410,16 @@ bool Tokenizer::tokenize(std::istream &code, void Tokenizer::arraySize() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "%var% [ ] = { %str% }")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "%var% [ ] = { %str% }")) { tok->tokAt(4)->deleteThis(); tok->tokAt(5)->deleteThis(); } - if (Token::Match(tok, "%var% [ ] = {")) - { + if (Token::Match(tok, "%var% [ ] = {")) { unsigned int sz = 1; const Token *tok2 = tok->tokAt(5); - while (Token::Match(tok2, "%any% ,")) - { + while (Token::Match(tok2, "%any% ,")) { if (tok2->isName()) break; sz++; @@ -2809,8 +2430,7 @@ void Tokenizer::arraySize() tok->next()->insertToken(MathLib::toString(sz)); } - else if (Token::Match(tok, "%var% [ ] = %str% ;")) - { + else if (Token::Match(tok, "%var% [ ] = %str% ;")) { std::size_t sz = tok->strAt(4).length() - 1; tok->next()->insertToken(MathLib::toString((unsigned int)sz)); } @@ -2821,19 +2441,15 @@ void Tokenizer::arraySize() void Tokenizer::labels() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, ") const| {")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, ") const| {")) { // Simplify labels in the executable scope.. unsigned int indentlevel = 0; unsigned int indentroundbraces = 0; - while (0 != (tok = tok->next())) - { + while (0 != (tok = tok->next())) { if (tok->str() == "{") ++indentlevel; - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel <= 1) break; --indentlevel; @@ -2841,8 +2457,7 @@ void Tokenizer::labels() if (tok->str() == "(") ++indentroundbraces; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (!indentroundbraces) break; --indentroundbraces; @@ -2850,16 +2465,12 @@ void Tokenizer::labels() // simplify label.. except for unhandled macro if (!indentroundbraces && Token::Match(tok, "[;{}] %var% :") && !Token::Match(tok->next(), "public|protected|private") - && tok->tokAt(3)->str() != ";") - { - for (Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) - { - if (Token::Match(tok2, "%var%")) - { + && tok->tokAt(3)->str() != ";") { + for (Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) { + if (Token::Match(tok2, "%var%")) { tok->tokAt(2)->insertToken(";"); break; - } - else if (!Token::Match(tok2, "[(*&{]")) + } else if (!Token::Match(tok2, "[(*&{]")) break; } } @@ -2885,8 +2496,7 @@ static unsigned int templateParameters(const Token *tok) return 0; tok = tok->next(); - while (tok) - { + while (tok) { ++numberOfParameters; // skip std:: @@ -2920,29 +2530,24 @@ static unsigned int templateParameters(const Token *tok) */ static void removeTemplates(Token *tok) { - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { if (! Token::simpleMatch(tok, "template <")) continue; - for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : 0; Token::eraseTokens(tok, tok2); tok->str(";"); break; } - if (tok2->str() == "(") - { + if (tok2->str() == "(") { tok2 = tok2->link(); if (!tok2) break; } - if (tok2->str() == ";") - { + if (tok2->str() == ";") { Token::eraseTokens(tok, tok2->next()); tok->str(";"); break; @@ -2956,8 +2561,7 @@ std::set Tokenizer::simplifyTemplatesExpandSpecialized() std::set expandedtemplates; // Locate specialized templates.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "template") continue; if (!Token::simpleMatch(tok->next(), "< >")) @@ -2980,8 +2584,7 @@ std::set Tokenizer::simplifyTemplatesExpandSpecialized() { std::ostringstream ostr; const Token *tok3 = tok2; - for (tok3 = tok2; tok3 && tok3->str() != ">"; tok3 = tok3->next()) - { + for (tok3 = tok2; tok3 && tok3->str() != ">"; tok3 = tok3->next()) { if (tok3 != tok2) ostr << " "; ostr << tok3->str(); @@ -3010,8 +2613,7 @@ std::set Tokenizer::simplifyTemplatesExpandSpecialized() tok->deleteThis(); // Use this special template in the code.. - while (0 != (tok2 = const_cast(Token::findmatch(tok2, pattern.c_str())))) - { + while (0 != (tok2 = const_cast(Token::findmatch(tok2, pattern.c_str())))) { Token::eraseTokens(tok2, Token::findmatch(tok2, "(")); tok2->str(name); } @@ -3023,23 +2625,19 @@ std::set Tokenizer::simplifyTemplatesExpandSpecialized() std::list Tokenizer::simplifyTemplatesGetTemplateDeclarations() { std::list templates; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "template <")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "template <")) { // set member variable, the code has templates. // this info is used by checks _codeWithTemplates = true; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { // Just a declaration => ignore this if (tok2->str() == ";") break; // Implementation => add to "templates" - if (tok2->str() == "{") - { + if (tok2->str() == "{") { templates.push_back(tok); break; } @@ -3053,29 +2651,24 @@ std::list Tokenizer::simplifyTemplatesGetTemplateInstantiations() { std::list used; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // template definition.. skip it - if (Token::simpleMatch(tok, "template <")) - { + if (Token::simpleMatch(tok, "template <")) { unsigned int level = 0; // Goto the end of the template definition - for (; tok; tok = tok->next()) - { + for (; tok; tok = tok->next()) { // skip '<' .. '>' if (tok->str() == "<") ++level; - else if (tok->str() == ">") - { + else if (tok->str() == ">") { if (level <= 1) break; --level; } // skip inner '(' .. ')' and '{' .. '}' - else if (tok->str() == "{" || tok->str() == "(") - { + else if (tok->str() == "{" || tok->str() == "(") { // skip inner tokens. goto ')' or '}' tok = tok->link(); @@ -3089,17 +2682,14 @@ std::list Tokenizer::simplifyTemplatesGetTemplateInstantiations() } // the end ';' for the template definition - else if (tok->str() == ";") - { + else if (tok->str() == ";") { break; } } if (!tok) break; - } - else if (Token::Match(tok->previous(), "[({};=] %var% <") || - Token::Match(tok->tokAt(-2), "[,:] private|protected|public %var% <")) - { + } else if (Token::Match(tok->previous(), "[({};=] %var% <") || + Token::Match(tok->tokAt(-2), "[,:] private|protected|public %var% <")) { if (templateParameters(tok->next())) used.push_back(tok); } @@ -3112,8 +2702,7 @@ std::list Tokenizer::simplifyTemplatesGetTemplateInstantiations() void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::list &templates, const std::list &instantiations) { - for (std::list::const_iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) - { + for (std::list::const_iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) { // template parameters with default value has syntax such as: // x = y // this list will contain all the '=' tokens for such arguments @@ -3126,11 +2715,9 @@ void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::listnext()) - { + for (Token *tok = *iter1; tok; tok = tok->next()) { // end of template parameters? - if (tok->str() == ">") - { + if (tok->str() == ">") { if (Token::Match(tok, "> class|struct %var%")) classname = tok->strAt(2); break; @@ -3148,8 +2735,7 @@ void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::list::const_iterator iter2 = instantiations.begin(); iter2 != instantiations.end(); ++iter2) - { + for (std::list::const_iterator iter2 = instantiations.begin(); iter2 != instantiations.end(); ++iter2) { Token *tok = *iter2; if (!Token::Match(tok, (classname + " < %any%").c_str())) @@ -3157,8 +2743,7 @@ void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::listtokAt(3); tok; tok = tok->tokAt(2)) - { + for (tok = tok->tokAt(3); tok; tok = tok->tokAt(2)) { if (tok->str() == ">") break; @@ -3168,26 +2753,22 @@ void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::liststr() == ">") - { + if (tok && tok->str() == ">") { tok = tok->previous(); std::list::const_iterator it = eq.begin(); for (std::size_t i = (templatepar - eq.size()); it != eq.end() && i < usedpar; ++i) ++it; - while (it != eq.end()) - { + while (it != eq.end()) { tok->insertToken(","); tok = tok->next(); const Token *from = (*it)->next(); std::stack links; - while (from && (!links.empty() || (from->str() != "," && from->str() != ">"))) - { + while (from && (!links.empty() || (from->str() != "," && from->str() != ">"))) { tok->insertToken(from->str()); tok = tok->next(); if (Token::Match(tok, "(|[")) links.push(tok); - else if (!links.empty() && Token::Match(tok, ")|]")) - { + else if (!links.empty() && Token::Match(tok, ")|]")) { Token::createMutualLinks(links.top(), tok); links.pop(); } @@ -3198,8 +2779,7 @@ void Tokenizer::simplifyTemplatesUseDefaultArgumentValues(const std::list::iterator it = eq.begin(); it != eq.end(); ++it) - { + for (std::list::iterator it = eq.begin(); it != eq.end(); ++it) { (*it)->deleteThis(); (*it)->deleteThis(); } @@ -3222,8 +2802,7 @@ static bool simplifyTemplatesInstantiateMatch(const Token *instance, const std:: if (numberOfArguments != templateParameters(instance->next())) return false; - if (patternAfter) - { + if (patternAfter) { const Token *tok = Token::findmatch(instance, ">"); if (!tok || !Token::Match(tok->next(), patternAfter)) return false; @@ -3242,8 +2821,7 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, bool done = false; std::vector type; - for (tok = tok->tokAt(2); tok && tok->str() != ">"; tok = tok->next()) - { + for (tok = tok->tokAt(2); tok && tok->str() != ">"; tok = tok->next()) { if (Token::Match(tok, "%var% ,|>")) type.push_back(tok); } @@ -3260,11 +2838,9 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, namepos = 2; else if (Token::Match(tok, "> %type% %type% *|&| %type% (")) namepos = 3; - else - { + else { // debug message that we bail out.. - if (_settings->debugwarnings) - { + if (_settings->debugwarnings) { std::list locationList; ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); @@ -3296,16 +2872,13 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, std::string::size_type sz1 = used.size(); unsigned int recursiveCount = 0; - for (std::list::const_iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) - { + for (std::list::const_iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) { // If the size of "used" has changed, simplify calculations - if (sz1 != used.size()) - { + if (sz1 != used.size()) { sz1 = used.size(); simplifyCalculations(); recursiveCount++; - if (recursiveCount > 100) - { + if (recursiveCount > 100) { // bail out.. break; } @@ -3317,8 +2890,7 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, // #2648 - simple fix for sizeof used as template parameter // TODO: this is a bit hardcoded. make a bit more generic - if (Token::Match(tok2, "%var% < sizeof ( %type% ) >") && tok2->tokAt(4)->isStandardType()) - { + if (Token::Match(tok2, "%var% < sizeof ( %type% ) >") && tok2->tokAt(4)->isStandardType()) { Token * const tok3 = tok2->next(); const unsigned int sz = sizeOfType(tok3->tokAt(3)); Token::eraseTokens(tok3, tok3->tokAt(5)); @@ -3333,17 +2905,14 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, std::vector types2; std::string s; std::string s1(name + " < "); - for (const Token *tok3 = tok2->tokAt(2); tok3 && tok3->str() != ">"; tok3 = tok3->next()) - { + for (const Token *tok3 = tok2->tokAt(2); tok3 && tok3->str() != ">"; tok3 = tok3->next()) { // #2648 - unhandled parenthesis => bail out // #2721 - unhandled [ => bail out - if (tok3->str() == "(" || tok3->str() == "[") - { + if (tok3->str() == "(" || tok3->str() == "[") { s.clear(); break; } - if (!tok3->next()) - { + if (!tok3->next()) { s.clear(); break; } @@ -3363,10 +2932,8 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, s1 += ">"; const std::string type2(s); - if (type2.empty() || type.size() != types2.size()) - { - if (_settings->debugwarnings) - { + if (type2.empty() || type.size() != types2.size()) { + if (_settings->debugwarnings) { std::list locationList; ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok2->linenr(); @@ -3389,14 +2956,12 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, // New classname/funcname.. const std::string name2(name + "<" + type2 + ">"); - if (expandedtemplates.find(name2) == expandedtemplates.end()) - { + if (expandedtemplates.find(name2) == expandedtemplates.end()) { expandedtemplates.insert(name2); // Copy template.. int _indentlevel = 0; int _parlevel = 0; - for (const Token *tok3 = _tokens; tok3; tok3 = tok3->next()) - { + for (const Token *tok3 = _tokens; tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++_indentlevel; else if (tok3->str() == "}") @@ -3407,16 +2972,14 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, --_parlevel; // Start of template.. - if (tok3 == tok) - { + if (tok3 == tok) { tok3 = tok3->next(); } // member function implemented outside class definition else if (_indentlevel == 0 && _parlevel == 0 && - simplifyTemplatesInstantiateMatch(tok3, name, type.size(), ":: ~| %var% (")) - { + simplifyTemplatesInstantiateMatch(tok3, name, type.size(), ":: ~| %var% (")) { addtoken(name2.c_str(), tok3->linenr(), tok3->fileIndex()); while (tok3->str() != "::") tok3 = tok3->next(); @@ -3431,15 +2994,12 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, std::stack brackets; // holds "(" tokens std::stack brackets2; // holds "[" tokens - for (; tok3; tok3 = tok3->next()) - { + for (; tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel; - else if (tok3->str() == "}") - { - if (indentlevel <= 1 && brackets.empty() && brackets2.empty()) - { + else if (tok3->str() == "}") { + if (indentlevel <= 1 && brackets.empty() && brackets2.empty()) { // there is a bug if indentlevel is 0 // the "}" token should only be added if indentlevel is 1 but I add it always intentionally // if indentlevel ever becomes 0, cppcheck will write: @@ -3453,20 +3013,17 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, } - if (tok3->isName()) - { + if (tok3->isName()) { // search for this token in the type vector unsigned int itype = 0; while (itype < type.size() && type[itype]->str() != tok3->str()) ++itype; // replace type with given type.. - if (itype < type.size()) - { + if (itype < type.size()) { for (const Token *typetok = types2[itype]; typetok && !Token::Match(typetok, "[,>]"); - typetok = typetok->next()) - { + typetok = typetok->next()) { addtoken(typetok, tok3->linenr(), tok3->fileIndex()); } continue; @@ -3474,48 +3031,35 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, } // replace name.. - if (Token::Match(tok3, (name + " !!<").c_str())) - { + if (Token::Match(tok3, (name + " !!<").c_str())) { addtoken(name2.c_str(), tok3->linenr(), tok3->fileIndex()); continue; } // copy addtoken(tok3, tok3->linenr(), tok3->fileIndex()); - if (Token::Match(tok3, "%type% <")) - { + if (Token::Match(tok3, "%type% <")) { if (!Token::Match(tok3, (name + " <").c_str())) done = false; used.push_back(_tokensBack); } // link() newly tokens manually - if (tok3->str() == "{") - { + if (tok3->str() == "{") { braces.push(_tokensBack); - } - else if (tok3->str() == "}") - { + } else if (tok3->str() == "}") { assert(braces.empty() == false); Token::createMutualLinks(braces.top(), _tokensBack); braces.pop(); - } - else if (tok3->str() == "(") - { + } else if (tok3->str() == "(") { brackets.push(_tokensBack); - } - else if (tok3->str() == "[") - { + } else if (tok3->str() == "[") { brackets2.push(_tokensBack); - } - else if (tok3->str() == ")") - { + } else if (tok3->str() == ")") { assert(brackets.empty() == false); Token::createMutualLinks(brackets.top(), _tokensBack); brackets.pop(); - } - else if (tok3->str() == "]") - { + } else if (tok3->str() == "]") { assert(brackets2.empty() == false); Token::createMutualLinks(brackets2.top(), _tokensBack); brackets2.pop(); @@ -3530,29 +3074,22 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, // Replace all these template usages.. std::list< std::pair > removeTokens; - for (Token *tok4 = tok2; tok4; tok4 = tok4->next()) - { - if (Token::simpleMatch(tok4, s1.c_str())) - { + for (Token *tok4 = tok2; tok4; tok4 = tok4->next()) { + if (Token::simpleMatch(tok4, s1.c_str())) { Token * tok5 = tok4->tokAt(2); unsigned int count = 0; const Token *typetok = (!types2.empty()) ? types2[0] : 0; - while (tok5 && tok5->str() != ">") - { - if (tok5->str() != ",") - { + while (tok5 && tok5->str() != ">") { + if (tok5->str() != ",") { if (!typetok || tok5->isUnsigned() != typetok->isUnsigned() || tok5->isSigned() != typetok->isSigned() || - tok5->isLong() != typetok->isLong()) - { + tok5->isLong() != typetok->isLong()) { break; } typetok = typetok ? typetok->next() : 0; - } - else - { + } else { ++count; typetok = (count < types2.size()) ? types2[count] : 0; } @@ -3561,11 +3098,9 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, // matching template usage => replace tokens.. // Foo < int > => Foo - if (tok5 && tok5->str() == ">" && count + 1U == types2.size()) - { + if (tok5 && tok5->str() == ">" && count + 1U == types2.size()) { tok4->str(name2); - for (Token *tok6 = tok4->next(); tok6 != tok5; tok6 = tok6->next()) - { + for (Token *tok6 = tok4->next(); tok6 != tok5; tok6 = tok6->next()) { if (tok6->isName()) used.remove(tok6); } @@ -3577,8 +3112,7 @@ void Tokenizer::simplifyTemplatesInstantiate(const Token *tok, break; } } - while (!removeTokens.empty()) - { + while (!removeTokens.empty()) { Token::eraseTokens(removeTokens.back().first, removeTokens.back().second); removeTokens.pop_back(); } @@ -3592,21 +3126,18 @@ void Tokenizer::simplifyTemplates() // Locate templates.. std::list templates(simplifyTemplatesGetTemplateDeclarations()); - if (templates.empty()) - { + if (templates.empty()) { removeTemplates(_tokens); return; } // There are templates.. // Remove "typename" unless used in template arguments.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "typename") tok->deleteThis(); - if (Token::simpleMatch(tok, "template <")) - { + if (Token::simpleMatch(tok, "template <")) { while (tok && tok->str() != ">") tok = tok->next(); if (!tok) @@ -3618,8 +3149,7 @@ void Tokenizer::simplifyTemplates() std::list used(simplifyTemplatesGetTemplateInstantiations()); // No template instantiations? Then remove all templates. - if (used.empty()) - { + if (used.empty()) { removeTemplates(_tokens); return; } @@ -3632,8 +3162,7 @@ void Tokenizer::simplifyTemplates() //while (!done) { done = true; - for (std::list::reverse_iterator iter1 = templates.rbegin(); iter1 != templates.rend(); ++iter1) - { + for (std::list::reverse_iterator iter1 = templates.rbegin(); iter1 != templates.rend(); ++iter1) { simplifyTemplatesInstantiate(*iter1, used, expandedtemplates); } } @@ -3644,22 +3173,18 @@ void Tokenizer::simplifyTemplates() void Tokenizer::simplifyTemplates2() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "(") tok = tok->link(); - else if (Token::Match(tok, "; %type% <")) - { + else if (Token::Match(tok, "; %type% <")) { const Token *tok2 = tok->tokAt(3); std::string type; - while (Token::Match(tok2, "%type% ,") || Token::Match(tok2, "%num% ,")) - { + while (Token::Match(tok2, "%type% ,") || Token::Match(tok2, "%num% ,")) { type += tok2->str() + ","; tok2 = tok2->tokAt(2); } - if (Token::Match(tok2, "%type% > (") || Token::Match(tok2, "%num% > (")) - { + if (Token::Match(tok2, "%type% > (") || Token::Match(tok2, "%num% > (")) { type += tok2->str(); tok = tok->next(); tok->str(tok->str() + "<" + type + ">"); @@ -3677,10 +3202,8 @@ std::string Tokenizer::getNameForFunctionParams(const Token *start) std::string result; bool findNextComma = false; - for (const Token *tok = start->next(); tok && tok != start->link(); tok = tok->next()) - { - if (findNextComma) - { + for (const Token *tok = start->next(); tok && tok != start->link(); tok = tok->next()) { + if (findNextComma) { if (tok->str() == ",") findNextComma = false; @@ -3702,8 +3225,7 @@ void Tokenizer::setVarId() // Set variable ids.. _varId = 0; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok != _tokens && !Token::Match(tok, "[;{}(,] %type%") && !Token::Match(tok, "[;{}(,] ::")) continue; @@ -3716,8 +3238,7 @@ void Tokenizer::setVarId() // If pattern is "( %type% *|& %var% )" then check if it's a // variable declaration or a multiplication / mask - if (Token::Match(tok, "( %type% *|& %var% [),]") && !tok->next()->isStandardType()) - { + if (Token::Match(tok, "( %type% *|& %var% [),]") && !tok->next()->isStandardType()) { if (!Token::Match(tok->previous(), "%type%")) continue; if (tok->strAt(-1) == "return") @@ -3727,12 +3248,10 @@ void Tokenizer::setVarId() continue; } - if (Token::Match(tok, "[,;{}(] %type%") || Token::Match(tok, "[;{}(,] ::")) - { + if (Token::Match(tok, "[,;{}(] %type%") || Token::Match(tok, "[;{}(,] ::")) { // not function declaration? // TODO: Better checking - if (Token::Match(tok->tokAt(-2), "= %var% (")) - { + if (Token::Match(tok->tokAt(-2), "= %var% (")) { continue; } if (tok->str() == "(" && @@ -3755,8 +3274,7 @@ void Tokenizer::setVarId() if (Token::Match(tok, "class|struct %type% :|{|;")) continue; - if (Token::Match(tok, "using namespace %type% ;")) - { + if (Token::Match(tok, "using namespace %type% ;")) { tok = tok->next(); continue; } @@ -3778,14 +3296,12 @@ void Tokenizer::setVarId() tok = tok->tokAt(2); // Skip template arguments.. - if (Token::Match(tok, "%type% <")) - { + if (Token::Match(tok, "%type% <")) { int level = 1; bool again; Token *tok2 = tok->tokAt(2); - do // Look for start of templates or template arguments - { + do { // Look for start of templates or template arguments if (!tok2) // syntax error return; @@ -3797,36 +3313,29 @@ void Tokenizer::setVarId() while (Token::Match(tok2, "%var% ::")) tok2 = tok2->tokAt(2); - if (Token::Match(tok2, "%type% <")) - { + if (Token::Match(tok2, "%type% <")) { level++; tok2 = tok2->tokAt(2); again = true; - } - else if (Token::Match(tok2, "%type% *|&| ,")) - { + } else if (Token::Match(tok2, "%type% *|&| ,")) { tok2 = tok2->tokAt(2); if (!tok2) // syntax error return; - if (tok2->str() == ",") - { + if (tok2->str() == ",") { tok2 = tok2->next(); if (!tok2) // syntax error return; } again = true; - } - else if (level > 1 && (Token::Match(tok2, "%type% *|&| >") || - Token::Match(tok2, "%num% >"))) - { + } else if (level > 1 && (Token::Match(tok2, "%type% *|&| >") || + Token::Match(tok2, "%num% >"))) { --level; while (tok2->str() != ">") tok2 = tok2->next(); tok2 = tok2->next(); if (!tok2) // syntax error return; - if (tok2->str() == ",") - { + if (tok2->str() == ",") { tok2 = tok2->next(); if (!tok2) // syntax error return; @@ -3834,52 +3343,42 @@ void Tokenizer::setVarId() if (level == 1 && tok2->str() == ">") break; again = true; - } - else - { + } else { while (tok2 && (tok2->isName() || tok2->isNumber() || tok2->str() == "*" || tok2->str() == "&" || tok2->str() == ",")) tok2 = tok2->next(); - if (tok2 && tok2->str() == "(") - { + if (tok2 && tok2->str() == "(") { tok2 = tok2->link()->next(); if (tok2 && tok2->str() == "(") tok2 = tok2->link()->next(); again = true; } } - } - while (again); + } while (again); - do // Look for end of templates - { + do { // Look for end of templates again = false; if (level == 1 && Token::Match(tok2, "> %var%")) tok = tok2; - else if (level > 1 && tok2 && tok2->str() == ">") - { + else if (level > 1 && tok2 && tok2->str() == ">") { level--; if (level == 0) tok = tok2; - else - { + else { tok2 = tok2->tokAt(1); again = true; } - } - else if (level == 1 && Token::Match(tok2, "> ::|*|& %var%")) + } else if (level == 1 && Token::Match(tok2, "> ::|*|& %var%")) tok = tok2->next(); else continue; // Not code that I understand / not a variable declaration - } - while (again); + } while (again); } // Determine name of declared variable.. std::string varname; Token *tok2 = tok->tokAt(1); - while (tok2) - { + while (tok2) { if (tok2->isName()) varname = tok2->str(); else if (tok2->str() != "*" && tok2->str() != "&") @@ -3898,8 +3397,7 @@ void Tokenizer::setVarId() continue; // Is it a function? - if (tok2->str() == "(") - { + if (tok2->str() == "(") { // Search for function declaration, e.g. void f(); if (Token::simpleMatch(tok2->next(), ") ;")) continue; @@ -3909,22 +3407,17 @@ void Tokenizer::setVarId() Token::Match(tok2->next(), "%bool%") || tok2->next()->str()[0] == '"' || tok2->next()->str()[0] == '\'' || - tok2->next()->varId() != 0) - { + tok2->next()->varId() != 0) { // This is not a function - } - else - { + } else { continue; } } // Don't set variable id for 'AAA a[0] = 0;' declaration (#2638) - if (tok2->previous()->varId() && tok2->str() == "[") - { + if (tok2->previous()->varId() && tok2->str() == "[") { const Token *tok3 = tok2; - while (tok3 && tok3->str() == "[") - { + while (tok3 && tok3->str() == "[") { tok3 = tok3->link(); tok3 = tok3 ? tok3->next() : NULL; } @@ -3933,22 +3426,17 @@ void Tokenizer::setVarId() } // Variable declaration found => Set variable ids - if (Token::Match(tok2, "[,();[=]") && !varname.empty()) - { + if (Token::Match(tok2, "[,();[=]") && !varname.empty()) { // Are we in a class declaration? // Then start at the start of the class declaration.. - while (NULL != (tok2 = tok2->previous())) - { + while (NULL != (tok2 = tok2->previous())) { if (tok2->str() == "}" || tok2->str() == ")") tok2 = tok2->link(); else if (tok2->str() == "(") break; - else if (tok2->str() == "{") - { - while (NULL != (tok2 = tok2->previous())) - { - if (Token::Match(tok2, "[,;{})]")) - { + else if (tok2->str() == "{") { + while (NULL != (tok2 = tok2->previous())) { + if (Token::Match(tok2, "[,;{})]")) { if (!Token::Match(tok2, ", public|protected|private")) break; } @@ -3965,25 +3453,20 @@ void Tokenizer::setVarId() className = tok2->strAt(1); // Set start token - if (Token::Match(tok2, "class|struct")) - { + if (Token::Match(tok2, "class|struct")) { while (tok2->str() != "{") tok2 = tok2->next(); - } - else + } else tok2 = tok; ++_varId; int indentlevel = 0; int parlevel = 0; bool funcDeclaration = false; - while (NULL != (tok2 = tok2->next())) - { + while (NULL != (tok2 = tok2->next())) { const char c = tok2->str()[0]; - if (c == varname[0]) - { - if (tok2->str() == varname) - { + if (c == varname[0]) { + if (tok2->str() == varname) { const std::string &prev = tok2->previous()->str(); /** @todo better handling when classes in different scopes have the same name */ @@ -3993,11 +3476,9 @@ void Tokenizer::setVarId() else if (tok2->str() == varname && prev != "struct" && prev != "union" && prev != "::" && prev != "." && tok2->strAt(1) != "::") tok2->varId(_varId); } - } - else if (c == '{') + } else if (c == '{') ++indentlevel; - else if (c == '}') - { + else if (c == '}') { --indentlevel; if (indentlevel < 0) break; @@ -4005,18 +3486,15 @@ void Tokenizer::setVarId() // We have reached the end of a loop: "for( int i;;) { }" if (funcDeclaration && indentlevel <= 0) break; - } - else if (c == '(') + } else if (c == '(') ++parlevel; - else if (c == ')') - { + else if (c == ')') { // Is this a function parameter or a variable declared in for example a for loop? if (parlevel == 0 && indentlevel == 0 && Token::Match(tok2, ") const| {")) funcDeclaration = true; else --parlevel; - } - else if (parlevel < 0 && c == ';') + } else if (parlevel < 0 && c == ';') break; } } @@ -4026,10 +3504,8 @@ void Tokenizer::setVarId() std::list allMemberFunctions; std::list allMemberVars; { - for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) - { - if (Token::Match(tok2, "%var% :: %var%")) - { + for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) { + if (Token::Match(tok2, "%var% :: %var%")) { if (Token::simpleMatch(tok2->tokAt(3), "(")) allMemberFunctions.push_back(tok2); else if (tok2->tokAt(2)->varId() != 0) @@ -4039,23 +3515,19 @@ void Tokenizer::setVarId() } // class members.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "class|struct %var% {|:")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "class|struct %var% {|:")) { const std::string &classname(tok->next()->str()); // What member variables are there in this class? std::map varlist; { unsigned int indentlevel = 0; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { // Indentation.. if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; @@ -4076,8 +3548,7 @@ void Tokenizer::setVarId() continue; // Member variables - for (std::list::iterator func = allMemberVars.begin(); func != allMemberVars.end(); ++func) - { + for (std::list::iterator func = allMemberVars.begin(); func != allMemberVars.end(); ++func) { if (!Token::simpleMatch(*func, classname.c_str())) continue; @@ -4090,13 +3561,11 @@ void Tokenizer::setVarId() std::list funclist; { const std::string funcpattern(classname + " :: %var% ("); - for (std::list::iterator func = allMemberFunctions.begin(); func != allMemberFunctions.end(); ++func) - { + for (std::list::iterator func = allMemberFunctions.begin(); func != allMemberFunctions.end(); ++func) { Token *tok2 = *func; // Found a class function.. - if (Token::Match(tok2, funcpattern.c_str())) - { + if (Token::Match(tok2, funcpattern.c_str())) { // Goto the end parenthesis.. tok2 = tok2->tokAt(3)->link(); if (!tok2) @@ -4111,24 +3580,19 @@ void Tokenizer::setVarId() // Update the variable ids.. // Parse each function.. - for (std::list::iterator func = funclist.begin(); func != funclist.end(); ++func) - { + for (std::list::iterator func = funclist.begin(); func != funclist.end(); ++func) { unsigned int indentlevel = 0; - for (Token *tok2 = *func; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = *func; tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; - } - else if (indentlevel > 0 && - tok2->varId() == 0 && - !Token::simpleMatch(tok2->previous(), ".") && - varlist.find(tok2->str()) != varlist.end()) - { + } else if (indentlevel > 0 && + tok2->varId() == 0 && + !Token::simpleMatch(tok2->previous(), ".") && + varlist.find(tok2->str()) != varlist.end()) { tok2->varId(varlist[tok2->str()]); } } @@ -4138,21 +3602,17 @@ void Tokenizer::setVarId() } // Struct/Class members - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // str.clear is a variable // str.clear() is a member function if (tok->varId() != 0 && Token::Match(tok->next(), ". %var% !!(") && - tok->tokAt(2)->varId() == 0) - { + tok->tokAt(2)->varId() == 0) { ++_varId; const std::string pattern(std::string(". ") + tok->strAt(2)); - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->varId() == tok->varId()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->varId() == tok->varId()) { if (Token::Match(tok2->next(), pattern.c_str())) tok2->tokAt(2)->varId(_varId); } @@ -4167,28 +3627,21 @@ bool Tokenizer::createLinks() std::list links; std::list links2; std::list links3; - for (Token *token = _tokens; token; token = token->next()) - { - if (token->link()) - { + for (Token *token = _tokens; token; token = token->next()) { + if (token->link()) { token->link(0); } - if (token->str() == "{") - { + if (token->str() == "{") { links.push_back(token); type.push_back(token); - } - else if (token->str() == "}") - { - if (links.empty()) - { + } else if (token->str() == "}") { + if (links.empty()) { // Error, { and } don't match. syntaxError(token, '{'); return false; } - if (type.back()->str() != "{") - { + if (type.back()->str() != "{") { syntaxError(type.back(), type.back()->str()[0]); return false; } @@ -4196,22 +3649,16 @@ bool Tokenizer::createLinks() Token::createMutualLinks(links.back(), token); links.pop_back(); - } - else if (token->str() == "(") - { + } else if (token->str() == "(") { links2.push_back(token); type.push_back(token); - } - else if (token->str() == ")") - { - if (links2.empty()) - { + } else if (token->str() == ")") { + if (links2.empty()) { // Error, ( and ) don't match. syntaxError(token, '('); return false; } - if (type.back()->str() != "(") - { + if (type.back()->str() != "(") { syntaxError(type.back(), type.back()->str()[0]); return false; } @@ -4219,22 +3666,16 @@ bool Tokenizer::createLinks() Token::createMutualLinks(links2.back(), token); links2.pop_back(); - } - else if (token->str() == "[") - { + } else if (token->str() == "[") { links3.push_back(token); type.push_back(token); - } - else if (token->str() == "]") - { - if (links3.empty()) - { + } else if (token->str() == "]") { + if (links3.empty()) { // Error, [ and ] don't match. syntaxError(token, '['); return false; } - if (type.back()->str() != "[") - { + if (type.back()->str() != "[") { syntaxError(type.back(), type.back()->str()[0]); return false; } @@ -4245,22 +3686,19 @@ bool Tokenizer::createLinks() } } - if (!links.empty()) - { + if (!links.empty()) { // Error, { and } don't match. syntaxError(links.back(), '{'); return false; } - if (!links2.empty()) - { + if (!links2.empty()) { // Error, ( and ) don't match. syntaxError(links2.back(), '('); return false; } - if (!links3.empty()) - { + if (!links3.empty()) { // Error, [ and ] don't match. syntaxError(links3.back(), '['); return false; @@ -4271,10 +3709,8 @@ bool Tokenizer::createLinks() void Tokenizer::simplifySizeof() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "class|struct %var%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "class|struct %var%")) { // we assume that the size of structs and classes are always // 100 bytes. _typeSize[tok->strAt(1)] = 100; @@ -4283,33 +3719,27 @@ void Tokenizer::simplifySizeof() // Locate variable declarations and calculate the size std::map sizeOfVar; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->varId() != 0 && sizeOfVar.find(tok->varId()) == sizeOfVar.end()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->varId() != 0 && sizeOfVar.find(tok->varId()) == sizeOfVar.end()) { const unsigned int varId = tok->varId(); if (Token::Match(tok->tokAt(-3), "[;{}(,] %type% * %var% [;,)]") || Token::Match(tok->tokAt(-4), "[;{}(,] const %type% * %var% [;),]") || Token::Match(tok->tokAt(-2), "[;{}(,] %type% %var% [;),]") || - Token::Match(tok->tokAt(-3), "[;{}(,] const %type% %var% [;),]")) - { + Token::Match(tok->tokAt(-3), "[;{}(,] const %type% %var% [;),]")) { const unsigned int size = sizeOfType(tok->previous()); - if (size == 0) - { + if (size == 0) { continue; } sizeOfVar[varId] = MathLib::toString(size); } - else if (Token::Match(tok->tokAt(-3), "[;{}(,] struct %type% %var% [;,)]")) - { + else if (Token::Match(tok->tokAt(-3), "[;{}(,] struct %type% %var% [;,)]")) { sizeOfVar[varId] = "100"; } else if (Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [;=]") || - Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [;=]")) - { + Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [;=]")) { const unsigned int size = sizeOfType(tok->tokAt(-1)); if (size == 0) continue; @@ -4318,15 +3748,13 @@ void Tokenizer::simplifySizeof() } else if (Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [,)]") || - Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [,)]")) - { + Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [,)]")) { Token tempTok(0); tempTok.str("*"); sizeOfVar[varId] = MathLib::toString(sizeOfType(&tempTok)); } - else if (Token::Match(tok->tokAt(-1), "%type% %var% [ ] = %str% ;")) - { + else if (Token::Match(tok->tokAt(-1), "%type% %var% [ ] = %str% ;")) { const unsigned int size = sizeOfType(tok->tokAt(4)); if (size == 0) continue; @@ -4336,8 +3764,7 @@ void Tokenizer::simplifySizeof() } } - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "sizeof") continue; @@ -4347,14 +3774,12 @@ void Tokenizer::simplifySizeof() if (Token::simpleMatch(tok->next(), "sizeof")) continue; - if (Token::simpleMatch(tok->next(), ". . .")) - { + if (Token::simpleMatch(tok->next(), ". . .")) { Token::eraseTokens(tok, tok->tokAt(4)); } // sizeof 'x' - if (tok->strAt(1)[0] == '\'') - { + if (tok->strAt(1)[0] == '\'') { tok->deleteThis(); std::ostringstream sz; sz << sizeof 'x'; @@ -4363,8 +3788,7 @@ void Tokenizer::simplifySizeof() } // sizeof('x') - if (Token::Match(tok, "sizeof ( %any% )") && tok->strAt(2)[0] == '\'') - { + if (Token::Match(tok, "sizeof ( %any% )") && tok->strAt(2)[0] == '\'') { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); @@ -4375,8 +3799,7 @@ void Tokenizer::simplifySizeof() } // sizeof "text" - if (Token::Match(tok->next(), "%str%")) - { + if (Token::Match(tok->next(), "%str%")) { tok->deleteThis(); std::ostringstream ostr; ostr << (Token::getStrLength(tok) + 1); @@ -4385,8 +3808,7 @@ void Tokenizer::simplifySizeof() } // sizeof ("text") - if (Token::Match(tok->next(), "( %str% )")) - { + if (Token::Match(tok->next(), "( %str% )")) { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); @@ -4397,23 +3819,20 @@ void Tokenizer::simplifySizeof() } // sizeof * (...) -> sizeof(*...) - if (Token::simpleMatch(tok->next(), "* (") && !Token::simpleMatch(tok->tokAt(2)->link(), ") .")) - { + if (Token::simpleMatch(tok->next(), "* (") && !Token::simpleMatch(tok->tokAt(2)->link(), ") .")) { tok->deleteNext(); tok->next()->insertToken("*"); } // sizeof a++ -> sizeof(a++) - if (Token::Match(tok->next(), "++|-- %var% !!.") || Token::Match(tok->next(), "%var% ++|--")) - { + if (Token::Match(tok->next(), "++|-- %var% !!.") || Token::Match(tok->next(), "%var% ++|--")) { tok->insertToken("("); tok->tokAt(3)->insertToken(")"); Token::createMutualLinks(tok->next(), tok->tokAt(4)); } // sizeof 1 => sizeof ( 1 ) - if (tok->next()->isNumber()) - { + if (tok->next()->isNumber()) { Token *tok2 = tok->next(); tok->insertToken("("); tok2->insertToken(")"); @@ -4421,47 +3840,35 @@ void Tokenizer::simplifySizeof() } // sizeof int -> sizeof( int ) - else if (tok->next()->str() != "(") - { + else if (tok->next()->str() != "(") { // Add parenthesis around the sizeof int parlevel = 0; - for (Token *tempToken = tok->next(); tempToken; tempToken = tempToken->next()) - { + for (Token *tempToken = tok->next(); tempToken; tempToken = tempToken->next()) { if (tempToken->str() == "(") ++parlevel; else if (tempToken->str() == ")") --parlevel; - if (Token::Match(tempToken, "%var%")) - { - while (tempToken && tempToken->next() && tempToken->next()->str() == "[") - { + if (Token::Match(tempToken, "%var%")) { + while (tempToken && tempToken->next() && tempToken->next()->str() == "[") { tempToken = tempToken->next()->link(); } - if (!tempToken || !tempToken->next()) - { + if (!tempToken || !tempToken->next()) { break; } - if (tempToken->next()->str() == ".") - { + if (tempToken->next()->str() == ".") { // We are checking a class or struct, search next varname tempToken = tempToken->tokAt(1); continue; - } - else if (Token::simpleMatch(tempToken->next(), "- >")) - { + } else if (Token::simpleMatch(tempToken->next(), "- >")) { // We are checking a class or struct, search next varname tempToken = tempToken->tokAt(2); continue; - } - else if (Token::Match(tempToken->next(), "++|--")) - { + } else if (Token::Match(tempToken->next(), "++|--")) { // We have variable++ or variable--, there should be // nothing after this tempToken = tempToken->tokAt(2); - } - else if (parlevel > 0 && Token::simpleMatch(tempToken->next(), ") .")) - { + } else if (parlevel > 0 && Token::simpleMatch(tempToken->next(), ") .")) { --parlevel; tempToken = tempToken->tokAt(2); continue; @@ -4477,77 +3884,59 @@ void Tokenizer::simplifySizeof() } // sizeof(type *) => sizeof(*) - if (Token::Match(tok->next(), "( %type% * )")) - { + if (Token::Match(tok->next(), "( %type% * )")) { tok->next()->deleteNext(); } - if (Token::simpleMatch(tok->next(), "( * )")) - { + if (Token::simpleMatch(tok->next(), "( * )")) { tok->str(MathLib::toString(sizeOfType(tok->tokAt(2)))); Token::eraseTokens(tok, tok->tokAt(4)); } // sizeof( a ) - else if (Token::Match(tok->next(), "( %var% )") && tok->tokAt(2)->varId() != 0) - { - if (sizeOfVar.find(tok->tokAt(2)->varId()) != sizeOfVar.end()) - { + else if (Token::Match(tok->next(), "( %var% )") && tok->tokAt(2)->varId() != 0) { + if (sizeOfVar.find(tok->tokAt(2)->varId()) != sizeOfVar.end()) { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); tok->str(sizeOfVar[tok->varId()]); - } - else - { + } else { // don't try to replace size of variable if variable has // similar name with type (#329) } } - else if (Token::Match(tok, "sizeof ( %type% )")) - { + else if (Token::Match(tok, "sizeof ( %type% )")) { unsigned int size = sizeOfType(tok->tokAt(2)); - if (size > 0) - { + if (size > 0) { tok->str(MathLib::toString(size)); Token::eraseTokens(tok, tok->tokAt(4)); } } - else if (Token::Match(tok, "sizeof ( * %var% )") || Token::Match(tok, "sizeof ( %var% [ %num% ] )")) - { + else if (Token::Match(tok, "sizeof ( * %var% )") || Token::Match(tok, "sizeof ( %var% [ %num% ] )")) { // Some default value.. unsigned int sz = 0; unsigned int varid = tok->tokAt((tok->tokAt(2)->str() == "*") ? 3 : 2)->varId(); - if (varid != 0) - { + if (varid != 0) { // Try to locate variable declaration.. const Token *decltok = Token::findmatch(_tokens, "%varid%", varid); - if (Token::Match(decltok->previous(), "%type% %var% [")) - { + if (Token::Match(decltok->previous(), "%type% %var% [")) { sz = sizeOfType(decltok->previous()); - } - else if (Token::Match(decltok->previous(), "* %var% [")) - { + } else if (Token::Match(decltok->previous(), "* %var% [")) { sz = sizeOfType(decltok->previous()); - } - else if (Token::Match(decltok->tokAt(-2), "%type% * %var%")) - { + } else if (Token::Match(decltok->tokAt(-2), "%type% * %var%")) { sz = sizeOfType(decltok->tokAt(-2)); } - } - else if (tok->strAt(3) == "[" && tok->tokAt(2)->isStandardType()) - { + } else if (tok->strAt(3) == "[" && tok->tokAt(2)->isStandardType()) { sz = sizeOfType(tok->tokAt(2)); if (sz == 0) continue; sz = sz * static_cast(MathLib::toLongNumber(tok->strAt(4))); } - if (sz > 0) - { + if (sz > 0) { tok->str(MathLib::toString(sz)); Token::eraseTokens(tok, tok->next()->link()->next()); } @@ -4562,8 +3951,7 @@ bool Tokenizer::simplifyTokenList() delete _symbolDatabase; _symbolDatabase = NULL; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::simpleMatch(tok, "* const")) tok->deleteNext(); } @@ -4578,10 +3966,8 @@ bool Tokenizer::simplifyTokenList() simplifyDeadCode(); // Combine wide strings - for (Token *tok = _tokens; tok; tok = tok->next()) - { - while (tok->str() == "L" && tok->next() && tok->next()->str()[0] == '"') - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + while (tok->str() == "L" && tok->next() && tok->next()->str()[0] == '"') { // Combine 'L "string"' tok->str(tok->next()->str()); tok->deleteNext(); @@ -4589,14 +3975,12 @@ bool Tokenizer::simplifyTokenList() } // Combine strings - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str()[0] != '"') continue; tok->str(simplifyString(tok->str())); - while (tok->next() && tok->next()->str()[0] == '"') - { + while (tok->next() && tok->next()->str()[0] == '"') { tok->next()->str(simplifyString(tok->next()->str())); // Two strings after each other, combine them @@ -4609,10 +3993,8 @@ bool Tokenizer::simplifyTokenList() // replace strlen(str) simplifyKnownVariables(); - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "strlen ( %str% )")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "strlen ( %str% )")) { std::ostringstream ostr; ostr << Token::getStrLength(tok->tokAt(2)); tok->str(ostr.str()); @@ -4623,45 +4005,35 @@ bool Tokenizer::simplifyTokenList() } // change array to pointer.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "%type% %var% [ ] [,;=]")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "%type% %var% [ ] [,;=]")) { Token::eraseTokens(tok->next(), tok->tokAt(4)); tok->insertToken("*"); } } // Replace constants.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "const %type% %var% = %num% ;")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "const %type% %var% = %num% ;")) { unsigned int varId = tok->tokAt(2)->varId(); - if (varId == 0) - { + if (varId == 0) { tok = tok->tokAt(5); continue; } const std::string num = tok->strAt(4); int indent = 1; - for (Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { ++indent; - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { --indent; if (indent == 0) break; } // Compare constants, but don't touch members of other structures - else if (tok2->varId() == varId) - { + else if (tok2->varId() == varId) { tok2->str(num); } } @@ -4674,8 +4046,7 @@ bool Tokenizer::simplifyTokenList() simplifyCalculations(); // Replace "*(str + num)" => "str[num]" - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (! strchr(";{}(=<>", tok->str()[0])) continue; @@ -4684,8 +4055,7 @@ bool Tokenizer::simplifyTokenList() break; if (Token::Match(next, "* ( %var% + %num% )") || - Token::Match(next, "* ( %var% + %var% )")) - { + Token::Match(next, "* ( %var% + %var% )")) { // var tok = tok->next(); tok->str(tok->strAt(2)); @@ -4711,10 +4081,8 @@ bool Tokenizer::simplifyTokenList() // simplify "x=realloc(y,0);" => "free(y); x=0;".. // and "x = realloc (0, n);" => "x = malloc(n);" - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;")) { const std::string varname(tok->next()->str()); const unsigned int varid(tok->next()->varId()); @@ -4737,9 +4105,7 @@ bool Tokenizer::simplifyTokenList() tok->insertToken("="); tok->insertToken(varname); tok->next()->varId(varid); - } - else if (Token::Match(tok, "; %var% = realloc ( 0 , %num% ) ;")) - { + } else if (Token::Match(tok, "; %var% = realloc ( 0 , %num% ) ;")) { const std::string varname(tok->next()->str()); tok = tok->tokAt(3); @@ -4773,8 +4139,7 @@ bool Tokenizer::simplifyTokenList() simplifyIfAssign(); // could be affected by simplifyIfNot - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "case %any% : %var%")) tok->tokAt(2)->insertToken(";"); if (Token::Match(tok, "default : %var%")) @@ -4785,8 +4150,7 @@ bool Tokenizer::simplifyTokenList() setVarId(); bool modified = true; - while (modified) - { + while (modified) { modified = false; modified |= simplifyConditions(); modified |= simplifyFunctionReturn(); @@ -4801,18 +4165,13 @@ bool Tokenizer::simplifyTokenList() removeRedundantFor(); // Remove redundant parentheses in return.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - while (Token::simpleMatch(tok, "return (")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + while (Token::simpleMatch(tok, "return (")) { Token *tok2 = tok->next()->link(); - if (Token::simpleMatch(tok2, ") ;")) - { + if (Token::simpleMatch(tok2, ") ;")) { tok->deleteNext(); tok2->deleteThis(); - } - else - { + } else { break; } } @@ -4831,13 +4190,11 @@ bool Tokenizer::simplifyTokenList() _tokens->assignProgressValues(); - if (_settings->debug) - { + if (_settings->debug) { _tokens->printOut(0, _files); } - if (_settings->debugwarnings) - { + if (_settings->debugwarnings) { printUnknownTypes(); } @@ -4847,10 +4204,8 @@ bool Tokenizer::simplifyTokenList() void Tokenizer::removeMacrosInGlobalScope() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "(") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "(") { tok = tok->link(); if (Token::Match(tok, ") %type% {") && !Token::Match(tok->next(), "const|namespace|class|struct|union")) @@ -4865,23 +4220,19 @@ void Tokenizer::removeMacrosInGlobalScope() void Tokenizer::removeRedundantAssignment() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "{") tok = tok->link(); - if (Token::Match(tok, ") const| {")) - { + if (Token::Match(tok, ") const| {")) { // parse in this function.. std::set localvars; if (tok->next()->str() == "const") tok = tok->next(); const Token * const end = tok->next()->link(); - for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) { // skip local class or struct - if (Token::Match(tok2, "class|struct %type% {|:")) - { + if (Token::Match(tok2, "class|struct %type% {|:")) { // skip to '{' while (tok2 && tok2->str() != "{") tok2 = tok2->next(); @@ -4890,40 +4241,27 @@ void Tokenizer::removeRedundantAssignment() tok2 = tok2->link(); // skip local class or struct else return; - } - else if (Token::Match(tok2, "[;{}] %type% * %var% ;") && tok2->strAt(1) != "return") - { + } else if (Token::Match(tok2, "[;{}] %type% * %var% ;") && tok2->strAt(1) != "return") { tok2 = tok2->tokAt(3); localvars.insert(tok2->varId()); - } - else if (Token::Match(tok2, "[;{}] %type% %var% ;") && tok2->next()->isStandardType()) - { + } else if (Token::Match(tok2, "[;{}] %type% %var% ;") && tok2->next()->isStandardType()) { tok2 = tok2->tokAt(2); localvars.insert(tok2->varId()); - } - else if (tok2->varId() && - !Token::Match(tok2->previous(), "[;{}] %var% = %var% ;") && - !Token::Match(tok2->previous(), "[;{}] %var% = %num% ;") && - !(Token::Match(tok2->previous(), "[;{}] %var% = %any% ;") && tok2->strAt(2)[0] == '\'')) - { + } else if (tok2->varId() && + !Token::Match(tok2->previous(), "[;{}] %var% = %var% ;") && + !Token::Match(tok2->previous(), "[;{}] %var% = %num% ;") && + !(Token::Match(tok2->previous(), "[;{}] %var% = %any% ;") && tok2->strAt(2)[0] == '\'')) { localvars.erase(tok2->varId()); } } localvars.erase(0); - if (!localvars.empty()) - { - for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) - { - if (Token::Match(tok2, "[;{}] %type% %var% ;") && localvars.find(tok2->tokAt(2)->varId()) != localvars.end()) - { + if (!localvars.empty()) { + for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) { + if (Token::Match(tok2, "[;{}] %type% %var% ;") && localvars.find(tok2->tokAt(2)->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(3)); - } - else if (Token::Match(tok2, "[;{}] %type% * %var% ;") && localvars.find(tok2->tokAt(3)->varId()) != localvars.end()) - { + } else if (Token::Match(tok2, "[;{}] %type% * %var% ;") && localvars.find(tok2->tokAt(3)->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(4)); - } - else if (Token::Match(tok2, "[;{}] %var% = %any% ;") && localvars.find(tok2->next()->varId()) != localvars.end()) - { + } else if (Token::Match(tok2, "[;{}] %var% = %any% ;") && localvars.find(tok2->next()->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(4)); } } @@ -4940,91 +4278,66 @@ void Tokenizer::simplifyDeadCode() unsigned int indentswitch = 0; unsigned int indentlabel = 0; unsigned int roundbraces = 0; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "(") ++roundbraces; - else if (tok->str() == ")") - { + else if (tok->str() == ")") { if (!roundbraces) break; //too many ending round parenthesis --roundbraces; } - if (tok->str() == "{") - { + if (tok->str() == "{") { ++indentlevel; - if (indentret) - { + if (indentret) { unsigned int indentlevel1 = indentlevel; - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel1; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel1 == indentlevel) break; --indentlevel1; - } - else if (Token::Match(tok2, "%var% : ;") && !Token::Match(tok2, "case|default")) - { + } else if (Token::Match(tok2, "%var% : ;") && !Token::Match(tok2, "case|default")) { indentlabel = indentlevel1; break; } } - if (indentlevel > indentlabel) - { + if (indentlevel > indentlabel) { tok = tok->previous(); tok->deleteNext(); } } - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { if (!indentlevel) break; //too many closing parenthesis - if (indentret) - { - if (!indentswitch || indentlevel > indentcase) - { - if (indentlevel > indentret && indentlevel > indentlabel) - { + if (indentret) { + if (!indentswitch || indentlevel > indentcase) { + if (indentlevel > indentret && indentlevel > indentlabel) { tok = tok->previous(); tok->deleteNext(); } - } - else - { - if (indentcase > indentret && indentlevel > indentlabel) - { + } else { + if (indentcase > indentret && indentlevel > indentlabel) { tok = tok->previous(); tok->deleteNext(); } } } - if (indentlevel == indentret) - { + if (indentlevel == indentret) { indentret = 0; } --indentlevel; - if (indentlevel <= indentcase) - { - if (!indentswitch) - { + if (indentlevel <= indentcase) { + if (!indentswitch) { indentcase = 0; - } - else - { + } else { --indentswitch; indentcase = indentlevel-1; } } - } - else if (!indentret) - { - if (tok->str() == "switch") - { + } else if (!indentret) { + if (tok->str() == "switch") { if (!indentlevel) break; @@ -5033,58 +4346,44 @@ void Tokenizer::simplifyDeadCode() break; unsigned int switchroundbraces = 0; - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++switchroundbraces; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (!switchroundbraces) break; //too many closing parenthesis --switchroundbraces; } - if (tok2->str() == "{") - { - if (switchroundbraces) - { + if (tok2->str() == "{") { + if (switchroundbraces) { tok = tok2->previous(); break; //too many opening parenthesis } tok = tok2; ++indentswitch; break; - } - else if (tok2->str() == "}") + } else if (tok2->str() == "}") break; //it's not expected, hence it's bad code } if (!indentswitch) break; ++indentlevel; indentcase = indentlevel; - } - else if (indentswitch && Token::Match(tok, "case|default")) - { - if (indentlevel > indentcase) - { + } else if (indentswitch && Token::Match(tok, "case|default")) { + if (indentlevel > indentcase) { --indentlevel; } - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { - if (Token::Match(tok2, ": ;| ")) - { - if (indentlevel == indentcase) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { + if (Token::Match(tok2, ": ;| ")) { + if (indentlevel == indentcase) { ++indentlevel; } tok = tok2; break; - } - else if (Token::Match(tok2, "[{}]")) + } else if (Token::Match(tok2, "[{}]")) break; //bad code } - } - else if (tok->str()=="return") - { + } else if (tok->str()=="return") { if (!indentlevel) break; @@ -5094,54 +4393,38 @@ void Tokenizer::simplifyDeadCode() //catch the first ';' after the return unsigned int returnroundbraces = 0; - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++returnroundbraces; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (!returnroundbraces) break; //excessive closing parenthesis --returnroundbraces; - } - else if (tok2->str() == ";") - { + } else if (tok2->str() == ";") { if (returnroundbraces) break; //excessive opening parenthesis indentret = indentlevel; tok = tok2; break; - } - else if (Token::Match(tok2, "[{}]")) + } else if (Token::Match(tok2, "[{}]")) break; //I think this is an error code... } if (!indentret) break; } - } - else if (indentret) //there's already a "return;" declaration - { - if (!indentswitch || indentlevel > indentcase+1) - { - if (indentlevel >= indentret && (!Token::Match(tok, "%var% : ;") || Token::Match(tok, "case|default"))) - { + } else if (indentret) { //there's already a "return;" declaration + if (!indentswitch || indentlevel > indentcase+1) { + if (indentlevel >= indentret && (!Token::Match(tok, "%var% : ;") || Token::Match(tok, "case|default"))) { tok = tok->previous(); tok->deleteNext(); - } - else - { + } else { indentret = 0; } - } - else - { - if (!Token::Match(tok, "%var% : ;") && !Token::Match(tok, "case|default")) - { + } else { + if (!Token::Match(tok, "%var% : ;") && !Token::Match(tok, "case|default")) { tok = tok->previous(); tok->deleteNext(); - } - else - { + } else { indentret = 0; tok = tok->previous(); } @@ -5156,8 +4439,7 @@ bool Tokenizer::removeReduntantConditions() // Return value for function. Set to true if there are any simplifications bool ret = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "if") continue; @@ -5175,25 +4457,18 @@ bool Tokenizer::removeReduntantConditions() boolValue = true; // Handle if with else - if (elseTag && elseTag->str() == "else") - { - if (Token::simpleMatch(elseTag->next(), "if (")) - { + if (elseTag && elseTag->str() == "else") { + if (Token::simpleMatch(elseTag->next(), "if (")) { // Handle "else if" - if (boolValue == false) - { + if (boolValue == false) { // Convert "if( false ) {aaa;} else if() {bbb;}" => "if() {bbb;}" Token::eraseTokens(tok, elseTag->tokAt(2)); ret = true; - } - else - { + } else { // Keep first if, remove every else if and else after it const Token *lastTagInIf = elseTag->tokAt(2); - while (lastTagInIf) - { - if (lastTagInIf->str() == "(") - { + while (lastTagInIf) { + if (lastTagInIf->str() == "(") { lastTagInIf = lastTagInIf->link()->next(); } @@ -5209,12 +4484,9 @@ bool Tokenizer::removeReduntantConditions() Token::eraseTokens(elseTag->previous(), lastTagInIf); ret = true; } - } - else - { + } else { // Handle else - if (boolValue == false) - { + if (boolValue == false) { // Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}" or ";{bbb;}" if (tok->previous()) tok = tok->previous(); @@ -5222,11 +4494,8 @@ bool Tokenizer::removeReduntantConditions() tok->str(";"); Token::eraseTokens(tok, elseTag->tokAt(1)); - } - else - { - if (elseTag->tokAt(1)->str() == "{") - { + } else { + if (elseTag->tokAt(1)->str() == "{") { // Convert "if( true ) {aaa;} else {bbb;}" => "{aaa;}" const Token *end = elseTag->tokAt(1)->link(); @@ -5248,10 +4517,8 @@ bool Tokenizer::removeReduntantConditions() } // Handle if without else - else - { - if (boolValue == false) - { + else { + if (boolValue == false) { // Remove if and its content if (tok->previous()) tok = tok->previous(); @@ -5259,9 +4526,7 @@ bool Tokenizer::removeReduntantConditions() tok->str(";"); Token::eraseTokens(tok, elseTag); - } - else - { + } else { // convert "if( true ) {aaa;}" => "{aaa;}" if (tok->previous()) tok = tok->previous(); @@ -5280,10 +4545,8 @@ bool Tokenizer::removeReduntantConditions() void Tokenizer::removeRedundantFor() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] for ( %var% = %num% ; %var% < %num% ; ++| %var% ++| ) {")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] for ( %var% = %num% ; %var% < %num% ; ++| %var% ++| ) {")) { // Same variable name.. const std::string varname(tok->tokAt(3)->str()); const unsigned int varid(tok->tokAt(3)->varId()); @@ -5305,27 +4568,21 @@ void Tokenizer::removeRedundantFor() bool read = false; bool write = false; unsigned int indentlevel = 0; - for (const Token *tok2 = tok->tokAt(2)->link(); tok2; tok2 = tok2->next()) - { + for (const Token *tok2 = tok->tokAt(2)->link(); tok2; tok2 = tok2->next()) { if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } - if (tok2->str() == varname) - { + if (tok2->str() == varname) { if (tok2->previous()->isArithmeticalOp() && tok2->next() && - (tok2->next()->isArithmeticalOp() || tok2->next()->str() == ";")) - { + (tok2->next()->isArithmeticalOp() || tok2->next()->str() == ";")) { read = true; - } - else - { + } else { read = write = true; break; } @@ -5333,21 +4590,17 @@ void Tokenizer::removeRedundantFor() } // Simplify loop if loop variable isn't written - if (!write) - { + if (!write) { // remove "for (" tok->deleteNext(); tok->deleteNext(); // If loop variable is read then keep assignment before // loop body.. - if (read) - { + if (read) { // goto ";" tok = tok->tokAt(4); - } - else - { + } else { // remove "x = 0 ;" tok->deleteNext(); tok->deleteNext(); @@ -5380,26 +4633,18 @@ void Tokenizer::removeRedundantFor() void Tokenizer::removeRedundantSemicolons() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "(") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "(") { tok = tok->link(); } - for (;;) - { - if (Token::simpleMatch(tok, "; ;")) - { + for (;;) { + if (Token::simpleMatch(tok, "; ;")) { tok->deleteNext(); - } - else if (Token::simpleMatch(tok, "; { ; }")) - { + } else if (Token::simpleMatch(tok, "; { ; }")) { tok->deleteNext(); tok->deleteNext(); tok->deleteNext(); - } - else - { + } else { break; } } @@ -5409,23 +4654,19 @@ void Tokenizer::removeRedundantSemicolons() bool Tokenizer::simplifyIfAddBraces() { - for (Token *tok = _tokens; tok; tok = tok ? tok->next() : NULL) - { - if (tok->str() == "(" && !Token::Match(tok->previous(), "[;{}]")) - { + for (Token *tok = _tokens; tok; tok = tok ? tok->next() : NULL) { + if (tok->str() == "(" && !Token::Match(tok->previous(), "[;{}]")) { tok = tok->link(); continue; } - if (Token::Match(tok, "if|for|while (")) - { + if (Token::Match(tok, "if|for|while (")) { // don't add "{}" around ";" in "do {} while();" (#609) const Token *prev = tok->previous(); if (Token::simpleMatch(prev, "} while") && prev->link() && prev->link()->previous() && - prev->link()->previous()->str() == "do") - { + prev->link()->previous()->str() == "do") { continue; } @@ -5437,21 +4678,18 @@ bool Tokenizer::simplifyIfAddBraces() continue; } - else if (tok->str() == "else") - { + else if (tok->str() == "else") { // An else followed by an if or brace don't need to be processed further if (Token::Match(tok, "else if|{")) continue; } - else - { + else { continue; } // If there is no code after the if(), abort - if (!tok->next()) - { + if (!tok->next()) { // This is a syntax error and we should call syntaxError() and return false but // many tokenizer tests are written with this syntax error so just ingore it. return true; @@ -5473,12 +4711,9 @@ bool Tokenizer::simplifyIfAddBraces() // * if (cond) for (;;) break; // * if (cond1) if (cond2) { } // * if (cond1) if (cond2) ; else ; - while ((tempToken = tempToken->next()) != NULL) - { - if (tempToken->str() == "{") - { - if (Token::simpleMatch(tempToken->previous(),"else {")) - { + while ((tempToken = tempToken->next()) != NULL) { + if (tempToken->str() == "{") { + if (Token::simpleMatch(tempToken->previous(),"else {")) { if (innerIf) tempToken = tempToken->link(); else @@ -5493,21 +4728,18 @@ bool Tokenizer::simplifyIfAddBraces() continue; } - if (tempToken->str() == "(") - { + if (tempToken->str() == "(") { tempToken = tempToken->link(); continue; } - if (tempToken->str() == "}") - { + if (tempToken->str() == "}") { // insert closing brace before this token tempToken = tempToken->previous(); break; } - if (tempToken->str() == ";") - { + if (tempToken->str() == ";") { if (!innerIf) break; @@ -5520,13 +4752,10 @@ bool Tokenizer::simplifyIfAddBraces() } } - if (tempToken) - { + if (tempToken) { tempToken->insertToken("}"); Token::createMutualLinks(tok, tempToken->next()); - } - else - { + } else { // Can't insert matching "}" so give up. This is fatal because it // causes unbalanced braces. syntaxError(tok); @@ -5538,8 +4767,7 @@ bool Tokenizer::simplifyIfAddBraces() bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) { - if (Token::Match(tok->next(), "[),]")) - { + if (Token::Match(tok->next(), "[),]")) { // fix for #988 return false; } @@ -5550,28 +4778,20 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) // skip loop body bool result = false; - while (tok3) - { - if (tok3->str() == "{") - { + while (tok3) { + if (tok3->str() == "{") { // skip all tokens until "}" tok3 = tok3->link(); - } - else if (tok3->str() == "while") - { + } else if (tok3->str() == "while") { tok2 = tok3; break; - } - else if (Token::simpleMatch(tok3, "do {")) - { + } else if (Token::simpleMatch(tok3, "do {")) { // Skip do{}while inside the current "do" tok3 = tok3->next()->link(); if (Token::simpleMatch(tok3->next(), "while")) tok3 = tok3->next(); - } - else if (Token::Match(tok3, "do !!{") && - !Token::Match(tok3->next(), "[),]")) - { + } else if (Token::Match(tok3, "do !!{") && + !Token::Match(tok3->next(), "[),]")) { // Handle do-while inside the current "do" // first and return true to get the outer // "do" to be handled later. @@ -5582,8 +4802,7 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) tok3 = tok3->next(); } - if (tok2) - { + if (tok2) { // insert "{" after "do" tok1->insertToken("{"); @@ -5591,8 +4810,7 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) tok2->previous()->insertToken("}"); Token::createMutualLinks(tok1->next(), tok2->previous()); - } - else + } else result = false; return result; @@ -5600,12 +4818,9 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) void Tokenizer::simplifyDoWhileAddBraces() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "do !!{")) - { - while (simplifyDoWhileAddBracesHelper(tok)) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "do !!{")) { + while (simplifyDoWhileAddBracesHelper(tok)) { // Call until the function returns false to // handle do-while inside do-while @@ -5618,12 +4833,9 @@ void Tokenizer::simplifyCompoundAssignment() { // Simplify compound assignments: // "a+=b" => "a = a + b" - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] (") || Token::Match(tok, "[;{}:] *| (| %var%")) - { - if (tok->str() == ":") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] (") || Token::Match(tok, "[;{}:] *| (| %var%")) { + if (tok->str() == ":") { if (tok->strAt(-2) != "case") continue; } @@ -5634,21 +4846,16 @@ void Tokenizer::simplifyCompoundAssignment() if (tok->strAt(1) == "*") tok = tok->next(); - if (tok->strAt(1) == "(") - { + if (tok->strAt(1) == "(") { tok = tok->next()->link()->next(); - } - else - { + } else { // variable.. tok = tok->tokAt(2); while (Token::Match(tok, ". %var%") || - Token::Match(tok, "[|(")) - { + Token::Match(tok, "[|(")) { if (tok->str() == ".") tok = tok->tokAt(2); - else - { + else { // goto "]" or ")" tok = tok->link(); @@ -5667,8 +4874,7 @@ void Tokenizer::simplifyCompoundAssignment() op = str.substr(0, 1); else if (str=="<<=" || str==">>=") op = str.substr(0, 2); - else - { + else { tok = tok1; continue; } @@ -5677,28 +4883,21 @@ void Tokenizer::simplifyCompoundAssignment() if (Token::Match(tok, "+=|-= 0 ;") || Token::Match(tok, "+=|-= '\\0' ;") || Token::simpleMatch(tok, "|= 0 ;") || - Token::Match(tok, "*=|/= 1 ;")) - { + Token::Match(tok, "*=|/= 1 ;")) { tok = tok1; while (tok->next()->str() != ";") tok->deleteNext(); - } - else - { + } else { // Enclose the rhs in parantheses.. - if (!Token::Match(tok->next(), "%any% [;)]")) - { + if (!Token::Match(tok->next(), "%any% [;)]")) { // Only enclose rhs in parantheses if there is some operator bool someOperator = false; - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); - if (Token::Match(tok2->next(), "[;)]")) - { - if (someOperator) - { + if (Token::Match(tok2->next(), "[;)]")) { + if (someOperator) { tok->insertToken("("); tok2->insertToken(")"); Token::createMutualLinks(tok->next(), tok2->next()); @@ -5715,14 +4914,12 @@ void Tokenizer::simplifyCompoundAssignment() tok->insertToken(op); std::stack tokend; - for (const Token *tok2 = tok->previous(); tok2 && tok2 != tok1; tok2 = tok2->previous()) - { + for (const Token *tok2 = tok->previous(); tok2 && tok2 != tok1; tok2 = tok2->previous()) { tok->insertToken(tok2->str()); tok->next()->varId(tok2->varId()); if (Token::Match(tok->next(), "]|)")) tokend.push(tok->next()); - else if (Token::Match(tok->next(), "(|[")) - { + else if (Token::Match(tok->next(), "(|[")) { Token::createMutualLinks(tok->next(), tokend.top()); tokend.pop(); } @@ -5735,27 +4932,22 @@ void Tokenizer::simplifyCompoundAssignment() void Tokenizer::simplifyConditionOperator() { int parlevel = 0; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "(") ++parlevel; else if (tok->str() == ")") --parlevel; else if (parlevel == 0 && (Token::Match(tok, ";|{|} *| %any% = %any% ? %any% : %any% ;") || - Token::Match(tok, ";|{|} return %any% ? %any% : %any% ;"))) - { + Token::Match(tok, ";|{|} return %any% ? %any% : %any% ;"))) { std::string var(tok->strAt(1)); bool isPointer = false; bool isReturn = false; int offset = 0; - if (tok->next()->str() == "*") - { + if (tok->next()->str() == "*") { tok = tok->next(); var += " " + tok->strAt(1); isPointer = true; - } - else if (tok->next()->str() == "return") - { + } else if (tok->next()->str() == "return") { isReturn = true; offset = -1; } @@ -5764,12 +4956,10 @@ void Tokenizer::simplifyConditionOperator() const std::string value1(tok->strAt(5 + offset)); const std::string value2(tok->strAt(7 + offset)); - if (isPointer) - { + if (isPointer) { tok = tok->previous(); Token::eraseTokens(tok, tok->tokAt(10)); - } - else if (isReturn) + } else if (isReturn) Token::eraseTokens(tok, tok->tokAt(7)); else Token::eraseTokens(tok, tok->tokAt(9)); @@ -5783,16 +4973,12 @@ void Tokenizer::simplifyConditionOperator() str = "if ( condition ) { var = value1 ; } else { var = value2 ; }"; std::string::size_type pos1 = 0; - while (pos1 != std::string::npos) - { + while (pos1 != std::string::npos) { std::string::size_type pos2 = str.find(" ", pos1); - if (pos2 == std::string::npos) - { + if (pos2 == std::string::npos) { tok->insertToken(str.substr(pos1).c_str()); pos1 = pos2; - } - else - { + } else { tok->insertToken(str.substr(pos1, pos2 - pos1).c_str()); pos1 = pos2 + 1; } @@ -5801,12 +4987,10 @@ void Tokenizer::simplifyConditionOperator() // set links. if (tok->str() == "(" || tok->str() == "{") starttok = tok; - else if (starttok && (tok->str() == ")" || tok->str() == "}")) - { + else if (starttok && (tok->str() == ")" || tok->str() == "}")) { Token::createMutualLinks(starttok, tok); starttok = 0; - } - else if (tok->str() == "condition") + } else if (tok->str() == "condition") tok->str(condition); else if (tok->str() == "var") tok->str(var); @@ -5823,10 +5007,8 @@ bool Tokenizer::simplifyConditions() { bool ret = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "! %num%") || Token::Match(tok, "! %bool%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "! %num%") || Token::Match(tok, "! %bool%")) { if (tok->next()->str() == "0" || tok->next()->str() == "false") tok->str("true"); else @@ -5838,43 +5020,37 @@ bool Tokenizer::simplifyConditions() if (Token::simpleMatch(tok, "( true &&") || Token::simpleMatch(tok, "&& true &&") || - Token::simpleMatch(tok->next(), "&& true )")) - { + Token::simpleMatch(tok->next(), "&& true )")) { Token::eraseTokens(tok, tok->tokAt(3)); ret = true; } else if (Token::simpleMatch(tok, "( false ||") || Token::simpleMatch(tok, "|| false ||") || - Token::simpleMatch(tok->next(), "|| false )")) - { + Token::simpleMatch(tok->next(), "|| false )")) { Token::eraseTokens(tok, tok->tokAt(3)); ret = true; } else if (Token::simpleMatch(tok, "( true ||") || - Token::simpleMatch(tok, "( false &&")) - { + Token::simpleMatch(tok, "( false &&")) { Token::eraseTokens(tok->next(), tok->link()); ret = true; } else if (Token::simpleMatch(tok, "|| true )") || - Token::simpleMatch(tok, "&& false )")) - { + Token::simpleMatch(tok, "&& false )")) { tok = tok->next(); Token::eraseTokens(tok->next()->link(), tok); ret = true; } // Change numeric constant in condition to "true" or "false" - if (Token::Match(tok, "if|while ( %num% )|%oror%|&&")) - { + if (Token::Match(tok, "if|while ( %num% )|%oror%|&&")) { tok->tokAt(2)->str((tok->tokAt(2)->str() != "0") ? "true" : "false"); ret = true; } - if (Token::Match(tok, "&&|%oror% %num% )|%oror%|&&")) - { + if (Token::Match(tok, "&&|%oror% %num% )|%oror%|&&")) { tok->next()->str((tok->next()->str() != "0") ? "true" : "false"); ret = true; } @@ -5883,16 +5059,13 @@ bool Tokenizer::simplifyConditions() if (Token::Match(tok, "&&|%oror%|(") && (Token::Match(tok->tokAt(1), "%num% %any% %num%") || Token::Match(tok->tokAt(1), "%bool% %any% %bool%")) && - Token::Match(tok->tokAt(4), "&&|%oror%|)|?")) - { + Token::Match(tok->tokAt(4), "&&|%oror%|)|?")) { std::string cmp = tok->strAt(2); bool result = false; - if (Token::Match(tok->tokAt(1), "%num%")) - { + if (Token::Match(tok->tokAt(1), "%num%")) { // Compare numbers - if (cmp == "==" || cmp == "!=") - { + if (cmp == "==" || cmp == "!=") { const std::string op1(tok->strAt(1)); const std::string op2(tok->strAt(3)); @@ -5906,9 +5079,7 @@ bool Tokenizer::simplifyConditions() result = eq; else result = !eq; - } - else - { + } else { double op1 = MathLib::toDoubleNumber(tok->strAt(1)); double op2 = MathLib::toDoubleNumber(tok->strAt(3)); if (cmp == ">=") @@ -5922,9 +5093,7 @@ bool Tokenizer::simplifyConditions() else cmp = ""; } - } - else - { + } else { // Compare boolean bool op1 = (tok->strAt(1) == std::string("true")); bool op2 = (tok->strAt(3) == std::string("true")); @@ -5945,8 +5114,7 @@ bool Tokenizer::simplifyConditions() cmp = ""; } - if (! cmp.empty()) - { + if (! cmp.empty()) { tok = tok->next(); tok->deleteNext(); tok->deleteNext(); @@ -5963,8 +5131,7 @@ bool Tokenizer::simplifyConditions() bool Tokenizer::simplifyQuestionMark() { bool ret = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "?") continue; @@ -5982,18 +5149,14 @@ bool Tokenizer::simplifyQuestionMark() Token *semicolon = 0; { unsigned int parlevel = 0; - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel == 0) break; --parlevel; - } - else if (parlevel == 0 && tok2->str() == ":") - { + } else if (parlevel == 0 && tok2->str() == ":") { semicolon = tok2; break; } @@ -6003,8 +5166,7 @@ bool Tokenizer::simplifyQuestionMark() continue; if (tok->previous()->str() == "false" || - tok->previous()->str() == "0") - { + tok->previous()->str() == "0") { // Use code after semicolon, remove code before it. semicolon = semicolon->next(); tok = tok->tokAt(-2); @@ -6015,13 +5177,11 @@ bool Tokenizer::simplifyQuestionMark() } // The condition is true. Delete the operator after the ":".. - else - { + else { const Token *end = 0; // check the operator after the : - if (Token::simpleMatch(semicolon, ": (")) - { + if (Token::simpleMatch(semicolon, ": (")) { end = semicolon->next()->link(); if (!Token::Match(end, ") !!.")) continue; @@ -6032,32 +5192,26 @@ bool Tokenizer::simplifyQuestionMark() Token::eraseTokens(tok, tok->tokAt(3)); // delete operator after the : - if (end) - { + if (end) { Token::eraseTokens(semicolon->previous(), end->next()); continue; } int ind = 0; - for (const Token *endTok = semicolon; endTok; endTok = endTok->next()) - { - if (endTok->str() == ";") - { + for (const Token *endTok = semicolon; endTok; endTok = endTok->next()) { + if (endTok->str() == ";") { Token::eraseTokens(semicolon->previous(), endTok); ret = true; break; } - else if (Token::Match(endTok, "[({[]")) - { + else if (Token::Match(endTok, "[({[]")) { ++ind; } - else if (Token::Match(endTok, "[)}]]")) - { + else if (Token::Match(endTok, "[)}]]")) { --ind; - if (ind < 0) - { + if (ind < 0) { Token::eraseTokens(semicolon->previous(), endTok); ret = true; break; @@ -6072,12 +5226,10 @@ bool Tokenizer::simplifyQuestionMark() void Tokenizer::simplifyCasts() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // #2897 : don't remove cast in such cases: // *((char *)a + 1) = 0; - if (!tok->isName() && Token::simpleMatch(tok->next(), "* (")) - { + if (!tok->isName() && Token::simpleMatch(tok->next(), "* (")) { tok = tok->tokAt(2)->link(); continue; } @@ -6085,8 +5237,7 @@ void Tokenizer::simplifyCasts() while (Token::Match(tok->next(), "( %type% *| ) *|&| %var%") || Token::Match(tok->next(), "( %type% %type% *| ) *|&| %var%") || (!tok->isName() && (Token::Match(tok->next(), "( %type% * ) (") || - Token::Match(tok->next(), "( %type% %type% * ) (")))) - { + Token::Match(tok->next(), "( %type% %type% * ) (")))) { if (tok->isName() && tok->str() != "return") break; @@ -6096,8 +5247,7 @@ void Tokenizer::simplifyCasts() // Remove cast.. Token::eraseTokens(tok, tok->next()->link()->next()); - if (tok->str() == ")" && tok->link()->previous()) - { + if (tok->str() == ")" && tok->link()->previous()) { // If there was another cast before this, go back // there to check it also. e.g. "(int)(char)x" tok = tok->link()->previous(); @@ -6106,27 +5256,22 @@ void Tokenizer::simplifyCasts() // Replace pointer casts of 0.. "(char *)0" => "0" while (Token::Match(tok->next(), "( %type% * ) 0") || - Token::Match(tok->next(), "( %type% %type% * ) 0")) - { + Token::Match(tok->next(), "( %type% %type% * ) 0")) { Token::eraseTokens(tok, tok->next()->link()->next()); - if (tok->str() == ")" && tok->link()->previous()) - { + if (tok->str() == ")" && tok->link()->previous()) { // If there was another cast before this, go back // there to check it also. e.g. "(char*)(char*)0" tok = tok->link()->previous(); } } - while (Token::Match(tok->next(), "dynamic_cast|reinterpret_cast|const_cast|static_cast <")) - { + while (Token::Match(tok->next(), "dynamic_cast|reinterpret_cast|const_cast|static_cast <")) { Token *tok2 = tok->next(); unsigned int level = 0; - while (tok2) - { + while (tok2) { if (tok2->str() == "<") ++level; - else if (tok2->str() == ">") - { + else if (tok2->str() == ">") { --level; if (level == 0) break; @@ -6134,21 +5279,15 @@ void Tokenizer::simplifyCasts() tok2 = tok2->next(); } - if (Token::simpleMatch(tok2, "> (")) - { + if (Token::simpleMatch(tok2, "> (")) { Token *closeBracket = tok2->next()->link(); - if (closeBracket) - { + if (closeBracket) { Token::eraseTokens(tok, tok2->tokAt(2)); closeBracket->deleteThis(); - } - else - { + } else { break; } - } - else - { + } else { break; } } @@ -6158,10 +5297,8 @@ void Tokenizer::simplifyCasts() void Tokenizer::simplifyFunctionParameters() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "{" || tok->str() == "[" || tok->str() == "(") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "{" || tok->str() == "[" || tok->str() == "(") { tok = tok->link(); if (!tok) break; @@ -6169,8 +5306,7 @@ void Tokenizer::simplifyFunctionParameters() } // Find the function e.g. foo( x ) or foo( x, y ) - if (Token::Match(tok, "%var% ( %var% [,)]")) - { + if (Token::Match(tok, "%var% ( %var% [,)]")) { // We have found old style function, now we need to change it // backup pointer to the '(' token @@ -6179,16 +5315,13 @@ void Tokenizer::simplifyFunctionParameters() // Get list of argument names std::map argumentNames; bool bailOut = false; - for (tok = tok->tokAt(2); tok; tok = tok->tokAt(2)) - { - if (!Token::Match(tok, "%var% [,)]")) - { + for (tok = tok->tokAt(2); tok; tok = tok->tokAt(2)) { + if (!Token::Match(tok, "%var% [,)]")) { bailOut = true; break; } - if (argumentNames.find(tok->str()) != argumentNames.end()) - { + if (argumentNames.find(tok->str()) != argumentNames.end()) { // Invalid code, two arguments with the same name. // TODO, print error perhaps? bailOut = true; @@ -6196,15 +5329,13 @@ void Tokenizer::simplifyFunctionParameters() } argumentNames[tok->str()] = tok; - if (tok->next()->str() == ")") - { + if (tok->next()->str() == ")") { tok = tok->tokAt(2); break; } } - if (bailOut) - { + if (bailOut) { tok = tok1->link(); if (!tok) return; @@ -6212,16 +5343,13 @@ void Tokenizer::simplifyFunctionParameters() } Token *start = tok; - while (tok && tok->str() != "{") - { - if (tok->str() == ";") - { + while (tok && tok->str() != "{") { + if (tok->str() == ";") { tok = tok->previous(); // Move tokens from start to tok into the place of // argumentNames[tok->str()] and remove the ";" - if (argumentNames.find(tok->str()) == argumentNames.end()) - { + if (argumentNames.find(tok->str()) == argumentNames.end()) { bailOut = true; break; } @@ -6235,9 +5363,7 @@ void Tokenizer::simplifyFunctionParameters() argumentNames.erase(tok->str()); tok = temp; start = tok; - } - else - { + } else { tok = tok->next(); } } @@ -6245,13 +5371,11 @@ void Tokenizer::simplifyFunctionParameters() if (Token::simpleMatch(tok, "{")) tok = tok->link(); - if (tok == NULL) - { + if (tok == NULL) { break; } - if (bailOut) - { + if (bailOut) { continue; } } @@ -6261,12 +5385,10 @@ void Tokenizer::simplifyFunctionParameters() void Tokenizer:: simplifyFunctionPointers() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // #2873 - dont simplify function pointer usage here: // (void)(xy(*p)(0)); - if (Token::simpleMatch(tok, ") (")) - { + if (Token::simpleMatch(tok, ") (")) { tok = tok->next()->link(); continue; } @@ -6275,8 +5397,7 @@ void Tokenizer:: simplifyFunctionPointers() if (Token::Match(tok, "( %type% *| *| ( * ) (") || Token::Match(tok, "( %type% %type% *| *| ( * ) (") || Token::Match(tok, "static_cast < %type% *| *| ( * ) (") || - Token::Match(tok, "static_cast < %type% %type% *| *| ( * ) (")) - { + Token::Match(tok, "static_cast < %type% %type% *| *| ( * ) (")) { Token *tok1 = tok; if (tok1->str() == "static_cast") @@ -6333,21 +5454,17 @@ bool Tokenizer::simplifyFunctionReturn() { bool ret = false; int indentlevel = 0; - for (const Token *tok = tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokens(); tok; tok = tok->next()) { if (tok->str() == "{") ++indentlevel; else if (tok->str() == "}") --indentlevel; - else if (indentlevel == 0 && Token::Match(tok, "%var% ( ) { return %num% ; }") && tok->str() != ")") - { + else if (indentlevel == 0 && Token::Match(tok, "%var% ( ) { return %num% ; }") && tok->str() != ")") { const std::string pattern("(|[|=|%op% " + tok->str() + " ( ) ;|]|)|%op%"); - for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) - { - if (Token::Match(tok2, pattern.c_str())) - { + for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) { + if (Token::Match(tok2, pattern.c_str())) { tok2 = tok2->next(); tok2->str(tok->strAt(5)); tok2->deleteNext(); @@ -6382,10 +5499,8 @@ void Tokenizer::simplifyVarDecl() { // Split up variable declarations.. // "int a=4;" => "int a; a=4;" - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "= {")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "= {")) { tok = tok->next()->link(); if (!tok) break; @@ -6405,8 +5520,7 @@ void Tokenizer::simplifyVarDecl() Token *tok2 = type0; unsigned int typelen = 1; - while (Token::Match(tok2, "%type% %type% *| *| %var%")) - { + while (Token::Match(tok2, "%type% %type% *| *| %var%")) { if (tok2->str() == "const") isconst = true; @@ -6426,78 +5540,62 @@ void Tokenizer::simplifyVarDecl() continue; // check for qualification.. - if (Token::Match(tok2, ":: %type%")) - { + if (Token::Match(tok2, ":: %type%")) { typelen++; tok2 = tok2->next(); } - if (Token::Match(tok2, "%type% :: %type%")) - { - while (tok2 && Token::Match(tok2, "%type% ::")) - { + if (Token::Match(tok2, "%type% :: %type%")) { + while (tok2 && Token::Match(tok2, "%type% ::")) { typelen += 2; tok2 = tok2->tokAt(2); } } - if (Token::Match(tok2, "%type% *| %var% ,|=")) - { + if (Token::Match(tok2, "%type% *| %var% ,|=")) { const bool isPointer = (tok2->next()->str() == "*"); const Token *varName = tok2->tokAt((isPointer ? 2 : 1)); Token *endDeclaration = varName->next(); - if (varName->str() != "operator") - { + if (varName->str() != "operator") { tok2 = endDeclaration; // The ',' or '=' token - if (isstatic && tok2->str() == "=") - { + if (isstatic && tok2->str() == "=") { if (Token::Match(tok2->next(), "%num% ,")) tok2 = tok2->tokAt(2); else tok2 = NULL; } - } - else + } else tok2 = NULL; } - else if (Token::Match(tok2, "%type% * * %var% ,|=")) - { + else if (Token::Match(tok2, "%type% * * %var% ,|=")) { if (tok2->tokAt(3)->str() != "operator") tok2 = tok2->tokAt(4); // The ',' token else tok2 = NULL; } - else if (Token::Match(tok2, "%type% * const %var% ,|=")) - { - if (tok2->tokAt(3)->str() != "operator") - { + else if (Token::Match(tok2, "%type% * const %var% ,|=")) { + if (tok2->tokAt(3)->str() != "operator") { tok2 = tok2->tokAt(4); // The ',' token - } - else - { + } else { tok2 = NULL; } } else if (Token::Match(tok2, "%type% %var% [ %num% ] ,|=|[") || - Token::Match(tok2, "%type% %var% [ %var% ] ,|=|[")) - { + Token::Match(tok2, "%type% %var% [ %var% ] ,|=|[")) { tok2 = tok2->tokAt(5); // The ',' token while (Token::Match(tok2, "[ %num% ]") || Token::Match(tok2, "[ %var% ]")) tok2 = tok2->tokAt(3); - if (!Token::Match(tok2, "=|,")) - { + if (!Token::Match(tok2, "=|,")) { tok2 = NULL; } - if (tok2 && tok2->str() == "=") - { - while (tok2 && tok2->str() != ",") - { + if (tok2 && tok2->str() == "=") { + while (tok2 && tok2->str() != ",") { if (tok2->str() == "{") tok2 = tok2->link(); @@ -6510,36 +5608,27 @@ void Tokenizer::simplifyVarDecl() } else if (Token::Match(tok2, "%type% * %var% [ %num% ] ,") || - Token::Match(tok2, "%type% * %var% [ %var% ] ,")) - { + Token::Match(tok2, "%type% * %var% [ %var% ] ,")) { tok2 = tok2->tokAt(6); // The ',' token } - else if (Token::Match(tok2, "%type% <")) - { + else if (Token::Match(tok2, "%type% <")) { typelen += 2; tok2 = tok2->tokAt(2); size_t indentlevel = 1; - for (Token *tok3 = tok2; tok3; tok3 = tok3->next()) - { + for (Token *tok3 = tok2; tok3; tok3 = tok3->next()) { ++typelen; - if (tok3->str() == "<") - { + if (tok3->str() == "<") { ++indentlevel; - } - else if (tok3->str() == ">") - { + } else if (tok3->str() == ">") { --indentlevel; - if (indentlevel == 0) - { + if (indentlevel == 0) { tok2 = tok3->next(); break; } - } - else if (tok3->str() == ";") - { + } else if (tok3->str() == ";") { break; } } @@ -6547,8 +5636,7 @@ void Tokenizer::simplifyVarDecl() if (!tok2) // syntax error break; - if (Token::Match(tok2, ":: %type%")) - { + if (Token::Match(tok2, ":: %type%")) { typelen += 2; tok2 = tok2->tokAt(2); } @@ -6556,68 +5644,54 @@ void Tokenizer::simplifyVarDecl() if (!tok2) // syntax error break; - if (tok2->str() == "*") - { + if (tok2->str() == "*") { tok2 = tok2->next(); } - if (Token::Match(tok2, "%var% ,|=")) - { + if (Token::Match(tok2, "%var% ,|=")) { tok2 = tok2->next(); // The ',' token typelen--; - } - else - { + } else { tok2 = NULL; typelen = 0; } - } - else - { + } else { tok2 = NULL; typelen = 0; } - if (tok2) - { - if (tok2->str() == ",") - { + if (tok2) { + if (tok2->str() == ",") { tok2->str(";"); insertTokens(tok2, type0, typelen); std::stack link1; std::stack link2; - while (((typelen--) > 0) && (0 != (tok2 = tok2->next()))) - { + while (((typelen--) > 0) && (0 != (tok2 = tok2->next()))) { if (tok2->str() == "(") link1.push(tok2); - else if (tok2->str() == ")" && !link1.empty()) - { + else if (tok2->str() == ")" && !link1.empty()) { Token::createMutualLinks(tok2, link1.top()); link1.pop(); } else if (tok2->str() == "[") link2.push(tok2); - else if (tok2->str() == "]" && !link2.empty()) - { + else if (tok2->str() == "]" && !link2.empty()) { Token::createMutualLinks(tok2, link2.top()); link2.pop(); } } } - else - { + else { Token *eq = tok2; unsigned int level = 0; - while (tok2) - { + while (tok2) { if (Token::Match(tok2, "[{(]")) tok2 = tok2->link(); - else if (tok2->str() == "<") - { + else if (tok2->str() == "<") { if (tok2->previous()->isName() && !tok2->previous()->varId()) ++level; } @@ -6625,8 +5699,7 @@ void Tokenizer::simplifyVarDecl() else if (level > 0 && tok2->str() == ">") --level; - else if (level == 0 && strchr(";,", tok2->str()[0])) - { + else if (level == 0 && strchr(";,", tok2->str()[0])) { // "type var =" => "type var; var =" Token *VarTok = type0->tokAt((int)typelen); while (Token::Match(VarTok, "*|&|const")) @@ -6635,8 +5708,7 @@ void Tokenizer::simplifyVarDecl() eq->str(";"); // "= x, " => "= x; type " - if (tok2->str() == ",") - { + if (tok2->str() == ",") { tok2->str(";"); insertTokens(tok2, type0, typelen); } @@ -6664,24 +5736,18 @@ void Tokenizer::simplifyPlatformTypes() else return; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "std :: size_t|ssize_t|ptrdiff_t|intptr_t|uintptr_t")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "std :: size_t|ssize_t|ptrdiff_t|intptr_t|uintptr_t")) { tok->deleteNext(); tok->deleteThis(); - } - else if (Token::simpleMatch(tok, ":: size_t|ssize_t|ptrdiff_t|intptr_t|uintptr_t")) - { + } else if (Token::simpleMatch(tok, ":: size_t|ssize_t|ptrdiff_t|intptr_t|uintptr_t")) { tok->deleteThis(); } - if (Token::Match(tok, "size_t|uintptr_t")) - { + if (Token::Match(tok, "size_t|uintptr_t")) { tok->str("unsigned"); - switch (type) - { + switch (type) { case isLongLong: tok->insertToken("long"); tok->insertToken("long"); @@ -6693,11 +5759,8 @@ void Tokenizer::simplifyPlatformTypes() tok->insertToken("int"); break; } - } - else if (Token::Match(tok, "ssize_t|ptrdiff_t|intptr_t")) - { - switch (type) - { + } else if (Token::Match(tok, "ssize_t|ptrdiff_t|intptr_t")) { + switch (type) { case isLongLong: tok->str("long"); tok->insertToken("long"); @@ -6714,162 +5777,110 @@ void Tokenizer::simplifyPlatformTypes() if (_settings->platformType == Settings::Win32A || _settings->platformType == Settings::Win32W || - _settings->platformType == Settings::Win64) - { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + _settings->platformType == Settings::Win64) { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "BOOL|INT|INT32")) tok->str("int"); - else if (Token::Match(tok, "BOOLEAN|BYTE|UCHAR")) - { + else if (Token::Match(tok, "BOOLEAN|BYTE|UCHAR")) { tok->str("unsigned"); tok->insertToken("char"); - } - else if (tok->str() == "CHAR") + } else if (tok->str() == "CHAR") tok->str("char"); - else if (Token::Match(tok, "DWORD|ULONG")) - { + else if (Token::Match(tok, "DWORD|ULONG")) { tok->str("unsigned"); tok->insertToken("long"); - } - else if (Token::Match(tok, "DWORD_PTR|ULONG_PTR|SIZE_T")) - { + } else if (Token::Match(tok, "DWORD_PTR|ULONG_PTR|SIZE_T")) { tok->str("unsigned"); tok->insertToken("long"); if (_settings->platformType == Settings::Win64) tok->insertToken("long"); - } - else if (tok->str() == "FLOAT") + } else if (tok->str() == "FLOAT") tok->str("float"); else if (tok->str() == "HRESULT") tok->str("long"); - else if (tok->str() == "INT64") - { + else if (tok->str() == "INT64") { tok->str("long"); tok->insertToken("long"); - } - else if (tok->str() == "LONG") + } else if (tok->str() == "LONG") tok->str("long"); - else if (tok->str() == "LONG_PTR") - { + else if (tok->str() == "LONG_PTR") { tok->str("long"); if (_settings->platformType == Settings::Win64) tok->insertToken("long"); - } - else if (Token::Match(tok, "LPBOOL|PBOOL")) - { + } else if (Token::Match(tok, "LPBOOL|PBOOL")) { tok->str("int"); tok->insertToken("*"); - } - else if (Token::Match(tok, "LPBYTE|PBOOLEAN|PBYTE")) - { + } else if (Token::Match(tok, "LPBYTE|PBOOLEAN|PBYTE")) { tok->str("unsigned"); tok->insertToken("*"); tok->insertToken("char"); - } - else if (Token::Match(tok, "LPCSTR|PCSTR")) - { + } else if (Token::Match(tok, "LPCSTR|PCSTR")) { tok->str("const"); tok->insertToken("*"); tok->insertToken("char"); - } - else if (tok->str() == "LPCVOID") - { + } else if (tok->str() == "LPCVOID") { tok->str("const"); tok->insertToken("*"); tok->insertToken("void"); - } - else if (tok->str() == "LPDWORD") - { + } else if (tok->str() == "LPDWORD") { tok->str("unsigned"); tok->insertToken("*"); tok->insertToken("long"); - } - else if (Token::Match(tok, "LPINT|PINT")) - { + } else if (Token::Match(tok, "LPINT|PINT")) { tok->str("int"); tok->insertToken("*"); - } - else if (Token::Match(tok, "LPLONG|PLONG")) - { + } else if (Token::Match(tok, "LPLONG|PLONG")) { tok->str("long"); tok->insertToken("*"); - } - else if (Token::Match(tok, "LPSTR|PSTR|PCHAR")) - { + } else if (Token::Match(tok, "LPSTR|PSTR|PCHAR")) { tok->str("char"); tok->insertToken("*"); - } - else if (Token::Match(tok, "LPVOID|PVOID|HANDLE")) - { + } else if (Token::Match(tok, "LPVOID|PVOID|HANDLE")) { tok->str("void"); tok->insertToken("*"); - } - else if (Token::Match(tok, "LPWORD|PWORD")) - { + } else if (Token::Match(tok, "LPWORD|PWORD")) { tok->str("unsigned"); tok->insertToken("*"); tok->insertToken("short"); - } - else if (tok->str() == "SHORT") + } else if (tok->str() == "SHORT") tok->str("short"); - else if (tok->str() == "UINT") - { + else if (tok->str() == "UINT") { tok->str("unsigned"); tok->insertToken("int"); - } - else if (tok->str() == "UINT_PTR") - { + } else if (tok->str() == "UINT_PTR") { tok->str("unsigned"); - if (_settings->platformType == Settings::Win64) - { + if (_settings->platformType == Settings::Win64) { tok->insertToken("long"); tok->insertToken("long"); - } - else + } else tok->insertToken("long"); - } - else if (Token::Match(tok, "USHORT|WORD|WCHAR|wchar_t")) - { + } else if (Token::Match(tok, "USHORT|WORD|WCHAR|wchar_t")) { tok->str("unsigned"); tok->insertToken("short"); - } - else if (tok->str() == "VOID") + } else if (tok->str() == "VOID") tok->str("void"); - else if (tok->str() == "TCHAR") - { + else if (tok->str() == "TCHAR") { if (_settings->platformType == Settings::Win32A) tok->str("char"); - else - { + else { tok->str("unsigned"); tok->insertToken("short"); } - } - else if (Token::Match(tok, "PTSTR|LPTSTR")) - { - if (_settings->platformType == Settings::Win32A) - { + } else if (Token::Match(tok, "PTSTR|LPTSTR")) { + if (_settings->platformType == Settings::Win32A) { tok->str("char"); tok->insertToken("*"); - } - else - { + } else { tok->str("unsigned"); tok->insertToken("*"); tok->insertToken("short"); } - } - else if (Token::Match(tok, "PCTSTR|LPCTSTR")) - { - if (_settings->platformType == Settings::Win32A) - { + } else if (Token::Match(tok, "PCTSTR|LPCTSTR")) { + if (_settings->platformType == Settings::Win32A) { tok->str("const"); tok->insertToken("*"); tok->insertToken("char"); - } - else - { + } else { tok->str("const"); tok->insertToken("*"); tok->insertToken("short"); @@ -6882,11 +5893,9 @@ void Tokenizer::simplifyPlatformTypes() void Tokenizer::simplifyStdType() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // long unsigned => unsigned long - if (Token::Match(tok, "char|short|int|long|__int8|__int16|__int32|__int64 unsigned|signed")) - { + if (Token::Match(tok, "char|short|int|long|__int8|__int16|__int32|__int64 unsigned|signed")) { std::string temp = tok->str(); tok->str(tok->next()->str()); tok->next()->str(temp); @@ -6896,8 +5905,7 @@ void Tokenizer::simplifyStdType() continue; // check if signed or unsigned specified - if (Token::Match(tok, "unsigned|signed")) - { + if (Token::Match(tok, "unsigned|signed")) { bool isUnsigned = tok->str() == "unsigned"; // unsigned i => unsigned int i @@ -6915,30 +5923,23 @@ void Tokenizer::simplifyStdType() tok->str("short"); else if (Token::simpleMatch(tok, "__int32")) tok->str("int"); - else if (Token::simpleMatch(tok, "__int64")) - { + else if (Token::simpleMatch(tok, "__int64")) { tok->str("long"); tok->isLong(true); - } - else if (Token::simpleMatch(tok, "long")) - { - if (Token::simpleMatch(tok->next(), "long")) - { + } else if (Token::simpleMatch(tok, "long")) { + if (Token::simpleMatch(tok->next(), "long")) { tok->isLong(true); tok->deleteNext(); } if (Token::simpleMatch(tok->next(), "int")) tok->deleteNext(); - else if (Token::simpleMatch(tok->next(), "double")) - { + else if (Token::simpleMatch(tok->next(), "double")) { tok->str("double"); tok->isLong(true); tok->deleteNext(); } - } - else if (Token::simpleMatch(tok, "short")) - { + } else if (Token::simpleMatch(tok, "short")) { if (Token::simpleMatch(tok->next(), "int")) tok->deleteNext(); } @@ -6949,8 +5950,7 @@ void Tokenizer::simplifyIfAssign() { // See also simplifyFunctionAssign - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (!Token::Match(tok->next(), "if|while ( !| (| %var% =") && !Token::Match(tok->next(), "if|while ( !| (| %var% . %var% =")) continue; @@ -6969,8 +5969,7 @@ void Tokenizer::simplifyIfAssign() // Delete parenthesis.. and remember how many there are with // their links. std::stack braces; - while (tok->next()->str() == "(") - { + while (tok->next()->str() == "(") { braces.push(tok->next()->link()); tok->deleteNext(); } @@ -6978,12 +5977,10 @@ void Tokenizer::simplifyIfAssign() // Skip the "%var% = ..." Token *tok2; unsigned int indentlevel = 0; - for (tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++indentlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (indentlevel == 0) break; --indentlevel; @@ -6992,16 +5989,14 @@ void Tokenizer::simplifyIfAssign() // Insert "; if|while ( .." tok2 = tok2->previous(); - if (Token::simpleMatch(tok->tokAt(2), ".")) - { + if (Token::simpleMatch(tok->tokAt(2), ".")) { tok2->insertToken(tok->strAt(3)); tok2->insertToken(tok->strAt(2)); } tok2->insertToken(tok->strAt(1)); tok2->next()->varId(tok->tokAt(1)->varId()); - while (! braces.empty()) - { + while (! braces.empty()) { tok2->insertToken("("); Token::createMutualLinks(tok2->next(), braces.top()); braces.pop(); @@ -7013,29 +6008,24 @@ void Tokenizer::simplifyIfAssign() tok2->insertToken(";"); // If it's a while loop.. insert the assignment in the loop - if (iswhile) - { + if (iswhile) { indentlevel = 0; Token *tok3 = tok2; - for (tok3 = tok2; tok3; tok3 = tok3->next()) - { + for (tok3 = tok2; tok3; tok3 = tok3->next()) { if (tok3->str() == "{") ++indentlevel; - else if (tok3->str() == "}") - { + else if (tok3->str() == "}") { if (indentlevel <= 1) break; --indentlevel; } } - if (tok3 && indentlevel == 1) - { + if (tok3 && indentlevel == 1) { tok3 = tok3->previous(); std::stack braces2; - for (tok2 = tok2->next(); tok2 && tok2 != tok; tok2 = tok2->previous()) - { + for (tok2 = tok2->next(); tok2 && tok2 != tok; tok2 = tok2->previous()) { tok3->insertToken(tok2->str()); Token *newTok = tok3->next(); @@ -7043,12 +6033,9 @@ void Tokenizer::simplifyIfAssign() newTok->linenr(tok2->linenr()); // link() newly tokens manually - if (Token::Match(newTok, "}|)|]")) - { + if (Token::Match(newTok, "}|)|]")) { braces2.push(newTok); - } - else if (Token::Match(newTok, "{|(|[")) - { + } else if (Token::Match(newTok, "{|(|[")) { Token::createMutualLinks(newTok, braces2.top()); braces2.pop(); } @@ -7061,22 +6048,18 @@ void Tokenizer::simplifyIfAssign() void Tokenizer::simplifyVariableMultipleAssign() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "%var% = %var% = %num% ;") || - Token::Match(tok, "%var% = %var% = %var% ;")) - { + Token::Match(tok, "%var% = %var% = %var% ;")) { // skip intermediate assignments Token *tok2 = tok->previous(); while (tok2 && tok2->str() == "=" && - Token::Match(tok2->previous(), "%var%")) - { + Token::Match(tok2->previous(), "%var%")) { tok2 = tok2->tokAt(-2); } - if (!tok2 || tok2->str() != ";") - { + if (!tok2 || tok2->str() != ";") { continue; } @@ -7085,8 +6068,7 @@ void Tokenizer::simplifyVariableMultipleAssign() const std::string value(valueTok->str()); tok2 = tok2->next(); - while (tok2 != stopAt) - { + while (tok2 != stopAt) { tok2->next()->insertToken(";"); tok2->next()->insertToken(value); tok2 = tok2->tokAt(4); @@ -7098,10 +6080,8 @@ void Tokenizer::simplifyVariableMultipleAssign() void Tokenizer::simplifyIfNot() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "(|&&|%oror%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "(|&&|%oror%")) { tok = tok->next(); while (tok && tok->str() == "(") tok = tok->next(); @@ -7110,29 +6090,25 @@ void Tokenizer::simplifyIfNot() break; if (Token::Match(tok, "0|false == (") || - Token::Match(tok, "0|false == %var%")) - { + Token::Match(tok, "0|false == %var%")) { tok->deleteNext(); tok->str("!"); } - else if (Token::Match(tok, "%var% == 0|false")) - { + else if (Token::Match(tok, "%var% == 0|false")) { tok->deleteNext(); tok->next()->str(tok->str()); tok->str("!"); } - else if (Token::Match(tok, "%var% .|:: %var% == 0|false")) - { + else if (Token::Match(tok, "%var% .|:: %var% == 0|false")) { tok = tok->previous(); tok->insertToken("!"); tok = tok->tokAt(4); Token::eraseTokens(tok, tok->tokAt(3)); } - else if (Token::Match(tok, "* %var% == 0|false")) - { + else if (Token::Match(tok, "* %var% == 0|false")) { tok = tok->previous(); tok->insertToken("!"); tok = tok->tokAt(3); @@ -7140,19 +6116,16 @@ void Tokenizer::simplifyIfNot() } } - else if (tok->link() && Token::Match(tok, ") == 0|false")) - { + else if (tok->link() && Token::Match(tok, ") == 0|false")) { // if( foo(x) == 0 ) - if (Token::Match(tok->link()->tokAt(-2), "( %var%")) - { + if (Token::Match(tok->link()->tokAt(-2), "( %var%")) { Token::eraseTokens(tok, tok->tokAt(3)); tok->link()->previous()->insertToken(tok->link()->previous()->str().c_str()); tok->link()->previous()->previous()->str("!"); } // if( (x) == 0 ) - else if (Token::simpleMatch(tok->link()->previous(), "(")) - { + else if (Token::simpleMatch(tok->link()->previous(), "(")) { Token::eraseTokens(tok, tok->tokAt(3)); tok->link()->insertToken("("); tok->link()->str("!"); @@ -7167,20 +6140,16 @@ void Tokenizer::simplifyIfNot() void Tokenizer::simplifyIfNotNull() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { Token *deleteFrom = NULL; // Remove 'x = (x != 0)' - if (Token::simpleMatch(tok, "= (")) - { - if (Token::Match(tok->tokAt(-2), "[;{}] %var%")) - { + if (Token::simpleMatch(tok, "= (")) { + if (Token::Match(tok->tokAt(-2), "[;{}] %var%")) { const std::string varname(tok->previous()->str()); if (Token::Match(tok->tokAt(2), (varname + " != 0 ) ;").c_str()) || - Token::Match(tok->tokAt(2), ("0 != " + varname + " ) ;").c_str())) - { + Token::Match(tok->tokAt(2), ("0 != " + varname + " ) ;").c_str())) { tok = tok->tokAt(-2); Token::eraseTokens(tok, tok->tokAt(9)); } @@ -7188,42 +6157,36 @@ void Tokenizer::simplifyIfNotNull() continue; } - if (Token::Match(tok, "(|&&|%oror%")) - { + if (Token::Match(tok, "(|&&|%oror%")) { tok = tok->next(); if (!tok) break; if (Token::simpleMatch(tok, "0 != (") || - Token::Match(tok, "0 != %var%")) - { + Token::Match(tok, "0 != %var%")) { deleteFrom = tok->previous(); if (tok->tokAt(2)) tok->tokAt(2)->isPointerCompare(true); } - else if (Token::Match(tok, "%var% != 0")) - { + else if (Token::Match(tok, "%var% != 0")) { deleteFrom = tok; tok->isPointerCompare(true); } - else if (Token::Match(tok, "%var% .|:: %var% != 0")) - { + else if (Token::Match(tok, "%var% .|:: %var% != 0")) { tok = tok->tokAt(2); deleteFrom = tok; tok->isPointerCompare(true); } } - else if (tok->link() && Token::simpleMatch(tok, ") != 0")) - { + else if (tok->link() && Token::simpleMatch(tok, ") != 0")) { deleteFrom = tok; } - if (deleteFrom) - { + if (deleteFrom) { Token::eraseTokens(deleteFrom, deleteFrom->tokAt(3)); tok = deleteFrom; } @@ -7234,20 +6197,16 @@ void Tokenizer::simplifyIfNotNull() void Tokenizer::simplifyIfSameInnerCondition() { // same inner condition - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "if ( %var% ) {")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "if ( %var% ) {")) { const unsigned int varid(tok->tokAt(2)->varId()); if (!varid) continue; - for (Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { if (tok2->str() == "{" || tok2->str() == "}") break; - if (Token::simpleMatch(tok2, "if (")) - { + if (Token::simpleMatch(tok2, "if (")) { tok2 = tok2->tokAt(2); if (Token::Match(tok2, "%varid% )", varid)) tok2->str("true"); @@ -7268,39 +6227,30 @@ bool Tokenizer::simplifyLogicalOperators() // "if (not p)" => "if (!p)" // "if (p and q)" => "if (p && q)" // "if (p or q)" => "if (p || q)" - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "if|while ( not|compl %var%")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "if|while ( not|compl %var%")) { tok->tokAt(2)->str(tok->strAt(2) == "not" ? "!" : "~"); ret = true; - } - else if (Token::Match(tok, "&& not|compl %var%")) - { + } else if (Token::Match(tok, "&& not|compl %var%")) { tok->next()->str(tok->strAt(1) == "not" ? "!" : "~"); ret = true; - } - else if (Token::Match(tok, "|| not|compl %var%")) - { + } else if (Token::Match(tok, "|| not|compl %var%")) { tok->next()->str(tok->strAt(1) == "not" ? "!" : "~"); ret = true; } // "%var%|) and %var%|(" - else if (Token::Match(tok->previous(), "%any% %var% %any%")) - { + else if (Token::Match(tok->previous(), "%any% %var% %any%")) { if (!Token::Match(tok, "and|or|bitand|bitor|xor|not_eq")) continue; const Token *tok2 = tok; - while (0 != (tok2 = tok2->previous())) - { + while (0 != (tok2 = tok2->previous())) { if (tok2->str() == ")") tok2 = tok2->link(); else if (Token::Match(tok2, "(|;|{|}")) break; } - if (tok2 && Token::Match(tok2->previous(), "if|while (")) - { + if (tok2 && Token::Match(tok2->previous(), "if|while (")) { if (tok->str() == "and") tok->str("&&"); else if (tok->str() == "or") @@ -7324,25 +6274,20 @@ bool Tokenizer::simplifyLogicalOperators() // int i(0), j; => int i; i = 0; int j; void Tokenizer::simplifyInitVar() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (!tok->isName() || (tok->previous() && !Token::Match(tok->previous(), "[;{}]"))) continue; if (Token::Match(tok, "class|struct|union| %type% *| %var% ( &| %any% ) ;") || - Token::Match(tok, "%type% *| %var% ( %type% (")) - { + Token::Match(tok, "%type% *| %var% ( %type% (")) { tok = initVar(tok); - } - else if (Token::Match(tok, "class|struct|union| %type% *| %var% ( &| %any% ) ,")) - { + } else if (Token::Match(tok, "class|struct|union| %type% *| %var% ( &| %any% ) ,")) { Token *tok1 = tok; while (tok1->str() != ",") tok1 = tok1->next(); tok1->str(";"); Token *tok2 = tok; - if (Token::Match(tok2, "class|struct|union")) - { + if (Token::Match(tok2, "class|struct|union")) { tok1->insertToken(tok2->str()); tok1 = tok1->next(); tok2 = tok2->next(); @@ -7350,8 +6295,7 @@ void Tokenizer::simplifyInitVar() tok1->insertToken(tok2->str()); tok1 = tok1->next(); tok2 = tok2->next(); - if (tok2->str() == "*") - { + if (tok2->str() == "*") { tok1->insertToken("*"); } tok = initVar(tok); @@ -7362,14 +6306,12 @@ void Tokenizer::simplifyInitVar() Token * Tokenizer::initVar(Token * tok) { // call constructor of class => no simplification - if (Token::Match(tok, "class|struct|union")) - { + if (Token::Match(tok, "class|struct|union")) { if (tok->tokAt(2)->str() != "*") return tok; tok = tok->next(); - } - else if (!tok->isStandardType() && tok->tokAt(1)->str() != "*") + } else if (!tok->isStandardType() && tok->tokAt(1)->str() != "*") return tok; // goto variable name.. @@ -7415,15 +6357,11 @@ bool Tokenizer::simplifyKnownVariables() // constants.. { std::map constantValues; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->isName() && Token::Match(tok, "static| const| static| %type% const| %var% = %any% ;")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->isName() && Token::Match(tok, "static| const| static| %type% const| %var% = %any% ;")) { bool isconst = false; - for (const Token *tok2 = tok; tok2->str() != "="; tok2 = tok2->next()) - { - if (tok2->str() == "const") - { + for (const Token *tok2 = tok; tok2->str() != "="; tok2 = tok2->next()) { + if (tok2->str() == "const") { isconst = true; break; } @@ -7445,8 +6383,7 @@ bool Tokenizer::simplifyKnownVariables() const Token * const vartok = (tok->strAt(1) == "const") ? tok->tokAt(2) : tok->next(); const Token * const valuetok = vartok->tokAt(2); - if (valuetok->isNumber() || Token::Match(valuetok, "%str% ;")) - { + if (valuetok->isNumber() || Token::Match(valuetok, "%str% ;")) { constantValues[vartok->varId()] = valuetok->str(); // remove statement @@ -7456,8 +6393,7 @@ bool Tokenizer::simplifyKnownVariables() } } - else if (tok->varId() && constantValues.find(tok->varId()) != constantValues.end()) - { + else if (tok->varId() && constantValues.find(tok->varId()) != constantValues.end()) { tok->str(constantValues[tok->varId()]); } } @@ -7467,8 +6403,7 @@ bool Tokenizer::simplifyKnownVariables() std::set floatvars; // auto variables.. - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // Search for a block of code if (! Token::Match(tok, ") const| {")) continue; @@ -7476,18 +6411,15 @@ bool Tokenizer::simplifyKnownVariables() // parse the block of code.. int indentlevel = 0; Token *tok2 = tok; - for (; tok2; tok2 = tok2->next()) - { - if (Token::Match(tok2, "[;{}] float|double %var% ;")) - { + for (; tok2; tok2 = tok2->next()) { + if (Token::Match(tok2, "[;{}] float|double %var% ;")) { floatvars.insert(tok2->tokAt(2)->varId()); } if (tok2->str() == "{") ++indentlevel; - else if (tok2->str() == "}") - { + else if (tok2->str() == "}") { --indentlevel; if (indentlevel <= 0) break; @@ -7502,15 +6434,13 @@ bool Tokenizer::simplifyKnownVariables() Token::Match(tok2, "%var% = %bool% ;") || Token::Match(tok2, "%var% = %var% ;") || Token::Match(tok2, "%var% = & %var% ;") || - Token::Match(tok2, "%var% = & %var% [ 0 ] ;"))) - { + Token::Match(tok2, "%var% = & %var% [ 0 ] ;"))) { const unsigned int varid = tok2->varId(); if (varid == 0) continue; // skip loop variable - if (Token::Match(tok2->tokAt(-2), "(|:: %type%")) - { + if (Token::Match(tok2->tokAt(-2), "(|:: %type%")) { const Token *tok3 = tok2->previous(); while (Token::Match(tok3->previous(), ":: %type%")) tok3 = tok3->tokAt(-2); @@ -7540,8 +6470,7 @@ bool Tokenizer::simplifyKnownVariables() ret |= simplifyKnownVariablesSimplify(&tok2, tok3, varid, structname, value, valueVarId, valueIsPointer, valueToken, indentlevel); } - else if (Token::Match(tok2, "strcpy ( %var% , %str% ) ;")) - { + else if (Token::Match(tok2, "strcpy ( %var% , %str% ) ;")) { const unsigned int varid(tok2->tokAt(2)->varId()); if (varid == 0) continue; @@ -7569,23 +6498,18 @@ bool Tokenizer::simplifyKnownVariablesGetData(unsigned int varid, Token **_tok2, Token *tok2 = *_tok2; Token *tok3 = *_tok3; - if (Token::Match(tok2->tokAt(-2), "for ( %varid% = %num% ; %varid% <|<= %num% ; ++| %varid% ++| ) {", varid)) - { + if (Token::Match(tok2->tokAt(-2), "for ( %varid% = %num% ; %varid% <|<= %num% ; ++| %varid% ++| ) {", varid)) { // is there a "break" in the for loop? bool hasbreak = false; unsigned int indentlevel4 = 0; // indentlevel for tok4 - for (const Token *tok4 = tok2->previous()->link(); tok4; tok4 = tok4->next()) - { + for (const Token *tok4 = tok2->previous()->link(); tok4; tok4 = tok4->next()) { if (tok4->str() == "{") ++indentlevel4; - else if (tok4->str() == "}") - { + else if (tok4->str() == "}") { if (indentlevel4 <= 1) break; --indentlevel4; - } - else if (tok4->str() == "break") - { + } else if (tok4->str() == "break") { hasbreak = true; break; } @@ -7595,28 +6519,21 @@ bool Tokenizer::simplifyKnownVariablesGetData(unsigned int varid, Token **_tok2, // no break => the value of the counter value is known after the for loop.. const std::string compareop = tok2->strAt(5); - if (compareop == "<") - { + if (compareop == "<") { value = tok2->strAt(6); valueVarId = tok2->tokAt(6)->varId(); - } - else + } else value = MathLib::toString(MathLib::toLongNumber(tok2->strAt(6)) + 1); // Skip for-body.. tok3 = tok2->previous()->link()->next()->link()->next(); - } - else - { + } else { value = tok2->strAt(2); valueVarId = tok2->tokAt(2)->varId(); - if (Token::simpleMatch(tok2->next(), "[")) - { + if (Token::simpleMatch(tok2->next(), "[")) { value = tok2->next()->link()->strAt(2); valueVarId = 0; - } - else if (value == "&") - { + } else if (value == "&") { value = tok2->strAt(3); valueVarId = tok2->tokAt(3)->varId(); @@ -7630,8 +6547,7 @@ bool Tokenizer::simplifyKnownVariablesGetData(unsigned int varid, Token **_tok2, // float value should contain a "." else if (tok2->tokAt(2)->isNumber() && floatvar && - value.find(".") == std::string::npos) - { + value.find(".") == std::string::npos) { value += ".0"; } @@ -7654,20 +6570,14 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign Token* bailOutFromLoop = 0; int indentlevel3 = indentlevel; bool ret3 = false; - for (; tok3; tok3 = tok3->next()) - { - if (tok3->str() == "{") - { + for (; tok3; tok3 = tok3->next()) { + if (tok3->str() == "{") { ++indentlevel3; - } - else if (tok3->str() == "}") - { + } else if (tok3->str() == "}") { --indentlevel3; - if (indentlevel3 < indentlevel) - { + if (indentlevel3 < indentlevel) { if (Token::Match((*tok2)->tokAt(-7), "%type% * %var% ; %var% = & %var% ;") && - (*tok2)->tokAt(-5)->str() == (*tok2)->tokAt(-3)->str()) - { + (*tok2)->tokAt(-5)->str() == (*tok2)->tokAt(-3)->str()) { (*tok2) = (*tok2)->tokAt(-4); Token::eraseTokens((*tok2), (*tok2)->tokAt(5)); } @@ -7683,26 +6593,21 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign valueToken->next() && valueToken->next()->isName() && tok3->str() == valueToken->next()->str() && - tok3->varId() > valueToken->next()->varId()) - { + tok3->varId() > valueToken->next()->varId()) { // more checking if this is a variable declaration bool decl = true; - for (const Token *tok4 = tok3->previous(); tok4; tok4 = tok4->previous()) - { + for (const Token *tok4 = tok3->previous(); tok4; tok4 = tok4->previous()) { if (Token::Match(tok4, "[;{}]")) break; - else if (tok4->isName()) - { - if (tok4->varId() > 0) - { + else if (tok4->isName()) { + if (tok4->varId() > 0) { decl = false; break; } } - else if (!Token::Match(tok4, "[&*]")) - { + else if (!Token::Match(tok4, "[&*]")) { decl = false; break; } @@ -7741,17 +6646,14 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign break; // Stop if something like 'while (--var)' is found - if (tok3->str() == "for" || tok3->str() == "while" || tok3->str() == "do") - { + if (tok3->str() == "for" || tok3->str() == "while" || tok3->str() == "do") { const Token *endpar = tok3->next()->link(); if (Token::simpleMatch(endpar, ") {")) endpar = endpar->next()->link(); bool bailout = false; - for (const Token *tok4 = tok3; tok4 && tok4 != endpar; tok4 = tok4->next()) - { + for (const Token *tok4 = tok3; tok4 && tok4 != endpar; tok4 = tok4->next()) { if (Token::Match(tok4, "++|-- %varid%", varid) || - Token::Match(tok4, "%varid% ++|--|=", varid)) - { + Token::Match(tok4, "%varid% ++|--|=", varid)) { bailout = true; break; } @@ -7760,28 +6662,22 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign break; } - if (bailOutFromLoop) - { + if (bailOutFromLoop) { // This could be a loop, skip it, but only if it doesn't contain // the variable we are checking for. If it contains the variable // we will bail out. - if (tok3->varId() == varid) - { + if (tok3->varId() == varid) { // Continue //tok2 = bailOutFromLoop; break; - } - else if (tok3 == bailOutFromLoop) - { + } else if (tok3 == bailOutFromLoop) { // We have skipped the loop bailOutFromLoop = 0; continue; } continue; - } - else if (tok3->str() == "{" && tok3->previous()->str() == ")") - { + } else if (tok3->str() == "{" && tok3->previous()->str() == ")") { // There is a possible loop after the assignment. Try to skip it. if (tok3->previous()->link() && !Token::simpleMatch(tok3->previous()->link()->previous(), "if")) @@ -7792,27 +6688,23 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign // Variable used in realloc (see Ticket #1649) if (Token::Match(tok3, "%var% = realloc ( %var% ,") && tok3->varId() == varid && - tok3->tokAt(4)->varId() == varid) - { + tok3->tokAt(4)->varId() == varid) { tok3->tokAt(4)->str(value); ret = true; } // condition "(|&&|%OROR% %varid% )|&&|%OROR% if (!Token::Match(tok3->previous(), "( %var% )") && - Token::Match(tok3->previous(), "&&|(|%oror% %varid% &&|%oror%|)", varid)) - { + Token::Match(tok3->previous(), "&&|(|%oror% %varid% &&|%oror%|)", varid)) { tok3->str(value); ret = true; } // Variable is used somehow in a non-defined pattern => bail out - if (tok3->varId() == varid) - { + if (tok3->varId() == varid) { // This is a really generic bailout so let's try to avoid this. // There might be lots of false negatives. - if (_settings->debugwarnings) - { + if (_settings->debugwarnings) { // FIXME: Fix all the debug warnings for values and then // remove this bailout if (pointeralias) @@ -7865,21 +6757,17 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign if (Token::Match(tok3->previous(), ("if ( " + structname + " %varid% ==|!=|<|<=|>|>=|)").c_str(), varid) || Token::Match(tok3, ("( " + structname + " %varid% ==|!=|<|<=|>|>=").c_str(), varid) || Token::Match(tok3, ("!|==|!=|<|<=|>|>= " + structname + " %varid% ==|!=|<|<=|>|>=|)|;").c_str(), varid) || - Token::Match(tok3->previous(), "strlen|free ( %varid% )", varid)) - { - if (value[0] == '\"' && tok3->strAt(-1) != "strlen") - { + Token::Match(tok3->previous(), "strlen|free ( %varid% )", varid)) { + if (value[0] == '\"' && tok3->strAt(-1) != "strlen") { // bail out if value is a string unless if it's just given // as parameter to strlen break; } - if (!structname.empty()) - { + if (!structname.empty()) { tok3->deleteNext(); tok3->deleteNext(); } - if (Token::Match(valueToken, "& %var% ;")) - { + if (Token::Match(valueToken, "& %var% ;")) { tok3->insertToken("&"); tok3 = tok3->next(); } @@ -7892,8 +6780,7 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign // Delete pointer alias if (pointeralias && tok3->str() == "delete" && (Token::Match(tok3, "delete %varid% ;", varid) || - Token::Match(tok3, "delete [ ] %varid%", varid))) - { + Token::Match(tok3, "delete [ ] %varid%", varid))) { tok3 = (tok3->strAt(1) == "[") ? tok3->tokAt(3) : tok3->next(); tok3->str(value); tok3->varId(valueVarId); @@ -7901,20 +6788,15 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } // Variable is used in function call.. - if (Token::Match(tok3, ("%var% ( " + structname + " %varid% ,").c_str(), varid)) - { - const char * const functionName[] = - { + if (Token::Match(tok3, ("%var% ( " + structname + " %varid% ,").c_str(), varid)) { + const char * const functionName[] = { "memcmp","memcpy","memmove","memset", "strcmp","strcpy","strncpy","strdup" }; - for (unsigned int i = 0; i < (sizeof(functionName) / sizeof(*functionName)); ++i) - { - if (tok3->str() == functionName[i]) - { + for (unsigned int i = 0; i < (sizeof(functionName) / sizeof(*functionName)); ++i) { + if (tok3->str() == functionName[i]) { Token *par1 = tok3->next()->next(); - if (!structname.empty()) - { + if (!structname.empty()) { par1->deleteThis(); par1->deleteThis(); } @@ -7926,20 +6808,15 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } // Variable is used as 2nd parameter in function call.. - if (Token::Match(tok3, ("%var% ( %any% , " + structname + " %varid% ,|)").c_str(), varid)) - { - const char * const functionName[] = - { + if (Token::Match(tok3, ("%var% ( %any% , " + structname + " %varid% ,|)").c_str(), varid)) { + const char * const functionName[] = { "memcmp","memcpy","memmove", "strcmp","strcpy","strncmp","strncpy" }; - for (unsigned int i = 0; i < (sizeof(functionName) / sizeof(*functionName)); ++i) - { - if (tok3->str() == functionName[i]) - { + for (unsigned int i = 0; i < (sizeof(functionName) / sizeof(*functionName)); ++i) { + if (tok3->str() == functionName[i]) { Token *par = tok3->tokAt(4); - if (!structname.empty()) - { + if (!structname.empty()) { par->deleteThis(); par->deleteThis(); } @@ -7951,10 +6828,8 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } // array usage - if (Token::Match(tok3, ("[(,] " + structname + " %varid% [|%op%").c_str(), varid)) - { - if (!structname.empty()) - { + if (Token::Match(tok3, ("[(,] " + structname + " %varid% [|%op%").c_str(), varid)) { + if (!structname.empty()) { tok3->deleteNext(); tok3->deleteNext(); } @@ -7969,41 +6844,34 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign Token::Match(tok3, ("[=+-*/%^|[] " + structname + " %varid% [=?+-*/%^|;])]").c_str(), varid) || Token::Match(tok3, ("[(=+-*/%^|[] " + structname + " %varid% <<|>>").c_str(), varid) || Token::Match(tok3, ("<<|>> " + structname + " %varid% %op%|;|]|)").c_str(), varid) || - Token::Match(tok3->previous(), ("[=+-*/%^|[] ( " + structname + " %varid% !!=").c_str(), varid)) - { + Token::Match(tok3->previous(), ("[=+-*/%^|[] ( " + structname + " %varid% !!=").c_str(), varid)) { if (value[0] == '\"') break; - if (!structname.empty()) - { + if (!structname.empty()) { tok3->deleteNext(); tok3->deleteNext(); } tok3 = tok3->next(); tok3->str(value); tok3->varId(valueVarId); - if (tok3->previous()->str() == "*" && valueIsPointer) - { + if (tok3->previous()->str() == "*" && valueIsPointer) { tok3 = tok3->previous(); tok3->deleteThis(); } ret = true; } - if (Token::simpleMatch(tok3, "= {")) - { + if (Token::simpleMatch(tok3, "= {")) { unsigned int indentlevel4 = 0; - for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) - { + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { if (tok4->str() == "{") ++indentlevel4; - else if (tok4->str() == "}") - { + else if (tok4->str() == "}") { if (indentlevel4 <= 1) break; --indentlevel4; } - if (Token::Match(tok4, "{|, %varid% ,|}", varid)) - { + if (Token::Match(tok4, "{|, %varid% ,|}", varid)) { tok4->next()->str(value); tok4->next()->varId(valueVarId); ret = true; @@ -8012,30 +6880,25 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } // Using the variable in for-condition.. - if (Token::simpleMatch(tok3, "for (")) - { - for (Token *tok4 = tok3->tokAt(2); tok4; tok4 = tok4->next()) - { + if (Token::simpleMatch(tok3, "for (")) { + for (Token *tok4 = tok3->tokAt(2); tok4; tok4 = tok4->next()) { if (tok4->str() == "(" || tok4->str() == ")") break; // Replace variable used in condition.. - if (Token::Match(tok4, "; %var% <|<=|!= %var% ; ++| %var% ++| )")) - { + if (Token::Match(tok4, "; %var% <|<=|!= %var% ; ++| %var% ++| )")) { const Token *inctok = tok4->tokAt(5); if (inctok->str() == "++") inctok = inctok->next(); if (inctok->varId() == varid) break; - if (tok4->next()->varId() == varid) - { + if (tok4->next()->varId() == varid) { tok4->next()->str(value); tok4->next()->varId(valueVarId); ret = true; } - if (tok4->tokAt(3)->varId() == varid) - { + if (tok4->tokAt(3)->varId() == varid) { tok4->tokAt(3)->str(value); tok4->tokAt(3)->varId(valueVarId); ret = true; @@ -8044,23 +6907,18 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } } - if (indentlevel == indentlevel3 && Token::Match(tok3->next(), "%varid% ++|--", varid) && MathLib::isInt(value)) - { + if (indentlevel == indentlevel3 && Token::Match(tok3->next(), "%varid% ++|--", varid) && MathLib::isInt(value)) { const std::string op(tok3->strAt(2)); - if (Token::Match(tok3, "[{};] %any% %any% ;")) - { + if (Token::Match(tok3, "[{};] %any% %any% ;")) { Token::eraseTokens(tok3, tok3->tokAt(3)); - } - else - { + } else { tok3 = tok3->next(); tok3->str(value); tok3->varId(valueVarId); tok3->deleteNext(); } incdec(value, op); - if (!Token::simpleMatch((*tok2)->tokAt(-2), "for (")) - { + if (!Token::simpleMatch((*tok2)->tokAt(-2), "for (")) { (*tok2)->tokAt(2)->str(value); (*tok2)->tokAt(2)->varId(valueVarId); } @@ -8068,17 +6926,13 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign } if (indentlevel == indentlevel3 && Token::Match(tok3->next(), "++|-- %varid%", varid) && MathLib::isInt(value) && - !Token::Match(tok3->tokAt(3), "[.[]")) - { + !Token::Match(tok3->tokAt(3), "[.[]")) { incdec(value, tok3->strAt(1)); (*tok2)->tokAt(2)->str(value); (*tok2)->tokAt(2)->varId(valueVarId); - if (Token::Match(tok3, "[;{}] %any% %any% ;")) - { + if (Token::Match(tok3, "[;{}] %any% %any% ;")) { Token::eraseTokens(tok3, tok3->tokAt(3)); - } - else - { + } else { tok3->deleteNext(); tok3->next()->str(value); tok3->next()->varId(valueVarId); @@ -8090,14 +6944,12 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign // return variable.. if (Token::Match(tok3, "return %varid% %any%", varid) && (tok3->tokAt(2)->isExtendedOp() || tok3->strAt(2) == ";") && - value[0] != '\"') - { + value[0] != '\"') { tok3->next()->str(value); tok3->next()->varId(valueVarId); } - else if (pointeralias && Token::Match(tok3, "return * %varid% ;", varid) && value[0] != '\"') - { + else if (pointeralias && Token::Match(tok3, "return * %varid% ;", varid) && value[0] != '\"') { tok3->deleteNext(); tok3->next()->str(value); tok3->next()->varId(valueVarId); @@ -8109,22 +6961,18 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign void Tokenizer::elseif() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (!Token::simpleMatch(tok, "else if")) continue; int indent = 0; - for (Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { if (Token::Match(tok2, "(|{")) ++indent; else if (Token::Match(tok2, ")|}")) --indent; - if (indent == 0 && Token::Match(tok2, "}|;")) - { - if (tok2->next() && tok2->next()->str() != "else") - { + if (indent == 0 && Token::Match(tok2, "}|;")) { + if (tok2->next() && tok2->next()->str() != "else") { tok->insertToken("{"); tok2->insertToken("}"); Token::createMutualLinks(tok->next(), tok2->next()); @@ -8139,8 +6987,7 @@ void Tokenizer::elseif() bool Tokenizer::simplifyRedundantParenthesis() { bool ret = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "(") continue; @@ -8148,16 +6995,14 @@ bool Tokenizer::simplifyRedundantParenthesis() if (tok->strAt(-2) != "operator" && tok->strAt(-1) == "=" && tok->strAt(1) != "{" && - Token::simpleMatch(tok->link(), ") ;")) - { + Token::simpleMatch(tok->link(), ") ;")) { tok->link()->deleteThis(); tok->deleteThis(); continue; } while (Token::simpleMatch(tok, "( (") && - tok->link()->previous() == tok->next()->link()) - { + tok->link()->previous() == tok->next()->link()) { // We have "(( *something* ))", remove the inner // parenthesis tok->deleteNext(); @@ -8166,8 +7011,7 @@ bool Tokenizer::simplifyRedundantParenthesis() } while (Token::Match(tok->previous(), "[,;{}(] ( %var% (") && - tok->link()->previous() == tok->tokAt(2)->link()) - { + tok->link()->previous() == tok->tokAt(2)->link()) { // We have "( func ( *something* ))", remove the outer // parenthesis tok->link()->deleteThis(); @@ -8175,8 +7019,7 @@ bool Tokenizer::simplifyRedundantParenthesis() ret = true; } - while (Token::Match(tok->previous(), "[;{] ( delete %var% ) ;")) - { + while (Token::Match(tok->previous(), "[;{] ( delete %var% ) ;")) { // We have "( delete var )", remove the outer // parenthesis tok->tokAt(3)->deleteThis(); @@ -8184,8 +7027,7 @@ bool Tokenizer::simplifyRedundantParenthesis() ret = true; } - while (Token::Match(tok->previous(), "[;{] ( delete [ ] %var% ) ;")) - { + while (Token::Match(tok->previous(), "[;{] ( delete [ ] %var% ) ;")) { // We have "( delete [] var )", remove the outer // parenthesis tok->tokAt(5)->deleteThis(); @@ -8196,15 +7038,13 @@ bool Tokenizer::simplifyRedundantParenthesis() if (!Token::simpleMatch(tok->tokAt(-2), "operator delete") && Token::Match(tok->previous(), "delete|; (") && (tok->strAt(-1) != "delete" || tok->next()->varId() > 0) && - Token::Match(tok->link(), ") ;|,")) - { + Token::Match(tok->link(), ") ;|,")) { tok->link()->deleteThis(); tok->deleteThis(); ret = true; } - if (Token::Match(tok->previous(), "[(!*;{}] ( %var% )") && tok->next()->varId() != 0) - { + if (Token::Match(tok->previous(), "[(!*;{}] ( %var% )") && tok->next()->varId() != 0) { // We have "( var )", remove the parenthesis tok->deleteThis(); tok->deleteNext(); @@ -8212,8 +7052,7 @@ bool Tokenizer::simplifyRedundantParenthesis() continue; } - if (Token::Match(tok->previous(), "[(!] ( %var% . %var% )")) - { + if (Token::Match(tok->previous(), "[(!] ( %var% . %var% )")) { // We have "( var . var )", remove the parenthesis tok->deleteThis(); tok = tok->tokAt(2); @@ -8223,16 +7062,14 @@ bool Tokenizer::simplifyRedundantParenthesis() } if (Token::Match(tok, "( ( %bool% )") || - Token::Match(tok, "( ( %num% )")) - { + Token::Match(tok, "( ( %num% )")) { tok->tokAt(2)->deleteNext(); tok->deleteNext(); ret = true; } if (Token::simpleMatch(tok->previous(), ", (") && - Token::simpleMatch(tok->link(), ") =")) - { + Token::simpleMatch(tok->link(), ") =")) { tok->link()->deleteThis(); tok->deleteThis(); ret = true; @@ -8243,29 +7080,23 @@ bool Tokenizer::simplifyRedundantParenthesis() void Tokenizer::simplifyReference() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // starting executable scope.. - if (Token::Match(tok, ") const| {")) - { + if (Token::Match(tok, ") const| {")) { // replace references in this scope.. if (tok->next()->str() != "{") tok = tok->next(); Token * const end = tok->next()->link(); - for (Token *tok2 = tok; tok2 && tok2 != end; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2 && tok2 != end; tok2 = tok2->next()) { // found a reference.. - if (Token::Match(tok2, "[;{}] %type% & %var% (|= %var% )| ;")) - { + if (Token::Match(tok2, "[;{}] %type% & %var% (|= %var% )| ;")) { const unsigned int ref_id = tok2->tokAt(3)->varId(); if (!ref_id) continue; // replace reference in the code.. - for (Token *tok3 = tok2->tokAt(7); tok3 && tok3 != end; tok3 = tok3->next()) - { - if (tok3->varId() == ref_id) - { + for (Token *tok3 = tok2->tokAt(7); tok3 && tok3 != end; tok3 = tok3->next()) { + if (tok3->varId() == ref_id) { tok3->str(tok2->strAt(5)); tok3->varId(tok2->tokAt(5)->varId()); } @@ -8281,8 +7112,7 @@ void Tokenizer::simplifyReference() bool Tokenizer::simplifyCalculations() { bool ret = false; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // Remove parentheses around variable.. // keep parentheses here: dynamic_cast(p); // keep parentheses here: A operator * (int); @@ -8301,24 +7131,19 @@ bool Tokenizer::simplifyCalculations() !Token::Match(tok->tokAt(-2), "* %var% )") && !Token::Match(tok->tokAt(-2), "%type% ( ) ( %var%") && !Token::Match(tok, ") ( %var% ) ;") - ) - { + ) { tok->deleteNext(); tok = tok->next(); tok->deleteNext(); ret = true; } - if (tok->isNumber()) - { - if (tok->str() == "0") - { - if (Token::Match(tok->previous(), "[+-|] 0")) - { + if (tok->isNumber()) { + if (tok->str() == "0") { + if (Token::Match(tok->previous(), "[+-|] 0")) { tok = tok->previous(); if (Token::Match(tok->tokAt(-4), "[;{}] %var% = %var% [+-|] 0 ;") && - tok->strAt(-3) == tok->strAt(-1)) - { + tok->strAt(-3) == tok->strAt(-1)) { tok = tok->previous()->previous()->previous(); tok->deleteThis(); tok->deleteThis(); @@ -8327,17 +7152,13 @@ bool Tokenizer::simplifyCalculations() tok->deleteThis(); tok->deleteThis(); ret = true; - } - else if (Token::Match(tok->previous(), "[=([,] 0 [+|]") || - Token::Match(tok->previous(), "return|case 0 [+|]")) - { + } else if (Token::Match(tok->previous(), "[=([,] 0 [+|]") || + Token::Match(tok->previous(), "return|case 0 [+|]")) { tok->deleteThis(); tok->deleteThis(); ret = true; - } - else if (Token::Match(tok->previous(), "[=[(,] 0 * %any% ,|]|)|;|=|%op%") || - Token::Match(tok->previous(), "return|case 0 * %any% ,|:|;|=|%op%")) - { + } else if (Token::Match(tok->previous(), "[=[(,] 0 * %any% ,|]|)|;|=|%op%") || + Token::Match(tok->previous(), "return|case 0 * %any% ,|:|;|=|%op%")) { tok->deleteNext(); if (tok->next()->str() == "(") Token::eraseTokens(tok, tok->next()->link()); @@ -8346,8 +7167,7 @@ bool Tokenizer::simplifyCalculations() } } - if (Token::simpleMatch(tok->previous(), "* 1") || Token::simpleMatch(tok, "1 *")) - { + if (Token::simpleMatch(tok->previous(), "* 1") || Token::simpleMatch(tok, "1 *")) { if (tok->previous()->isOp()) tok = tok->previous(); tok->deleteThis(); @@ -8356,8 +7176,7 @@ bool Tokenizer::simplifyCalculations() } // Remove parentheses around number.. - if (Token::Match(tok->tokAt(-2), "%any% ( %num% )") && !tok->tokAt(-2)->isName() && tok->strAt(-2) != ">") - { + if (Token::Match(tok->tokAt(-2), "%any% ( %num% )") && !tok->tokAt(-2)->isName() && tok->strAt(-2) != ">") { tok = tok->previous(); tok->deleteThis(); tok->deleteNext(); @@ -8369,8 +7188,7 @@ bool Tokenizer::simplifyCalculations() Token::simpleMatch(tok->previous(), "( 0 |") || Token::simpleMatch(tok->previous(), "| 0 )") || Token::simpleMatch(tok->previous(), "( 1 &&") || - Token::simpleMatch(tok->previous(), "&& 1 )")) - { + Token::simpleMatch(tok->previous(), "&& 1 )")) { if (tok->previous()->isOp()) tok = tok->previous(); tok->deleteThis(); @@ -8380,10 +7198,8 @@ bool Tokenizer::simplifyCalculations() if (Token::Match(tok, "%num% ==|!=|<=|>=|<|> %num%") && MathLib::isInt(tok->str()) && - MathLib::isInt(tok->tokAt(2)->str())) - { - if (Token::Match(tok->previous(), "(|&&|%oror%") && Token::Match(tok->tokAt(3), ")|&&|%oror%")) - { + MathLib::isInt(tok->tokAt(2)->str())) { + if (Token::Match(tok->previous(), "(|&&|%oror%") && Token::Match(tok->tokAt(3), ")|&&|%oror%")) { const MathLib::bigint op1(MathLib::toLongNumber(tok->str())); const std::string &cmp(tok->next()->str()); const MathLib::bigint op2(MathLib::toLongNumber(tok->tokAt(2)->str())); @@ -8410,8 +7226,7 @@ bool Tokenizer::simplifyCalculations() } } - if (Token::Match(tok->previous(), "[([,=] %num% <<|>> %num%")) - { + if (Token::Match(tok->previous(), "[([,=] %num% <<|>> %num%")) { const MathLib::bigint op1(MathLib::toLongNumber(tok->str())); const MathLib::bigint op2(MathLib::toLongNumber(tok->tokAt(2)->str())); MathLib::bigint result; @@ -8430,8 +7245,7 @@ bool Tokenizer::simplifyCalculations() } } - else if (tok->next() && tok->next()->isNumber()) - { + else if (tok->next() && tok->next()->isNumber()) { // (1-2) while (Token::Match(tok, "[[,(=<>+-*|&^] %num% [+-*/] %num% ]|,|)|;|=|%op%") || Token::Match(tok, "<< %num% [+-*/] %num% ]|,|)|;|=|%op%") || @@ -8439,8 +7253,7 @@ bool Tokenizer::simplifyCalculations() Token::Match(tok, "<< %num% [+-*/] %num% <<") || Token::Match(tok, "[(,[] %num% [|&^] %num% [];,);]") || Token::Match(tok, "(|%op% %num% [+-*/] %num% )|%op%") || - Token::Match(tok,"return|case %num% [+-*/] %num% ;|,|=|:|%op%")) - { + Token::Match(tok,"return|case %num% [+-*/] %num% ;|,|=|:|%op%")) { tok = tok->next(); // Don't simplify "%num% / 0" @@ -8448,8 +7261,7 @@ bool Tokenizer::simplifyCalculations() continue; // & | ^ - if (Token::Match(tok->next(), "[&|^]")) - { + if (Token::Match(tok->next(), "[&|^]")) { std::string result; const std::string first(tok->str()); const std::string second(tok->strAt(2)); @@ -8461,8 +7273,7 @@ bool Tokenizer::simplifyCalculations() else if (op == '^') result = MathLib::toString(MathLib::toLongNumber(first) ^ MathLib::toLongNumber(second)); - if (!result.empty()) - { + if (!result.empty()) { ret = true; tok->str(result); Token::eraseTokens(tok, tok->tokAt(3)); @@ -8472,13 +7283,11 @@ bool Tokenizer::simplifyCalculations() // Division where result is a whole number if (Token::Match(tok->previous(), "* %num% /") && - tok->str() == MathLib::multiply(tok->strAt(2), MathLib::divide(tok->str(), tok->strAt(2)))) - { + tok->str() == MathLib::multiply(tok->strAt(2), MathLib::divide(tok->str(), tok->strAt(2)))) { } // + and - are calculated after * and / - else if (Token::Match(tok->next(), "[+-/]")) - { + else if (Token::Match(tok->next(), "[+-/]")) { if (Token::Match(tok->previous(), "[*/%]")) continue; if (Token::Match(tok->tokAt(3), "[*/%]")) @@ -8497,8 +7306,7 @@ bool Tokenizer::simplifyCalculations() // evaluate "2 + 2 - 2 - 2" // as (((2 + 2) - 2) - 2) = 0 // instead of ((2 + 2) - (2 - 2)) = 4 - if (Token::Match(tok->next(), "[+-*/]")) - { + if (Token::Match(tok->next(), "[+-*/]")) { tok = tok->previous(); continue; } @@ -8518,35 +7326,29 @@ void Tokenizer::simplifyGoto() std::list gotos; unsigned int indentlevel = 0; Token *beginfunction = 0; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "{") { if (beginfunction == 0 && indentlevel == 0 && tok->link()) tok = tok->link(); else ++indentlevel; } - else if (tok->str() == "}") - { + else if (tok->str() == "}") { if (indentlevel == 0) break; // break out - it seems the code is wrong --indentlevel; - if (indentlevel == 0) - { + if (indentlevel == 0) { gotos.clear(); beginfunction = 0; } } - else if (indentlevel > 0 && tok->str() == "(") - { + else if (indentlevel > 0 && tok->str() == "(") { tok = tok->link(); } - else if (indentlevel == 0 && Token::Match(tok, ") const| {")) - { + else if (indentlevel == 0 && Token::Match(tok, ") const| {")) { gotos.clear(); beginfunction = tok; } @@ -8554,29 +7356,22 @@ void Tokenizer::simplifyGoto() else if (Token::Match(tok, "goto %var% ;")) gotos.push_back(tok); - else if (indentlevel == 1 && Token::Match(tok->previous(), "[};] %var% :")) - { + else if (indentlevel == 1 && Token::Match(tok->previous(), "[};] %var% :")) { // Is this label at the end.. bool end = false; int level = 0; - for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "}") - { + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { + if (tok2->str() == "}") { --level; - if (level < 0) - { + if (level < 0) { end = true; break; } - } - else if (tok2->str() == "{") - { + } else if (tok2->str() == "{") { ++level; } - if (Token::Match(tok2, "%var% :") || tok2->str() == "goto") - { + if (Token::Match(tok2, "%var% :") || tok2->str() == "goto") { break; } } @@ -8591,11 +7386,9 @@ void Tokenizer::simplifyGoto() tok->deleteThis(); // This label is at the end of the function.. replace all matching goto statements.. - for (std::list::iterator it = gotos.begin(); it != gotos.end(); ++it) - { + for (std::list::iterator it = gotos.begin(); it != gotos.end(); ++it) { Token *token = *it; - if (token->next()->str() == name) - { + if (token->next()->str() == name) { // Delete the "goto name;" token = token->previous(); token->deleteNext(); @@ -8609,20 +7402,15 @@ void Tokenizer::simplifyGoto() std::list links2; std::list links3; int lev = 0; - for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "}") - { + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "}") { --lev; if (lev < 0) break; } - if (tok2->str() == "{") - { + if (tok2->str() == "{") { ++lev; - } - else if (tok2->str() == "return") - { + } else if (tok2->str() == "return") { ret = true; if (indentlevel == 1 && lev == 0) ret2 = true; @@ -8631,18 +7419,13 @@ void Tokenizer::simplifyGoto() token = token->next(); token->linenr(tok2->linenr()); token->varId(tok2->varId()); - if (ret2 && tok2->str() == ";") - { + if (ret2 && tok2->str() == ";") { break; } - if (token->str() == "(") - { + if (token->str() == "(") { links.push_back(token); - } - else if (token->str() == ")") - { - if (links.empty()) - { + } else if (token->str() == ")") { + if (links.empty()) { // This should never happen at this point syntaxError(token, ')'); return; @@ -8650,15 +7433,10 @@ void Tokenizer::simplifyGoto() Token::createMutualLinks(links.back(), token); links.pop_back(); - } - else if (token->str() == "{") - { + } else if (token->str() == "{") { links2.push_back(token); - } - else if (token->str() == "}") - { - if (links2.empty()) - { + } else if (token->str() == "}") { + if (links2.empty()) { // This should never happen at this point syntaxError(token, '}'); return; @@ -8666,15 +7444,10 @@ void Tokenizer::simplifyGoto() Token::createMutualLinks(links2.back(), token); links2.pop_back(); - } - else if (token->str() == "[") - { + } else if (token->str() == "[") { links3.push_back(token); - } - else if (token->str() == "]") - { - if (links3.empty()) - { + } else if (token->str() == "]") { + if (links3.empty()) { // This should never happen at this point syntaxError(token, ']'); return; @@ -8685,8 +7458,7 @@ void Tokenizer::simplifyGoto() } } - if (!ret) - { + if (!ret) { token->insertToken("return"); token = token->next(); token->insertToken(";"); @@ -8696,8 +7468,7 @@ void Tokenizer::simplifyGoto() } // goto the end of the function - while (tok) - { + while (tok) { if (tok->str() == "{") tok = tok->link(); else if (tok->str() == "}") @@ -8716,17 +7487,14 @@ void Tokenizer::simplifyGoto() void Tokenizer::simplifyNestedStrcat() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (! Token::Match(tok, "[;{}] strcat ( strcat (")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (! Token::Match(tok, "[;{}] strcat ( strcat (")) { continue; } // find inner strcat call Token *tok2 = tok->tokAt(3); - while (Token::simpleMatch(tok2, "strcat ( strcat")) - { + while (Token::simpleMatch(tok2, "strcat ( strcat")) { tok2 = tok2->tokAt(2); } @@ -8756,8 +7524,7 @@ void Tokenizer::duplicateEnumError(const Token * tok1, const Token * tok2, const std::list locationList; std::string tok2_str; - if (tok1 && tok2) - { + if (tok1 && tok2) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok1->linenr(); loc.setfile(file(tok1)); @@ -8766,8 +7533,7 @@ void Tokenizer::duplicateEnumError(const Token * tok1, const Token * tok2, const loc.setfile(file(tok2)); locationList.push_back(loc); tok2_str = tok2->str(); - } - else + } else tok2_str = "name"; const ErrorLogger::ErrorMessage errmsg(locationList, @@ -8790,16 +7556,12 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) { // check for an end of definition const Token * tok = *tokPtr; - if (tok && Token::Match(tok->next(), ";|,|[|=|)|>")) - { + if (tok && Token::Match(tok->next(), ";|,|[|=|)|>")) { const Token * end = tok->next(); - if (end->str() == "[") - { + if (end->str() == "[") { end = end->link()->next(); - } - else if (end->str() == ",") - { + } else if (end->str() == ",") { // check for function argument if (Token::Match(tok->previous(), "(|,")) return false; @@ -8807,8 +7569,7 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) // find end of definition int level = 0; while (end && end->next() && (!Token::Match(end->next(), ";|)|>") || - (end->next()->str() == ")" && level == 0))) - { + (end->next()->str() == ")" && level == 0))) { if (end->next()->str() == "(") level++; else if (end->next()->str() == ")") @@ -8816,18 +7577,14 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) end = end->next(); } - } - else if (end->str() == ")") - { + } else if (end->str() == ")") { // check for function argument if (tok->previous()->str() == ",") return false; } - if (end) - { - if (Token::simpleMatch(end, ") {")) // function parameter ? - { + if (end) { + if (Token::simpleMatch(end, ") {")) { // function parameter ? // make sure it's not a conditional if (Token::Match(end->link()->previous(), "if|for|while|switch")) return false; @@ -8836,39 +7593,31 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) if (tok->previous()->str() == "enum" || (Token::Match(tok->previous(), "%type%") && tok->previous()->str() != "return") || - Token::Match(tok->tokAt(-2), "%type% &|*")) - { + Token::Match(tok->tokAt(-2), "%type% &|*")) { duplicateEnumError(*tokPtr, name, "Function parameter"); // duplicate definition so skip entire function *tokPtr = end->next()->link(); return true; } - } - else if (end->str() == ">") // template parameter ? - { + } else if (end->str() == ">") { // template parameter ? // look backwards if (tok->previous()->str() == "enum" || (Token::Match(tok->previous(), "%type%") && - tok->previous()->str() != "return")) - { + tok->previous()->str() != "return")) { // duplicate definition so skip entire template while (end && end->str() != "{") end = end->next(); - if (end) - { + if (end) { duplicateEnumError(*tokPtr, name, "Template parameter"); *tokPtr = end->link(); return true; } } - } - else - { + } else { // look backwards if (Token::Match(tok->previous(), "enum|,") || (Token::Match(tok->previous(), "%type%") && - tok->previous()->str() != "return")) - { + tok->previous()->str() != "return")) { duplicateEnumError(*tokPtr, name, "Variable"); return true; } @@ -8886,31 +7635,23 @@ void Tokenizer::simplifyEnum() std::string className; int classLevel = 0; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "class|struct|namespace %any%") && - (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) - { + (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) { className = tok->next()->str(); classLevel = 0; continue; - } - else if (tok->str() == "}") - { + } else if (tok->str() == "}") { --classLevel; if (classLevel < 0) className = ""; continue; - } - else if (tok->str() == "{") - { + } else if (tok->str() == "{") { ++classLevel; continue; - } - else if (Token::Match(tok, "enum class|struct| {|:") || - Token::Match(tok, "enum class|struct| %type% {|:|;")) - { + } else if (Token::Match(tok, "enum class|struct| {|:") || + Token::Match(tok, "enum class|struct| %type% {|:|;")) { Token *tok1; Token *start = tok; Token *end; @@ -8923,19 +7664,16 @@ void Tokenizer::simplifyEnum() tok->deleteNext(); // check for name - if (Token::Match(tok->next(), "%type%")) - { + if (Token::Match(tok->next(), "%type%")) { enumType = tok->next(); tok = tok->next(); } // check for C++0x typed enumeration - if (tok->next()->str() == ":") - { + if (tok->next()->str() == ":") { tok = tok->next(); - if (!tok->next()) - { + if (!tok->next()) { syntaxError(tok); return; // can't recover } @@ -8945,22 +7683,19 @@ void Tokenizer::simplifyEnum() typeTokenEnd = typeTokenStart; while (typeTokenEnd->next() && (typeTokenEnd->next()->str() == "::" || - Token::Match(typeTokenEnd->next(), "%type%"))) - { + Token::Match(typeTokenEnd->next(), "%type%"))) { typeTokenEnd = typeTokenEnd->next(); tok = tok->next(); } - if (!tok->next()) - { + if (!tok->next()) { syntaxError(tok); return; // can't recover } } // check for forward declaration - if (tok->next()->str() == ";") - { + if (tok->next()->str() == ";") { tok = tok->next(); /** @todo start substitution check at forward declaration */ @@ -8970,9 +7705,7 @@ void Tokenizer::simplifyEnum() start->deleteThis(); tok = start; continue; - } - else if (tok->next()->str() != "{") - { + } else if (tok->next()->str() != "{") { syntaxError(tok->next()); return; } @@ -8988,29 +7721,25 @@ void Tokenizer::simplifyEnum() // iterate over all enumerators between { and } // Give each enumerator the const value specified or if not specified, 1 + the // previous value or 0 if it is the first one. - for (; tok1 && tok1 != end; tok1 = tok1->next()) - { + for (; tok1 && tok1 != end; tok1 = tok1->next()) { Token * enumName = 0; Token * enumValue = 0; Token * enumValueStart = 0; Token * enumValueEnd = 0; - if (tok1->str() == "(") - { + if (tok1->str() == "(") { tok1 = tok1->link(); continue; } - if (Token::Match(tok1->previous(), ",|{ %type% ,|}")) - { + if (Token::Match(tok1->previous(), ",|{ %type% ,|}")) { // no value specified enumName = tok1; lastValue++; tok1->insertToken("="); tok1 = tok1->next(); - if (lastEnumValueStart && lastEnumValueEnd) - { + if (lastEnumValueStart && lastEnumValueEnd) { // previous value was an expression Token *valueStart = tok1; tok1 = copyTokens(tok1, lastEnumValueStart, lastEnumValueEnd); @@ -9022,25 +7751,19 @@ void Tokenizer::simplifyEnum() enumValue = 0; enumValueStart = valueStart->next(); enumValueEnd = tok1->next(); - } - else - { + } else { // value is previous numeric value + 1 tok1->insertToken(MathLib::toString(lastValue)); enumValue = tok1->next(); } - } - else if (Token::Match(tok1->previous(), ",|{ %type% = %num% ,|}")) - { + } else if (Token::Match(tok1->previous(), ",|{ %type% = %num% ,|}")) { // value is specified numeric value enumName = tok1; lastValue = MathLib::toLongNumber(tok1->strAt(2)); enumValue = tok1->tokAt(2); lastEnumValueStart = 0; lastEnumValueEnd = 0; - } - else if (Token::Match(tok1->previous(), ",|{ %type% =")) - { + } else if (Token::Match(tok1->previous(), ",|{ %type% =")) { // value is specified expression enumName = tok1; lastValue = 0; @@ -9053,8 +7776,7 @@ void Tokenizer::simplifyEnum() enumValueEnd->str() == "{") level++; while (enumValueEnd->next() && - (!Token::Match(enumValueEnd->next(), "}|,") || level)) - { + (!Token::Match(enumValueEnd->next(), "}|,") || level)) { if (enumValueEnd->next()->str() == "(" || enumValueEnd->next()->str() == "[" || enumValueEnd->next()->str() == "{") @@ -9074,8 +7796,7 @@ void Tokenizer::simplifyEnum() } // find all uses of this enumerator and substitute it's value for it's name - if (enumName && (enumValue || (enumValueStart && enumValueEnd))) - { + if (enumName && (enumValue || (enumValueStart && enumValueEnd))) { const std::string pattern = className.empty() ? std::string("") : std::string(className + " :: " + enumName->str()); @@ -9087,65 +7808,48 @@ void Tokenizer::simplifyEnum() bool simplify = false; bool hasClass = false; const Token *endScope = 0; - for (Token *tok2 = tok1->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "}") - { + for (Token *tok2 = tok1->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == "}") { --level; if (level < 0) inScope = false; - if (exitThisScope) - { + if (exitThisScope) { if (level < exitScope) exitThisScope = false; } - } - else if (tok2->str() == "{") - { + } else if (tok2->str() == "{") { // Is the same enum redefined? const Token *begin = end->link(); if (tok2->fileIndex() == begin->fileIndex() && tok2->linenr() == begin->linenr() && Token::Match(begin->tokAt(-2), "enum %type% {") && Token::Match(tok2->tokAt(-2), "enum %type% {") && - begin->strAt(-1) == tok2->strAt(-1)) - { + begin->strAt(-1) == tok2->strAt(-1)) { // remove duplicate enum Token * startToken = tok2->tokAt(-3); tok2 = tok2->link()->next(); Token::eraseTokens(startToken, tok2); if (!tok2) break; - } - else - { + } else { // Not a duplicate enum.. ++level; } endScope = tok2->link(); - } - else if (!pattern.empty() && Token::Match(tok2, pattern.c_str())) - { + } else if (!pattern.empty() && Token::Match(tok2, pattern.c_str())) { simplify = true; hasClass = true; - } - else if (inScope && !exitThisScope && tok2->str() == enumName->str()) - { + } else if (inScope && !exitThisScope && tok2->str() == enumName->str()) { if (Token::simpleMatch(tok2->previous(), "::") || - Token::Match(tok2->next(), "::|[")) - { + Token::Match(tok2->next(), "::|[")) { // Don't replace this enum if: // * it's preceded or followed by "::" // * it's followed by "[" - } - else if (!duplicateDefinition(&tok2, enumName)) - { + } else if (!duplicateDefinition(&tok2, enumName)) { simplify = true; hasClass = false; - } - else - { + } else { // something with the same name. exitScope = level; if (endScope) @@ -9153,19 +7857,16 @@ void Tokenizer::simplifyEnum() } } - if (simplify) - { + if (simplify) { if (enumValue) tok2->str(enumValue->str()); - else - { + else { tok2 = tok2->previous(); tok2->deleteNext(); tok2 = copyTokens(tok2, enumValueStart, enumValueEnd); } - if (hasClass) - { + if (hasClass) { tok2->deleteNext(); tok2->deleteNext(); } @@ -9177,22 +7878,19 @@ void Tokenizer::simplifyEnum() } // check for a variable definition: enum {} x; - if (end->next() && end->next()->str() != ";") - { + if (end->next() && end->next()->str() != ";") { Token *tempTok = end; tempTok->insertToken(";"); tempTok = tempTok->next(); if (typeTokenStart == 0) tempTok->insertToken("int"); - else - { + else { Token *tempTok1 = typeTokenStart; tempTok->insertToken(tempTok1->str()); - while (tempTok1 != typeTokenEnd) - { + while (tempTok1 != typeTokenEnd) { tempTok1 = tempTok1->next(); tempTok->insertToken(tempTok1->str()); @@ -9201,8 +7899,7 @@ void Tokenizer::simplifyEnum() } } - if (enumType) - { + if (enumType) { const std::string pattern(className.empty() ? "" : (className + " :: " + enumType->str()).c_str()); // count { and } for tok2 @@ -9213,55 +7910,42 @@ void Tokenizer::simplifyEnum() int exitScope = 0; bool simplify = false; bool hasClass = false; - for (Token *tok2 = end->next(); tok2; tok2 = tok2->next()) - { - if (tok2->str() == "}") - { + for (Token *tok2 = end->next(); tok2; tok2 = tok2->next()) { + if (tok2->str() == "}") { --level; if (level < 0) inScope = false; - if (exitThisScope) - { + if (exitThisScope) { if (level < exitScope) exitThisScope = false; } - } - else if (tok2->str() == "{") + } else if (tok2->str() == "{") ++level; - else if (!pattern.empty() && ((Token::simpleMatch(tok2, "enum") && Token::Match(tok2->next(), pattern.c_str())) || Token::Match(tok2, pattern.c_str()))) - { + else if (!pattern.empty() && ((Token::simpleMatch(tok2, "enum") && Token::Match(tok2->next(), pattern.c_str())) || Token::Match(tok2, pattern.c_str()))) { simplify = true; hasClass = true; - } - else if (inScope && !exitThisScope && (tok2->str() == enumType->str() || (tok2->str() == "enum" && tok2->next() && tok2->next()->str() == enumType->str()))) - { - if (Token::simpleMatch(tok2->previous(), "::")) - { + } else if (inScope && !exitThisScope && (tok2->str() == enumType->str() || (tok2->str() == "enum" && tok2->next() && tok2->next()->str() == enumType->str()))) { + if (Token::simpleMatch(tok2->previous(), "::")) { // Don't replace this enum if it's preceded by "::" - } - else if (tok2->next() && - (tok2->next()->isName() || tok2->next()->str() == "(")) - { + } else if (tok2->next() && + (tok2->next()->isName() || tok2->next()->str() == "(")) { simplify = true; hasClass = false; } } - if (simplify) - { + if (simplify) { if (tok2->str() == "enum") tok2->deleteNext(); if (typeTokenStart == 0) tok2->str("int"); - else - { + else { Token *tok3 = typeTokenStart; tok2->str(tok3->str()); - while (tok3 != typeTokenEnd) - { + while (tok3 != typeTokenEnd) { tok3 = tok3->next(); tok2->insertToken(tok3->str()); @@ -9269,8 +7953,7 @@ void Tokenizer::simplifyEnum() } } - if (hasClass) - { + if (hasClass) { tok2->deleteNext(); tok2->deleteNext(); } @@ -9284,14 +7967,11 @@ void Tokenizer::simplifyEnum() while (tok1->next() && tok1->next() != end) tok1->deleteNext(); tok1->deleteNext(); - if (start != _tokens) - { + if (start != _tokens) { tok1 = start->previous(); tok1->deleteNext(); tok = tok1; - } - else - { + } else { _tokens->deleteThis(); tok = _tokens; } @@ -9310,14 +7990,12 @@ void Tokenizer::simplifyStd() f.insert("malloc"); f.insert("strdup"); - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "std") continue; if (Token::Match(tok->previous(), "[(,{};] std :: %var% (") && - f.find(tok->strAt(2)) != f.end()) - { + f.find(tok->strAt(2)) != f.end()) { tok->deleteNext(); tok->deleteThis(); } @@ -9338,10 +8016,8 @@ const Token *Tokenizer::getFunctionTokenByName(const char funcname[]) const std::list::const_iterator scope; - for (scope = _symbolDatabase->scopeList.begin(); scope != _symbolDatabase->scopeList.end(); ++scope) - { - if (scope->type == Scope::eFunction) - { + for (scope = _symbolDatabase->scopeList.begin(); scope != _symbolDatabase->scopeList.end(); ++scope) { + if (scope->type == Scope::eFunction) { if (scope->classDef->str() == funcname) return scope->classDef; } @@ -9368,8 +8044,7 @@ void Tokenizer::deallocateTokens() void Tokenizer::deleteTokens(Token *tok) { - while (tok) - { + while (tok) { Token *next = tok->next(); delete tok; tok = next; @@ -9381,8 +8056,7 @@ void Tokenizer::deleteTokens(Token *tok) const char *Tokenizer::getParameterName(const Token *ftok, unsigned int par) { unsigned int _par = 1; - for (; ftok; ftok = ftok->next()) - { + for (; ftok; ftok = ftok->next()) { if (ftok->str() == ")") break; if (ftok->str() == ",") @@ -9412,8 +8086,7 @@ std::string Tokenizer::file(const Token *tok) const void Tokenizer::syntaxError(const Token *tok) { std::list locationList; - if (tok) - { + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); loc.setfile(file(tok)); @@ -9435,8 +8108,7 @@ void Tokenizer::syntaxError(const Token *tok) void Tokenizer::syntaxError(const Token *tok, char c) { std::list locationList; - if (tok) - { + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); loc.setfile(file(tok)); @@ -9463,8 +8135,7 @@ void Tokenizer::syntaxError(const Token *tok, char c) void Tokenizer::cppcheckError(const Token *tok) const { std::list locationList; - if (tok) - { + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); loc.setfile(file(tok)); @@ -9486,19 +8157,15 @@ void Tokenizer::cppcheckError(const Token *tok) const void Tokenizer::simplifyMathFunctions() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "atol ( %str% )")) - { - if (!MathLib::isInt(tok->tokAt(2)->strValue())) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "atol ( %str% )")) { + if (!MathLib::isInt(tok->tokAt(2)->strValue())) { // Ignore strings which we can't convert continue; } if (tok->previous() && - Token::simpleMatch(tok->previous()->previous(), "std ::")) - { + Token::simpleMatch(tok->previous()->previous(), "std ::")) { // Delete "std ::" tok = tok->previous()->previous(); tok->deleteNext(); @@ -9520,11 +8187,9 @@ void Tokenizer::simplifyMathFunctions() void Tokenizer::simplifyComma() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::simpleMatch(tok, "for (") || - Token::Match(tok, "=|enum {")) - { + Token::Match(tok, "=|enum {")) { tok = tok->next()->link(); if (!tok) break; @@ -9532,31 +8197,25 @@ void Tokenizer::simplifyComma() continue; } - if (tok->str() == "(") - { + if (tok->str() == "(") { tok = tok->link(); continue; } // Skip unhandled template specifiers.. - if (Token::Match(tok, "%var% <")) - { + if (Token::Match(tok, "%var% <")) { // Todo.. use the link instead. unsigned int comparelevel = 0; - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { if (tok2->str() == "<") ++comparelevel; - else if (tok2->str() == ">") - { - if (comparelevel <= 1) - { + else if (tok2->str() == ">") { + if (comparelevel <= 1) { tok = tok2; break; } ++comparelevel; - } - else if (Token::Match(tok2, "[;{}]")) + } else if (Token::Match(tok2, "[;{}]")) break; } } @@ -9567,40 +8226,29 @@ void Tokenizer::simplifyComma() // We must not accept just any keyword, e.g. accepting int // would cause function parameters to corrupt. - if (Token::simpleMatch(tok->next(), "delete")) - { + if (Token::simpleMatch(tok->next(), "delete")) { // Handle "delete a, delete b;" tok->str(";"); } - if (tok->previous() && tok->previous()->previous()) - { + if (tok->previous() && tok->previous()->previous()) { if (Token::Match(tok->previous()->previous(), "delete %var% , %var% ;") && - tok->next()->varId() != 0) - { + tok->next()->varId() != 0) { // Handle "delete a, b;" tok->str(";"); tok->insertToken("delete"); - } - else - { - for (Token *tok2 = tok->previous(); tok2; tok2 = tok2->previous()) - { - if (tok2->str() == "=") - { + } else { + for (Token *tok2 = tok->previous(); tok2; tok2 = tok2->previous()) { + if (tok2->str() == "=") { // Handle "a = 0, b = 0;" tok->str(";"); break; - } - else if (Token::Match(tok2, "delete %var%") || - Token::Match(tok2, "delete [ ] %var%")) - { + } else if (Token::Match(tok2, "delete %var%") || + Token::Match(tok2, "delete [ ] %var%")) { // Handle "delete a, a = 0;" tok->str(";"); break; - } - else if (Token::Match(tok2, "[;,{}()]")) - { + } else if (Token::Match(tok2, "[;,{}()]")) { break; } } @@ -9612,15 +8260,11 @@ void Tokenizer::simplifyComma() Token *endAt = NULL; // first ";" token after "; return" // find "; return" pattern before comma - for (Token *tok2 = tok; tok2; tok2 = tok2->previous()) - { - if (Token::Match(tok2, "[;{}]")) - { + for (Token *tok2 = tok; tok2; tok2 = tok2->previous()) { + if (Token::Match(tok2, "[;{}]")) { break; - } - else if (tok2->str() == "return" && Token::Match(tok2->previous(), "[;{}]")) - { + } else if (tok2->str() == "return" && Token::Match(tok2->previous(), "[;{}]")) { inReturn = true; startFrom = tok2->next(); break; @@ -9628,61 +8272,44 @@ void Tokenizer::simplifyComma() } // find token where return ends and also count commas - if (inReturn) - { + if (inReturn) { size_t commaCounter = 0; size_t indentlevel = 0; - for (Token *tok2 = startFrom; tok2; tok2 = tok2->next()) - { - if (tok2->str() == ";") - { + for (Token *tok2 = startFrom; tok2; tok2 = tok2->next()) { + if (tok2->str() == ";") { endAt = tok2; break; - } - else if (tok2->str() == "(") - { + } else if (tok2->str() == "(") { ++indentlevel; - } - else if (tok2->str() == ")") - { + } else if (tok2->str() == ")") { --indentlevel; - } - else if (tok2->str() == "," && indentlevel == 0) - { + } else if (tok2->str() == "," && indentlevel == 0) { ++commaCounter; } } - if (commaCounter) - { + if (commaCounter) { indentlevel = 0; // change tokens: // "; return a ( ) , b ( ) , c ;" // to // "; return a ( ) ; b ( ) ; c ;" - for (Token *tok2 = startFrom; tok2 != endAt; tok2 = tok2->next()) - { - if (tok2->str() == "(") - { + for (Token *tok2 = startFrom; tok2 != endAt; tok2 = tok2->next()) { + if (tok2->str() == "(") { ++indentlevel; - } - else if (tok2->str() == ")") - { + } else if (tok2->str() == ")") { --indentlevel; - } - else if (tok2->str() == "," && indentlevel == 0) - { + } else if (tok2->str() == "," && indentlevel == 0) { tok2->str(";"); --commaCounter; - if (commaCounter == 0) - { + if (commaCounter == 0) { tok2->insertToken("return"); } } @@ -9704,32 +8331,26 @@ void Tokenizer::simplifyComma() void Tokenizer::removeExceptionSpecifications(Token *tok) const { - while (tok) - { + while (tok) { if (tok->str() == "{") tok = tok->link(); else if (tok->str() == "}") break; - else if (Token::Match(tok, ") const| throw (")) - { - if (tok->next()->str() == "const") - { + else if (Token::Match(tok, ") const| throw (")) { + if (tok->next()->str() == "const") { Token::eraseTokens(tok->next(), tok->tokAt(3)->link()); tok = tok->next(); - } - else + } else Token::eraseTokens(tok, tok->tokAt(2)->link()); tok->deleteNext(); } - else if (Token::Match(tok, "class|namespace|struct %type%")) - { + else if (Token::Match(tok, "class|namespace|struct %type%")) { while (tok && !Token::Match(tok, "[;{=]")) tok = tok->next(); - if (tok && tok->str() == "{") - { + if (tok && tok->str() == "{") { removeExceptionSpecifications(tok->next()); tok = tok->link(); } @@ -9745,13 +8366,10 @@ bool Tokenizer::validate() const { std::stack linktok; const Token *lastTok = 0; - for (const Token *tok = tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokens(); tok; tok = tok->next()) { lastTok = tok; - if (Token::Match(tok, "[{([]")) - { - if (tok->link() == 0) - { + if (Token::Match(tok, "[{([]")) { + if (tok->link() == 0) { cppcheckError(tok); return false; } @@ -9760,28 +8378,23 @@ bool Tokenizer::validate() const continue; } - else if (Token::Match(tok, "[})]]")) - { - if (tok->link() == 0) - { + else if (Token::Match(tok, "[})]]")) { + if (tok->link() == 0) { cppcheckError(tok); return false; } - if (linktok.empty() == true) - { + if (linktok.empty() == true) { cppcheckError(tok); return false; } - if (tok->link() != linktok.top()) - { + if (tok->link() != linktok.top()) { cppcheckError(tok); return false; } - if (tok != tok->link()->link()) - { + if (tok != tok->link()->link()) { cppcheckError(tok); return false; } @@ -9790,22 +8403,19 @@ bool Tokenizer::validate() const continue; } - if (tok->link() != 0) - { + if (tok->link() != 0) { cppcheckError(tok); return false; } } - if (!linktok.empty()) - { + if (!linktok.empty()) { cppcheckError(linktok.top()); return false; } // Validate that the Tokenizer::_tokensBack is updated correctly during simplifications - if (lastTok != _tokensBack) - { + if (lastTok != _tokensBack) { cppcheckError(lastTok); return false; } @@ -9819,23 +8429,19 @@ std::string Tokenizer::simplifyString(const std::string &source) // true when previous char is a \ . bool escaped = false; - for (std::string::size_type i = 0; i + 2 < str.size(); i++) - { - if (!escaped) - { + for (std::string::size_type i = 0; i + 2 < str.size(); i++) { + if (!escaped) { if (str[i] == '\\') escaped = true; continue; } - if (str[i] == 'x') - { + if (str[i] == 'x') { // Hex value if (str[i+1] == '0' && str[i+2] == '0') str.replace(i, 3, "0"); - else if (i > 0) - { + else if (i > 0) { // We will replace all other character as 'a' // If that causes problems in the future, this can // be improved. But for now, this should be OK. @@ -9846,16 +8452,12 @@ std::string Tokenizer::simplifyString(const std::string &source) n += 2; str.replace(i, n, "a"); } - } - else if (MathLib::isOctalDigit(str[i])) - { + } else if (MathLib::isOctalDigit(str[i])) { if (MathLib::isOctalDigit(str[i+1]) && - MathLib::isOctalDigit(str[i+2])) - { + MathLib::isOctalDigit(str[i+2])) { if (str[i+1] == '0' && str[i+2] == '0') str.replace(i, 3, "0"); - else - { + else { // We will replace all other character as 'a' // If that causes problems in the future, this can // be improved. But for now, this should be OK. @@ -9874,16 +8476,13 @@ std::string Tokenizer::simplifyString(const std::string &source) void Tokenizer::simplifyStructInit() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;{}] struct| %type% %var% = { . %type% =")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;{}] struct| %type% %var% = { . %type% =")) { // Goto "." and check if the initializations have an expected format const Token *tok2 = tok; while (tok2->str() != ".") tok2 = tok2->next(); - while (tok2 && tok2->str() == ".") - { + while (tok2 && tok2->str() == ".") { if (Token::Match(tok2, ". %type% = %num% [,}]")) tok2 = tok2->tokAt(4); else if (Token::Match(tok2, ". %type% = %var% [,}]")) @@ -9907,15 +8506,13 @@ void Tokenizer::simplifyStructInit() Token *tok3 = vartok->tokAt(2); tok3->link(0); - while (Token::Match(tok3, "[{,] . %type% =")) - { + while (Token::Match(tok3, "[{,] . %type% =")) { tok3->str(vartok->str()); tok3->varId(vartok->varId()); tok3 = tok3->tokAt(5); while (!Token::Match(tok3, "[,}]")) tok3 = tok3->next(); - if (tok3->str() == "}") - { + if (tok3->str() == "}") { tok3->deleteThis(); break; } @@ -9929,10 +8526,8 @@ void Tokenizer::simplifyStructInit() void Tokenizer::simplifyComparisonOrder() { // Use "<" comparison instead of ">" - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "[;(] %any% >|>= %any% [);]")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "[;(] %any% >|>= %any% [);]")) { if (!tok->next()->isName() && !tok->next()->isNumber()) continue; const Token *operand2 = tok->tokAt(3); @@ -9945,9 +8540,7 @@ void Tokenizer::simplifyComparisonOrder() tok->tokAt(2)->str("<"); else tok->tokAt(2)->str("<="); - } - else if (Token::Match(tok, "( %num% ==|!= %var% )")) - { + } else if (Token::Match(tok, "( %num% ==|!= %var% )")) { if (!tok->next()->isName() && !tok->next()->isNumber()) continue; const std::string op1(tok->strAt(1)); @@ -9959,12 +8552,10 @@ void Tokenizer::simplifyComparisonOrder() void Tokenizer::simplifyConst() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "[;{}(,] %type% const") && tok->next()->str().find(":") == std::string::npos && - tok->next()->str() != "operator") - { + tok->next()->str() != "operator") { tok->tokAt(2)->str(tok->tokAt(1)->str()); tok->tokAt(1)->str("const"); } @@ -9985,8 +8576,7 @@ void Tokenizer::getErrorMessages(ErrorLogger *errorLogger, const Settings *setti /** find pattern */ static bool findmatch(const Token *tok1, const Token *tok2, const char pattern[]) { - for (const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) - { + for (const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) { if (Token::Match(tok, pattern)) return true; } @@ -9995,8 +8585,7 @@ static bool findmatch(const Token *tok1, const Token *tok2, const char pattern[] void Tokenizer::simplifyWhile0() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // while (0) const bool while0(Token::Match(tok, "while ( 0|false )")); @@ -10009,13 +8598,11 @@ void Tokenizer::simplifyWhile0() if (!while0 && !for0) continue; - if (while0 && Token::simpleMatch(tok->previous(), "}")) - { + if (while0 && Token::simpleMatch(tok->previous(), "}")) { // find "do" Token *tok2 = tok->previous()->link(); tok2 = tok2 ? tok2->previous() : 0; - if (tok2 && tok2->str() == "do" && !findmatch(tok2, tok, "continue|break")) - { + if (tok2 && tok2->str() == "do" && !findmatch(tok2, tok, "continue|break")) { // delete "do {" tok2->deleteThis(); tok2->deleteThis(); @@ -10033,11 +8620,9 @@ void Tokenizer::simplifyWhile0() } // remove "while (0) { .. }" - if (Token::simpleMatch(tok->next()->link(), ") {")) - { + if (Token::simpleMatch(tok->next()->link(), ") {")) { const Token *end = tok->next()->link()->next()->link(); - if (!findmatch(tok, end, "%var% : ;")) - { + if (!findmatch(tok, end, "%var% : ;")) { Token::eraseTokens(tok, end ? end->next() : 0); tok->deleteThis(); // delete "while" } @@ -10048,8 +8633,7 @@ void Tokenizer::simplifyWhile0() void Tokenizer::simplifyErrNoInWhile() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() != "errno") continue; @@ -10061,8 +8645,7 @@ void Tokenizer::simplifyErrNoInWhile() else continue; - if (Token::simpleMatch(endpar->link()->previous(), "while (")) - { + if (Token::simpleMatch(endpar->link()->previous(), "while (")) { Token *tok1 = tok->previous(); if (tok1->str() == "(") tok1 = tok1->previous(); @@ -10080,8 +8663,7 @@ void Tokenizer::simplifyErrNoInWhile() void Tokenizer::simplifyFuncInWhile() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (!Token::Match(tok, "while ( %var% ( %var% ) ) {")) continue; @@ -10121,8 +8703,7 @@ void Tokenizer::simplifyStructDecl() std::list skip; // true = in function, false = not in function skip.push_back(false); - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { Token *restart; // check for start of scope and determine if it is in a function @@ -10134,8 +8715,7 @@ void Tokenizer::simplifyStructDecl() skip.pop_back(); // check for named struct/union - else if (Token::Match(tok, "class|struct|union %type% :|{")) - { + else if (Token::Match(tok, "class|struct|union %type% :|{")) { Token *isStatic = tok->previous() && tok->previous()->str() == "static" ? tok->previous() : NULL; Token *type = tok->next(); Token *next = tok->tokAt(2); @@ -10149,12 +8729,10 @@ void Tokenizer::simplifyStructDecl() restart = next; // check for named type - if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) - { + if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) { tok->insertToken(";"); tok = tok->next(); - if (isStatic) - { + if (isStatic) { isStatic->deleteThis(); tok->insertToken("static"); tok = tok->next(); @@ -10166,8 +8744,7 @@ void Tokenizer::simplifyStructDecl() } // check for anonymous struct/union - else if (Token::Match(tok, "struct|union {")) - { + else if (Token::Match(tok, "struct|union {")) { bool inFunction = skip.back(); skip.push_back(false); Token *tok1 = tok; @@ -10176,8 +8753,7 @@ void Tokenizer::simplifyStructDecl() tok = tok->next()->link(); // check for named type - if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) - { + if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) { std::string name; name = "Anonymous" + MathLib::toString(count++); @@ -10190,14 +8766,11 @@ void Tokenizer::simplifyStructDecl() } // unnamed anonymous struct/union so possibly remove it - else if (tok->next() && tok->next()->str() == ";") - { - if (tok1->str() == "union" && inFunction) - { + else if (tok->next() && tok->next()->str() == ";") { + if (tok1->str() == "union" && inFunction) { // Try to create references in the union.. Token *tok2 = tok1->tokAt(2); - while (tok2) - { + while (tok2) { if (Token::Match(tok2, "%type% %var% ;")) tok2 = tok2->tokAt(3); else @@ -10207,15 +8780,11 @@ void Tokenizer::simplifyStructDecl() continue; Token *vartok = 0; tok2 = tok1->tokAt(2); - while (Token::Match(tok2, "%type% %var% ;")) - { - if (!vartok) - { + while (Token::Match(tok2, "%type% %var% ;")) { + if (!vartok) { vartok = tok2->next(); tok2 = tok2->tokAt(3); - } - else - { + } else { tok2->insertToken("&"); tok2 = tok2->tokAt(2); tok2->insertToken(vartok->str()); @@ -10227,16 +8796,13 @@ void Tokenizer::simplifyStructDecl() } // don't remove unnamed anonymous unions from a class, struct or union - if (!(tok1->str() == "union" && !inFunction)) - { + if (!(tok1->str() == "union" && !inFunction)) { skip.pop_back(); tok1->deleteThis(); - if (tok1->next() == tok) - { + if (tok1->next() == tok) { tok1->deleteThis(); tok = tok1; - } - else + } else tok1->deleteThis(); restart = tok1->previous(); tok->deleteThis(); @@ -10245,12 +8811,10 @@ void Tokenizer::simplifyStructDecl() } } - if (!restart) - { + if (!restart) { simplifyStructDecl(); return; - } - else if (!restart->next()) + } else if (!restart->next()) return; tok = restart; @@ -10261,14 +8825,11 @@ void Tokenizer::simplifyStructDecl() void Tokenizer::simplifyCallingConvention() { const char * pattern = "__cdecl|__stdcall|__fastcall|__thiscall|__clrcall|__syscall|__pascal|__fortran|__far|__near|WINAPI|APIENTRY|CALLBACK"; - while (Token::Match(_tokens, pattern)) - { + while (Token::Match(_tokens, pattern)) { _tokens->deleteThis(); } - for (Token *tok = _tokens; tok; tok = tok->next()) - { - while (Token::Match(tok->next(), pattern)) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + while (Token::Match(tok->next(), pattern)) { tok->deleteNext(); } } @@ -10276,15 +8837,12 @@ void Tokenizer::simplifyCallingConvention() void Tokenizer::simplifyDeclspec() { - while (Token::simpleMatch(_tokens, "__declspec (") && _tokens->next()->link() && _tokens->next()->link()->next()) - { + while (Token::simpleMatch(_tokens, "__declspec (") && _tokens->next()->link() && _tokens->next()->link()->next()) { Token::eraseTokens(_tokens, _tokens->next()->link()->next()); _tokens->deleteThis(); } - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "__declspec (") && tok->next()->link() && tok->next()->link()->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "__declspec (") && tok->next()->link() && tok->next()->link()->next()) { Token::eraseTokens(tok, tok->next()->link()->next()); tok->deleteThis(); } @@ -10293,20 +8851,15 @@ void Tokenizer::simplifyDeclspec() void Tokenizer::simplifyAttribute() { - while (Token::simpleMatch(_tokens, "__attribute__ (") && _tokens->next()->link() && _tokens->next()->link()->next()) - { + while (Token::simpleMatch(_tokens, "__attribute__ (") && _tokens->next()->link() && _tokens->next()->link()->next()) { Token::eraseTokens(_tokens, _tokens->next()->link()->next()); _tokens->deleteThis(); } - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "__attribute__ (") && tok->next()->link() && tok->next()->link()->next()) - { - if (Token::simpleMatch(tok->tokAt(2), "( unused )")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "__attribute__ (") && tok->next()->link() && tok->next()->link()->next()) { + if (Token::simpleMatch(tok->tokAt(2), "( unused )")) { // check if after variable name - if (Token::Match(tok->next()->link()->next(), ";|=")) - { + if (Token::Match(tok->next()->link()->next(), ";|=")) { if (Token::Match(tok->previous(), "%type%")) tok->previous()->isUnused(true); } @@ -10327,14 +8880,11 @@ void Tokenizer::simplifyAttribute() void Tokenizer::simplifyKeyword() { const char pattern[] = "volatile|inline|__inline|__forceinline|register|restrict|__restrict|__restrict__"; - while (Token::Match(_tokens, pattern)) - { + while (Token::Match(_tokens, pattern)) { _tokens->deleteThis(); } - for (Token *tok = _tokens; tok; tok = tok->next()) - { - while (Token::Match(tok->next(), pattern)) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + while (Token::Match(tok->next(), pattern)) { tok->deleteNext(); } } @@ -10342,28 +8892,24 @@ void Tokenizer::simplifyKeyword() void Tokenizer::simplifyAssignmentInFunctionCall() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (tok->str() == "(") tok = tok->link(); // Find 'foo(var='. Exclude 'assert(var=' to allow tests to check that assert(...) does not contain side-effects else if (Token::Match(tok, "[;{}] %var% ( %var% =") && Token::simpleMatch(tok->tokAt(2)->link(), ") ;") && - tok->strAt(1) != "assert") - { + tok->strAt(1) != "assert") { const std::string funcname(tok->strAt(1)); const Token * const vartok = tok->tokAt(3); // Goto ',' or ')'.. - for (Token *tok2 = tok->tokAt(4); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->tokAt(4); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); else if (tok2->str() == ";") break; - else if (tok2->str() == ")" || tok2->str() == ",") - { + else if (tok2->str() == ")" || tok2->str() == ",") { tok2 = tok2->previous(); tok2->insertToken(vartok->str()); @@ -10386,17 +8932,14 @@ void Tokenizer::simplifyAssignmentInFunctionCall() // Remove __asm.. void Tokenizer::simplifyAsm() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok->next(), "__asm|_asm|asm {") && tok->tokAt(2)->link() && - tok->tokAt(2)->link()->next()) - { + tok->tokAt(2)->link()->next()) { Token::eraseTokens(tok, tok->tokAt(2)->link()->next()); } - else if (Token::Match(tok->next(), "asm|__asm|__asm__ volatile|__volatile__| (")) - { + else if (Token::Match(tok->next(), "asm|__asm|__asm__ volatile|__volatile__| (")) { // Goto "(" Token *partok = tok->tokAt(2); if (partok->str() != "(") @@ -10404,8 +8947,7 @@ void Tokenizer::simplifyAsm() Token::eraseTokens(tok, partok->link() ? partok->link()->next() : NULL); } - else if (Token::simpleMatch(tok->next(), "__asm")) - { + else if (Token::simpleMatch(tok->next(), "__asm")) { const Token *tok2 = tok->next(); while (tok2 && (tok2->isNumber() || tok2->isName() || tok2->str() == ",")) tok2 = tok2->next(); @@ -10430,14 +8972,12 @@ void Tokenizer::simplifyAsm() // Simplify bitfields void Tokenizer::simplifyBitfields() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { Token *last = 0; if (Token::Match(tok, ";|{|}|public:|protected:|private: const| %type% %var% :") && !Token::Match(tok->next(), "case|public|protected|private|class|struct") && - !Token::simpleMatch(tok->tokAt(2), "default :")) - { + !Token::simpleMatch(tok->tokAt(2), "default :")) { int offset = 0; if (tok->next()->str() == "const") offset = 1; @@ -10445,30 +8985,25 @@ void Tokenizer::simplifyBitfields() Token *tok1 = tok->tokAt(2 + offset); if (tok1 && tok1->tokAt(2) && (tok1->tokAt(2)->isBoolean() || Token::Match(tok1->tokAt(2), "%num%") || - !Token::Match(tok1->tokAt(2), "public|protected|private| %type% ::|<|,|{|;"))) - { + !Token::Match(tok1->tokAt(2), "public|protected|private| %type% ::|<|,|{|;"))) { while (tok1->next() && !Token::Match(tok1->next(), ";|,")) tok1->deleteNext(); last = tok1->next(); } - } - else if (Token::Match(tok, ";|{|}|public:|protected:|private: const| %type% : %any% ;") && - tok->next()->str() != "default") - { + } else if (Token::Match(tok, ";|{|}|public:|protected:|private: const| %type% : %any% ;") && + tok->next()->str() != "default") { int offset = 0; if (tok->next()->str() == "const") offset = 1; - if (tok->strAt(3 + offset) != "{") - { + if (tok->strAt(3 + offset) != "{") { Token::eraseTokens(tok->tokAt(0), tok->tokAt(5 + offset)); tok = tok->previous(); } } - if (last && last->str() == ",") - { + if (last && last->str() == ",") { Token *tok1 = last; tok1->str(";"); @@ -10486,35 +9021,27 @@ void Tokenizer::simplifyBitfields() // Remove __builtin_expect(...), likely(...), and unlikely(...) void Tokenizer::simplifyBuiltinExpect() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok->next(), "__builtin_expect (")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok->next(), "__builtin_expect (")) { // Count parentheses for tok2 unsigned int parlevel = 0; - for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) - { + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(") ++parlevel; - else if (tok2->str() == ")") - { + else if (tok2->str() == ")") { if (parlevel <= 1) break; --parlevel; } - if (parlevel == 1 && tok2->str() == ",") - { - if (Token::Match(tok2, ", %num% )")) - { + if (parlevel == 1 && tok2->str() == ",") { + if (Token::Match(tok2, ", %num% )")) { tok->deleteNext(); Token::eraseTokens(tok2->previous(), tok2->tokAt(2)); } break; } } - } - else if (Token::Match(tok->next(), "likely|unlikely (")) - { + } else if (Token::Match(tok->next(), "likely|unlikely (")) { // remove closing ')' tok->tokAt(2)->link()->previous()->deleteNext(); @@ -10535,16 +9062,12 @@ void Tokenizer::simplifyMicrosoftMFC() _settings->platformType == Settings::Win64)) return; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok->next(), "DECLARE_MESSAGE_MAP ( )")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok->next(), "DECLARE_MESSAGE_MAP ( )")) { tok->deleteNext(); tok->deleteNext(); tok->deleteNext(); - } - else if (Token::Match(tok->next(), "DECLARE_DYNAMIC|DECLARE_DYNAMIC_CLASS|DECLARE_DYNCREATE ( %any% )")) - { + } else if (Token::Match(tok->next(), "DECLARE_DYNAMIC|DECLARE_DYNAMIC_CLASS|DECLARE_DYNCREATE ( %any% )")) { tok->deleteNext(); tok->deleteNext(); tok->deleteNext(); @@ -10561,26 +9084,19 @@ void Tokenizer::simplifyMicrosoftMemoryFunctions() _settings->platformType == Settings::Win64)) return; - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "CopyMemory (")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "CopyMemory (")) { tok->str("memcpy"); - } - else if (Token::simpleMatch(tok, "MoveMemory (")) - { + } else if (Token::simpleMatch(tok, "MoveMemory (")) { tok->str("memmove"); - } - else if (Token::simpleMatch(tok, "FillMemory (")) - { + } else if (Token::simpleMatch(tok, "FillMemory (")) { // FillMemory(dst, len, val) -> memset(dst, val, len) tok->str("memset"); // find first ',' Token *tok1 = tok->tokAt(2); unsigned int level = 0; - while (tok1) - { + while (tok1) { if (tok1->str() == "(") level++; else if (tok1->str() == ")") @@ -10592,12 +9108,10 @@ void Tokenizer::simplifyMicrosoftMemoryFunctions() } // find second ',' - if (tok1) - { + if (tok1) { Token *tok2 = tok1->next(); level = 0; - while (tok2) - { + while (tok2) { if (tok2->str() == "(") level++; else if (tok2->str() == ")") @@ -10609,21 +9123,17 @@ void Tokenizer::simplifyMicrosoftMemoryFunctions() } // move second argument to third position - if (tok2) - { + if (tok2) { Token::move(tok1, tok2->previous(), tok->next()->link()->previous()); } } - } - else if (Token::simpleMatch(tok, "ZeroMemory (")) - { + } else if (Token::simpleMatch(tok, "ZeroMemory (")) { // ZeroMemory(dst, len) -> memset(dst, 0, len) tok->str("memset"); Token *tok1 = tok->tokAt(2); unsigned int level = 0; - while (tok1) - { + while (tok1) { if (tok1->str() == "(") level++; else if (tok1->str() == ")") @@ -10634,8 +9144,7 @@ void Tokenizer::simplifyMicrosoftMemoryFunctions() tok1 = tok1->next(); } - if (tok1) - { + if (tok1) { tok1->insertToken("0"); tok1 = tok1->next(); tok1->insertToken(","); @@ -10647,181 +9156,98 @@ void Tokenizer::simplifyMicrosoftMemoryFunctions() void Tokenizer::simplifyMicrosoftStringFunctions() { // skip if not Windows - if (_settings->platformType == Settings::Win32A) - { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "_topen (")) - { + if (_settings->platformType == Settings::Win32A) { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "_topen (")) { tok->str("open"); - } - else if (Token::simpleMatch(tok, "_tfopen (")) - { + } else if (Token::simpleMatch(tok, "_tfopen (")) { tok->str("fopen"); - } - else if (Token::simpleMatch(tok, "_tcscat (")) - { + } else if (Token::simpleMatch(tok, "_tcscat (")) { tok->str("strcat"); - } - else if (Token::simpleMatch(tok, "_tcschr (")) - { + } else if (Token::simpleMatch(tok, "_tcschr (")) { tok->str("strchr"); - } - else if (Token::simpleMatch(tok, "_tcscmp (")) - { + } else if (Token::simpleMatch(tok, "_tcscmp (")) { tok->str("strcmp"); - } - else if (Token::simpleMatch(tok, "_tcsdup (")) - { + } else if (Token::simpleMatch(tok, "_tcsdup (")) { tok->str("strdup"); - } - else if (Token::simpleMatch(tok, "_tcscpy (")) - { + } else if (Token::simpleMatch(tok, "_tcscpy (")) { tok->str("strcpy"); - } - else if (Token::simpleMatch(tok, "_tcslen (")) - { + } else if (Token::simpleMatch(tok, "_tcslen (")) { tok->str("strlen"); - } - else if (Token::simpleMatch(tok, "_tcsncat (")) - { + } else if (Token::simpleMatch(tok, "_tcsncat (")) { tok->str("strncat"); - } - else if (Token::simpleMatch(tok, "_tcsncpy (")) - { + } else if (Token::simpleMatch(tok, "_tcsncpy (")) { tok->str("strncpy"); - } - else if (Token::simpleMatch(tok, "_tcsnlen (")) - { + } else if (Token::simpleMatch(tok, "_tcsnlen (")) { tok->str("strnlen"); - } - else if (Token::simpleMatch(tok, "_tcsrchr (")) - { + } else if (Token::simpleMatch(tok, "_tcsrchr (")) { tok->str("strrchr"); - } - else if (Token::simpleMatch(tok, "_tcsstr (")) - { + } else if (Token::simpleMatch(tok, "_tcsstr (")) { tok->str("strstr"); - } - else if (Token::simpleMatch(tok, "_tcstok (")) - { + } else if (Token::simpleMatch(tok, "_tcstok (")) { tok->str("strtok"); - } - else if (Token::simpleMatch(tok, "_tprintf (")) - { + } else if (Token::simpleMatch(tok, "_tprintf (")) { tok->str("printf"); - } - else if (Token::simpleMatch(tok, "_stprintf (")) - { + } else if (Token::simpleMatch(tok, "_stprintf (")) { tok->str("sprintf"); - } - else if (Token::simpleMatch(tok, "_sntprintf (")) - { + } else if (Token::simpleMatch(tok, "_sntprintf (")) { tok->str("snprintf"); - } - else if (Token::simpleMatch(tok, "_tscanf (")) - { + } else if (Token::simpleMatch(tok, "_tscanf (")) { tok->str("scanf"); - } - else if (Token::simpleMatch(tok, "_stscanf (")) - { + } else if (Token::simpleMatch(tok, "_stscanf (")) { tok->str("sscanf"); - } - else if (Token::Match(tok, "_T ( %str% )")) - { + } else if (Token::Match(tok, "_T ( %str% )")) { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); - } - else if (Token::Match(tok, "_T ( %any% )") && tok->strAt(2)[0] == '\'') - { + } else if (Token::Match(tok, "_T ( %any% )") && tok->strAt(2)[0] == '\'') { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); } } - } - else if (_settings->platformType == Settings::Win32W || - _settings->platformType == Settings::Win64) - { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::simpleMatch(tok, "_tcscat (")) - { + } else if (_settings->platformType == Settings::Win32W || + _settings->platformType == Settings::Win64) { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::simpleMatch(tok, "_tcscat (")) { tok->str("wcscat"); - } - else if (Token::simpleMatch(tok, "_tcschr (")) - { + } else if (Token::simpleMatch(tok, "_tcschr (")) { tok->str("wcschr"); - } - else if (Token::simpleMatch(tok, "_tcscmp (")) - { + } else if (Token::simpleMatch(tok, "_tcscmp (")) { tok->str("wcscmp"); - } - else if (Token::simpleMatch(tok, "_tcscpy (")) - { + } else if (Token::simpleMatch(tok, "_tcscpy (")) { tok->str("wcscpy"); - } - else if (Token::simpleMatch(tok, "_tcsdup (")) - { + } else if (Token::simpleMatch(tok, "_tcsdup (")) { tok->str("wcsdup"); - } - else if (Token::simpleMatch(tok, "_tcslen (")) - { + } else if (Token::simpleMatch(tok, "_tcslen (")) { tok->str("wcslen"); - } - else if (Token::simpleMatch(tok, "_tcsncat (")) - { + } else if (Token::simpleMatch(tok, "_tcsncat (")) { tok->str("wcsncat"); - } - else if (Token::simpleMatch(tok, "_tcsncpy (")) - { + } else if (Token::simpleMatch(tok, "_tcsncpy (")) { tok->str("wcsncpy"); - } - else if (Token::simpleMatch(tok, "_tcsnlen (")) - { + } else if (Token::simpleMatch(tok, "_tcsnlen (")) { tok->str("wcsnlen"); - } - else if (Token::simpleMatch(tok, "_tcsrchr (")) - { + } else if (Token::simpleMatch(tok, "_tcsrchr (")) { tok->str("wcsrchr"); - } - else if (Token::simpleMatch(tok, "_tcsstr (")) - { + } else if (Token::simpleMatch(tok, "_tcsstr (")) { tok->str("wcsstr"); - } - else if (Token::simpleMatch(tok, "_tcstok (")) - { + } else if (Token::simpleMatch(tok, "_tcstok (")) { tok->str("wcstok"); - } - else if (Token::simpleMatch(tok, "_tprintf (")) - { + } else if (Token::simpleMatch(tok, "_tprintf (")) { tok->str("wprintf"); - } - else if (Token::simpleMatch(tok, "_stprintf (")) - { + } else if (Token::simpleMatch(tok, "_stprintf (")) { tok->str("swprintf"); - } - else if (Token::simpleMatch(tok, "_sntprintf (")) - { + } else if (Token::simpleMatch(tok, "_sntprintf (")) { tok->str("snwprintf"); - } - else if (Token::simpleMatch(tok, "_tscanf (")) - { + } else if (Token::simpleMatch(tok, "_tscanf (")) { tok->str("wscanf"); - } - else if (Token::simpleMatch(tok, "_stscanf (")) - { + } else if (Token::simpleMatch(tok, "_stscanf (")) { tok->str("swscanf"); - } - else if (Token::Match(tok, "_T ( %str% )")) - { + } else if (Token::Match(tok, "_T ( %str% )")) { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); - } - else if (Token::Match(tok, "_T ( %any% )") && tok->strAt(2)[0] == '\'') - { + } else if (Token::Match(tok, "_T ( %any% )") && tok->strAt(2)[0] == '\'') { tok->deleteThis(); tok->deleteThis(); tok->deleteNext(); @@ -10833,49 +9259,37 @@ void Tokenizer::simplifyMicrosoftStringFunctions() // Remove Borland code void Tokenizer::simplifyBorland() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "( __closure * %var% )")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "( __closure * %var% )")) { tok->deleteNext(); } } // I think that these classes are always declared at the outer scope // I save some time by ignoring inner classes. - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "{") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "{") { tok = tok->link(); if (!tok) break; } - if (Token::Match(tok, "class %var% :|{")) - { + if (Token::Match(tok, "class %var% :|{")) { // count { and } for tok2 unsigned int indentlevel = 0; - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { if (indentlevel == 0) indentlevel = 1; else tok2 = tok2->link(); - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { break; - } - else if (tok2->str() == "__property" && - Token::Match(tok2->previous(), ";|{|}|protected:|public:|__published:")) - { + } else if (tok2->str() == "__property" && + Token::Match(tok2->previous(), ";|{|}|protected:|public:|__published:")) { while (tok2->next() && !Token::Match(tok2, "{|;")) tok2->deleteThis(); - if (Token::simpleMatch(tok2, "{")) - { + if (Token::simpleMatch(tok2, "{")) { Token::eraseTokens(tok2, tok2->link()); tok2->deleteThis(); tok2->deleteThis(); @@ -10894,63 +9308,48 @@ void Tokenizer::simplifyBorland() // Remove Qt signals and slots void Tokenizer::simplifyQtSignalsSlots() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { // check for emit which can be outside of class if (Token::Match(tok, "emit|Q_EMIT %var% (") && - Token::simpleMatch(tok->tokAt(2)->link(), ") ;")) - { + Token::simpleMatch(tok->tokAt(2)->link(), ") ;")) { tok->deleteThis(); - } - else if (!Token::Match(tok, "class %var% :")) + } else if (!Token::Match(tok, "class %var% :")) continue; - if (tok->previous() && tok->previous()->str() == "enum") - { + if (tok->previous() && tok->previous()->str() == "enum") { tok = tok->tokAt(2); continue; } // count { and } for tok2 unsigned int indentlevel = 0; - for (Token *tok2 = tok; tok2; tok2 = tok2->next()) - { - if (tok2->str() == "{") - { + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { + if (tok2->str() == "{") { indentlevel++; if (indentlevel == 1) tok = tok2; else tok2 = tok2->link(); - } - else if (tok2->str() == "}") - { + } else if (tok2->str() == "}") { indentlevel--; if (indentlevel == 0) break; } - if (Token::simpleMatch(tok2->next(), "Q_OBJECT")) - { + if (Token::simpleMatch(tok2->next(), "Q_OBJECT")) { tok2->deleteNext(); - } - else if (Token::Match(tok2->next(), "public|protected|private slots|Q_SLOTS :")) - { + } else if (Token::Match(tok2->next(), "public|protected|private slots|Q_SLOTS :")) { tok2 = tok2->next(); tok2->str(tok2->str() + ":"); tok2->deleteNext(); tok2->deleteNext(); tok2 = tok2->previous(); - } - else if (Token::Match(tok2->next(), "signals|Q_SIGNALS :")) - { + } else if (Token::Match(tok2->next(), "signals|Q_SIGNALS :")) { tok2 = tok2->next(); tok2->str("protected:"); tok2->deleteNext(); - } - else if (Token::Match(tok2->next(), "emit|Q_EMIT %var% (") && - Token::simpleMatch(tok2->tokAt(3)->link(), ") ;")) - { + } else if (Token::Match(tok2->next(), "emit|Q_EMIT %var% (") && + Token::simpleMatch(tok2->tokAt(3)->link(), ") ;")) { tok2->deleteNext(); } } @@ -10967,43 +9366,35 @@ const SymbolDatabase *Tokenizer::getSymbolDatabase() const void Tokenizer::simplifyOperatorName() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (tok->str() == "operator") - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (tok->str() == "operator") { // operator op std::string op; Token *par = tok->next(); bool done = false; - while (!done && par) - { + while (!done && par) { done = true; - if (par && par->isName()) - { + if (par && par->isName()) { op += par->str(); par = par->next(); done = false; } - if (Token::Match(par, "=|.|++|--|%op%")) - { + if (Token::Match(par, "=|.|++|--|%op%")) { op += par->str(); par = par->next(); done = false; } - if (Token::simpleMatch(par, "[ ]")) - { + if (Token::simpleMatch(par, "[ ]")) { op += "[]"; par = par->next()->next(); done = false; } - if (Token::Match(par, "( *| )")) - { + if (Token::Match(par, "( *| )")) { // break out and simplify.. if (Token::Match(par, "( ) const| [=;{),]")) break; - while (par->str() != ")") - { + while (par->str() != ")") { op += par->str(); par = par->next(); } @@ -11013,8 +9404,7 @@ void Tokenizer::simplifyOperatorName() } } - if (par && Token::Match(par->link(), ") const| [=;{),]")) - { + if (par && Token::Match(par->link(), ") const| [=;{),]")) { tok->str("operator" + op); Token::eraseTokens(tok,par); } @@ -11026,11 +9416,9 @@ void Tokenizer::simplifyOperatorName() void Tokenizer::removeUnnecessaryQualification() { std::vector classInfo; - for (Token *tok = _tokens; tok; tok = tok->next()) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { if (Token::Match(tok, "class|struct|namespace %type% :|{") && - (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) - { + (!tok->previous() || (tok->previous() && tok->previous()->str() != "enum"))) { Space info; info.isNamespace = tok->str() == "namespace"; tok = tok->next(); @@ -11042,53 +9430,42 @@ void Tokenizer::removeUnnecessaryQualification() return; info.classEnd = tok->link(); classInfo.push_back(info); - } - else if (!classInfo.empty()) - { + } else if (!classInfo.empty()) { if (tok == classInfo.back().classEnd) classInfo.pop_back(); else if (tok->str() == classInfo.back().className && !classInfo.back().isNamespace && tok->previous()->str() != ":" && (Token::Match(tok, "%type% :: ~| %type% (") || - Token::Match(tok, "%type% :: operator"))) - { + Token::Match(tok, "%type% :: operator"))) { int offset = 3; - if (tok->strAt(2) == "operator") - { + if (tok->strAt(2) == "operator") { const Token *tok1 = tok->tokAt(offset); // check for operator () - if (tok1->str() == "(") - { + if (tok1->str() == "(") { tok1 = tok1->next(); offset++; } - while (tok1 && tok1->str() != "(") - { + while (tok1 && tok1->str() != "(") { tok1 = tok1->next(); offset++; } - } - else if (tok->strAt(2) == "~") + } else if (tok->strAt(2) == "~") offset++; - if (Token::Match(tok->tokAt(offset)->link(), ") const| {|;|:")) - { + if (Token::Match(tok->tokAt(offset)->link(), ") const| {|;|:")) { std::string qualification = tok->str() + "::"; // check for extra qualification /** @todo this should be made more generic to handle more levels */ - if (Token::Match(tok->tokAt(-2), "%type% ::")) - { - if (classInfo.size() >= 2) - { + if (Token::Match(tok->tokAt(-2), "%type% ::")) { + if (classInfo.size() >= 2) { if (classInfo.at(classInfo.size() - 2).className != tok->strAt(-2)) continue; else qualification = tok->strAt(-2) + "::" + qualification; - } - else + } else continue; } @@ -11106,8 +9483,7 @@ void Tokenizer::removeUnnecessaryQualification() void Tokenizer::unnecessaryQualificationError(const Token *tok, const std::string &qualification) { std::list locationList; - if (tok) - { + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); loc.setfile(file(tok)); @@ -11128,10 +9504,8 @@ void Tokenizer::unnecessaryQualificationError(const Token *tok, const std::strin void Tokenizer::simplifyReturn() { - for (Token *tok = _tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "return strncat ( %any% , %any% , %any% ) ;")) - { + for (Token *tok = _tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "return strncat ( %any% , %any% , %any% ) ;")) { // Change to: strncat ( %any% , %any% , %any% ) ; tok->deleteNext(); tok->str("strncat"); @@ -11150,13 +9524,11 @@ void Tokenizer::printUnknownTypes() std::set unknowns; - for (size_t i = 1; i <= _varId; i++) - { + for (size_t i = 1; i <= _varId; i++) { const Variable *var = _symbolDatabase->getVariableFromVarId(i); // is unknown record type? - if (var && var->isClass() && !var->type()) - { + if (var && var->isClass() && !var->type()) { std::string name; // single token type? @@ -11164,13 +9536,11 @@ void Tokenizer::printUnknownTypes() name = var->typeStartToken()->str(); // complcated type - else - { + else { const Token *tok = var->typeStartToken(); int level = 0; - while (tok) - { + while (tok) { // skip pointer and reference part of type if (level == 0 && (tok->str() == "*" || tok->str() == "&")) break; @@ -11197,8 +9567,7 @@ void Tokenizer::printUnknownTypes() } } - if (!unknowns.empty()) - { + if (!unknowns.empty()) { std::ostringstream ss; ss << unknowns.size() << " unknown types:" << std::endl; diff --git a/lib/tokenize.h b/lib/tokenize.h index 957996fdd..45de86e94 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -37,8 +37,7 @@ class SymbolDatabase; /// @{ /** @brief The main purpose is to tokenize the source code. It also has functions that simplify the token list */ -class Tokenizer -{ +class Tokenizer { private: /** Deallocate lists */ void deallocateTokens(); @@ -49,8 +48,7 @@ public: virtual ~Tokenizer(); /** Is the code JAVA/C#. Used for bailouts */ - bool isJavaOrCSharp() const - { + bool isJavaOrCSharp() const { if (_files.size() != 1) return false; const std::string::size_type pos = _files[0].rfind("."); @@ -683,13 +681,11 @@ public: void unsupportedTypedef(const Token *tok) const; /** Was there templates in the code? */ - bool codeWithTemplates() const - { + bool codeWithTemplates() const { return _codeWithTemplates; } - void setSettings(const Settings *settings) - { + void setSettings(const Settings *settings) { _settings = settings; } @@ -701,8 +697,7 @@ public: * Get variable count. * @return number of variables */ - unsigned int varIdCount() const - { + unsigned int varIdCount() const { return _varId; } diff --git a/runastyle b/runastyle index e12e04954..1ee4a2288 100755 --- a/runastyle +++ b/runastyle @@ -13,7 +13,7 @@ if [[ "`astyle --version 2>&1`" != ${ASTYLE_VERSION}* ]]; then exit 1; fi -style="--style=ansi --lineend=linux --min-conditional-indent=0" +style="--style=stroustrup --indent=spaces=4 --indent-namespaces --lineend=linux --min-conditional-indent=0" options="--pad-header --unpad-paren --suffix=none" astyle $style $options cli/*.cpp diff --git a/runastyle.bat b/runastyle.bat index f8a27308f..4ee66f58d 100644 --- a/runastyle.bat +++ b/runastyle.bat @@ -1,6 +1,6 @@ REM A script to run Astyle for the sources -SET STYLE=--style=ansi --lineend=linux --min-conditional-indent=0 +SET STYLE=--style=stroustrup --indent=spaces=4 --indent-namespaces --lineend=linux --min-conditional-indent=0 SET OPTIONS=--pad-header --unpad-paren --suffix=none astyle %STYLE% %OPTIONS% cli/*.cpp diff --git a/test/options.cpp b/test/options.cpp index cb1488f90..14ac51977 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -24,8 +24,7 @@ options::options(int argc, const char* argv[]) { _options.erase("-g"); _options.erase("-q"); - if (! _options.empty()) - { + if (! _options.empty()) { _which_test = *_options.rbegin(); } } diff --git a/test/options.h b/test/options.h index 2309c71fb..3fec644f7 100644 --- a/test/options.h +++ b/test/options.h @@ -25,8 +25,7 @@ * Has getters for available switches and parameters. * See test/testoptions.cpp for sample usage. */ -class options -{ +class options { public: /** Call from main() to populate object */ options(int argc, const char* argv[]); diff --git a/test/redirect.h b/test/redirect.h index f3f532572..90ccce4e5 100644 --- a/test/redirect.h +++ b/test/redirect.h @@ -26,12 +26,10 @@ extern std::ostringstream output; * for later use. Uses RAII to stop redirection when the object goes out of * scope. */ -class RedirectOutputError -{ +class RedirectOutputError { public: /** Set up redirection, flushing anything in the pipes. */ - RedirectOutputError() - { + RedirectOutputError() { // flush all old output std::cout.flush(); std::cerr.flush(); @@ -44,8 +42,7 @@ public: } /** Revert cout and cerr behaviour */ - ~RedirectOutputError() - { + ~RedirectOutputError() { std::cout.rdbuf(_oldCout); // restore cout's original streambuf std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf diff --git a/test/test64bit.cpp b/test/test64bit.cpp index bfc0f7e8e..cf96635e2 100644 --- a/test/test64bit.cpp +++ b/test/test64bit.cpp @@ -24,8 +24,7 @@ extern std::ostringstream errout; -class Test64BitPortability : public TestFixture -{ +class Test64BitPortability : public TestFixture { public: Test64BitPortability() : TestFixture("Test64BitPortability") { } @@ -33,8 +32,7 @@ public: private: - void run() - { + void run() { TEST_CASE(novardecl); TEST_CASE(functionpar); TEST_CASE(structmember); @@ -42,8 +40,7 @@ private: TEST_CASE(ptrarithmetic); } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -61,8 +58,7 @@ private: check64BitPortability.pointerassignment(); } - void novardecl() - { + void novardecl() { // if the variable declarations can't be seen then skip the warning check("void foo()\n" "{\n" @@ -71,8 +67,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void functionpar() - { + void functionpar() { check("int foo(int *p)\n" "{\n" " int a = p;\n" @@ -102,8 +97,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning an integer (int/long/etc) to a pointer is not portable\n", errout.str()); } - void structmember() - { + void structmember() { check("struct Foo { int *p };\n" "void f(struct Foo *foo) {\n" " int i = foo->p;\n" @@ -111,8 +105,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning an address value to the integer (int/long/etc) type is not portable\n", "", errout.str()); } - void ptrcompare() - { + void ptrcompare() { // Ticket #2892 check("void foo(int *p) {\n" " int a = (p != NULL);\n" @@ -120,8 +113,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ptrarithmetic() - { + void ptrarithmetic() { // #3073 check("void foo(int *p) {\n" " int x = 10;\n" diff --git a/test/testassignif.cpp b/test/testassignif.cpp index 6d483275c..4c1d49ab6 100644 --- a/test/testassignif.cpp +++ b/test/testassignif.cpp @@ -24,8 +24,7 @@ extern std::ostringstream errout; -class TestAssignIf : public TestFixture -{ +class TestAssignIf : public TestFixture { public: TestAssignIf() : TestFixture("TestAssignIf") { } @@ -33,15 +32,13 @@ public: private: - void run() - { + void run() { TEST_CASE(assignAndCompare); // assignment and comparison don't match TEST_CASE(compare); // mismatching LHS/RHS in comparison TEST_CASE(multicompare); // mismatching comparisons } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -62,8 +59,7 @@ private: checkAssignIf.multiCondition(); } - void assignAndCompare() - { + void assignAndCompare() { // & check("void foo(int x)\n" "{\n" @@ -93,8 +89,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void compare() - { + void compare() { check("void foo(int x)\n" "{\n" " if (x & 4 == 3);\n" @@ -114,8 +109,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Mismatching comparison, the result is always true\n", errout.str()); } - void multicompare() - { + void multicompare() { check("void foo(int x)\n" "{\n" " if (x & 7);\n" diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index dbe19d818..9c41d65fb 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -25,8 +25,7 @@ extern std::ostringstream errout; -class TestAutoVariables : public TestFixture -{ +class TestAutoVariables : public TestFixture { public: TestAutoVariables() : TestFixture("TestAutoVariables") { } @@ -35,8 +34,7 @@ private: - void check(const char code[], bool inconclusive=false) - { + void check(const char code[], bool inconclusive=false) { // Clear the error buffer.. errout.str(""); @@ -65,8 +63,7 @@ private: checkAutoVariables.returncstr(); } - void run() - { + void run() { TEST_CASE(testautovar1); TEST_CASE(testautovar2); TEST_CASE(testautovar3); // ticket #2925 @@ -105,8 +102,7 @@ private: - void testautovar1() - { + void testautovar1() { check("void func1(int **res)\n" "{\n" " int num = 2;\n" @@ -129,8 +125,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar2() - { + void testautovar2() { check("class Fred {\n" " void func1(int **res);\n" "}\n" @@ -162,8 +157,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar3() // ticket #2925 - { + void testautovar3() { // ticket #2925 check("void foo(int **p)\n" "{\n" " int x[100];\n" @@ -172,8 +166,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Assigning address of local auto-variable to a function parameter.\n", errout.str()); } - void testautovar4() // ticket #2928 - { + void testautovar4() { // ticket #2928 check("void foo(int **p)\n" "{\n" " static int x[100];\n" @@ -182,8 +175,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar5() // ticket #2926 - { + void testautovar5() { // ticket #2926 check("void foo(struct AB *ab)\n" "{\n" " char a;\n" @@ -199,8 +191,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Inconclusive: Assigning address of local auto-variable to a function parameter.\n", errout.str()); } - void testautovar6() // ticket #2931 - { + void testautovar6() { // ticket #2931 check("void foo(struct X *x)\n" "{\n" " char a[10];\n" @@ -216,8 +207,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Inconclusive: Assigning address of local auto-variable to a function parameter.\n", errout.str()); } - void testautovar7() // ticket #3066 - { + void testautovar7() { // ticket #3066 check("struct txt_scrollpane_s * TXT_NewScrollPane(struct txt_widget_s * target)\n" "{\n" " struct txt_scrollpane_s * scrollpane;\n" @@ -227,8 +217,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar_array1() - { + void testautovar_array1() { check("void func1(int* arr[2])\n" "{\n" " int num=2;" @@ -237,8 +226,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Assigning address of local auto-variable to a function parameter.\n", errout.str()); } - void testautovar_array2() - { + void testautovar_array2() { check("class Fred {\n" " void func1(int* arr[2]);\n" "}\n" @@ -250,8 +238,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Assigning address of local auto-variable to a function parameter.\n", errout.str()); } - void testautovar_return1() - { + void testautovar_return1() { check("int* func1()\n" "{\n" " int num=2;" @@ -260,8 +247,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Return of the address of an auto-variable\n", errout.str()); } - void testautovar_return2() - { + void testautovar_return2() { check("class Fred {\n" " int* func1()\n" "}\n" @@ -273,8 +259,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Return of the address of an auto-variable\n", errout.str()); } - void testautovar_return3() - { + void testautovar_return3() { // #2975 - FP check("void** f()\n" "{\n" @@ -284,8 +269,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar_return4() - { + void testautovar_return4() { // #3030 check("char *foo()\n" "{\n" @@ -302,8 +286,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testautovar_extern() - { + void testautovar_extern() { check("struct foo *f()\n" "{\n" " extern struct foo f;\n" @@ -312,8 +295,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testinvaliddealloc() - { + void testinvaliddealloc() { check("int* func1()\n" "{\n" "int a;\n" @@ -334,8 +316,7 @@ private: ASSERT_EQUALS(std::string(""), errout.str()); } - void testassign1() // Ticket #1819 - { + void testassign1() { // Ticket #1819 check("void f(EventPtr *eventP, ActionPtr **actionsP) {\n" " EventPtr event = *eventP;\n" " *actionsP = &event->actions;\n" @@ -343,8 +324,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testassign2() // Ticket #2765 - { + void testassign2() { // Ticket #2765 check("static void function(unsigned long **datap) {\n" " struct my_s *mr = global_structure_pointer;\n" " *datap = &mr->value;\n" @@ -352,8 +332,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void returnLocalVariable1() - { + void returnLocalVariable1() { check("char *foo()\n" "{\n" " char str[100] = {0};\n" @@ -372,8 +351,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Returning pointer to local array variable\n", errout.str()); } - void returnLocalVariable2() - { + void returnLocalVariable2() { check("std::string foo()\n" "{\n" " char str[100] = {0};\n" @@ -392,8 +370,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void returnReference1() - { + void returnReference1() { check("std::string &foo()\n" "{\n" " std::string s;\n" @@ -427,8 +404,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) Returning reference to temporary\n", errout.str()); } - void returnReference2() - { + void returnReference2() { check("class Fred {\n" " std::string &foo();\n" "}\n" @@ -487,8 +463,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Returning reference to temporary\n", errout.str()); } - void returnReference3() - { + void returnReference3() { check("double & f(double & rd) {\n" " double ret = getValue();\n" " rd = ret;\n" @@ -497,8 +472,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void returncstr1() - { + void returncstr1() { check("const char *foo()\n" "{\n" " std::string s;\n" @@ -525,8 +499,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) Returning pointer to temporary\n", errout.str()); } - void returncstr2() - { + void returncstr2() { check("class Fred {\n" " const char *foo();\n" "};\n" @@ -563,8 +536,7 @@ private: } - void testglobalnamespace() - { + void testglobalnamespace() { check("class SharedPtrHolder\n" "{\n" " ::std::tr1::shared_ptr pNum;\n" @@ -578,8 +550,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void returnParameterAddress() - { + void returnParameterAddress() { check("int* foo(int y)\n" "{\n" " return &y;\n" diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index c62b995e2..6cbcc81d5 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -26,8 +26,7 @@ extern std::ostringstream errout; -class TestBufferOverrun : public TestFixture -{ +class TestBufferOverrun : public TestFixture { public: TestBufferOverrun() : TestFixture("TestBufferOverrun") { } @@ -36,8 +35,7 @@ private: - void check(const char code[], bool experimental = true) - { + void check(const char code[], bool experimental = true) { // Clear the error buffer.. errout.str(""); @@ -65,8 +63,7 @@ private: checkBufferOverrun.arrayIndexThenCheck(); } - void run() - { + void run() { TEST_CASE(noerr1); TEST_CASE(noerr2); TEST_CASE(noerr3); @@ -241,8 +238,7 @@ private: - void noerr1() - { + void noerr1() { check("extern int ab;\n" "void f()\n" "{\n" @@ -259,8 +255,7 @@ private: } - void noerr2() - { + void noerr2() { check("static char buf[2];\n" "void f1(char *str)\n" "{\n" @@ -282,8 +277,7 @@ private: } - void noerr3() - { + void noerr3() { check("struct { char data[10]; } abc;\n" "static char f()\n" "{\n" @@ -294,8 +288,7 @@ private: } - void noerr4() - { + void noerr4() { // The memory isn't read or written and therefore there is no error. check("static void f()\n" "{\n" @@ -308,8 +301,7 @@ private: - void sizeof1() - { + void sizeof1() { check("static void f()\n" "{\n" " char data[10];\n" @@ -318,8 +310,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sizeof2() - { + void sizeof2() { check("static void f()\n" "{\n" " char data[10];\n" @@ -335,8 +326,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'data[2]' index 4 out of bounds\n", errout.str()); } - void sizeof3() - { + void sizeof3() { check("struct group { int gr_gid; };\n" "void f()\n" "{\n" @@ -350,8 +340,7 @@ private: - void arrayInfo() - { + void arrayInfo() { // Clear the error buffer.. errout.str(""); @@ -369,8 +358,7 @@ private: } - void array_index_1() - { + void array_index_1() { check("void f()\n" "{\n" " char str[0x10];\n" @@ -388,8 +376,7 @@ private: } - void array_index_2() - { + void array_index_2() { check("void f()\n" "{\n" " char *str = new char[0x10];\n" @@ -400,8 +387,7 @@ private: } - void array_index_3() - { + void array_index_3() { { check("void f()\n" "{\n" @@ -469,8 +455,7 @@ private: } } - void array_index_4() - { + void array_index_4() { check("const int SIZE = 10;\n" "void f()\n" "{\n" @@ -481,8 +466,7 @@ private: } - void array_index_5() - { + void array_index_5() { check("void f()\n" "{\n" " int i[10];\n" @@ -492,8 +476,7 @@ private: } - void array_index_6() - { + void array_index_6() { check("struct ABC\n" "{\n" " char str[10];\n" @@ -642,8 +625,7 @@ private: } - void array_index_7() - { + void array_index_7() { check("struct ABC\n" "{\n" " char str[10];\n" @@ -657,8 +639,7 @@ private: } - void array_index_8() - { + void array_index_8() { check("const int SIZE = 10;\n" "\n" "struct ABC\n" @@ -674,8 +655,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Array 'abc.str[10]' index 10 out of bounds\n", errout.str()); } - void array_index_9() - { + void array_index_9() { check("static void memclr( char *data )\n" "{\n" " data[10] = 0;\n" @@ -743,8 +723,7 @@ private: } - void array_index_11() - { + void array_index_11() { check("class ABC\n" "{\n" "public:\n" @@ -765,8 +744,7 @@ private: } - void array_index_12() - { + void array_index_12() { check("class Fred\n" "{\n" "private:\n" @@ -794,8 +772,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (error) Array 'str[10]' index 10 out of bounds\n", errout.str()); } - void array_index_13() - { + void array_index_13() { check("void f()\n" "{\n" " char buf[10];\n" @@ -808,8 +785,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_14() - { + void array_index_14() { check("void f()\n" "{\n" " int a[10];\n" @@ -819,8 +795,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' index 19 out of bounds\n", errout.str()); } - void array_index_15() - { + void array_index_15() { check("void f()\n" "{\n" " int a[10];\n" @@ -830,8 +805,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' index 19 out of bounds\n", errout.str()); } - void array_index_16() - { + void array_index_16() { check("void f()\n" "{\n" " int a[10];\n" @@ -841,8 +815,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' index 10 out of bounds\n", errout.str()); } - void array_index_17() - { + void array_index_17() { check("void f()\n" "{\n" " int a[10];\n" @@ -868,8 +841,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[12]' index 12 out of bounds\n", errout.str()); } - void array_index_18() - { + void array_index_18() { check("void f()\n" "{\n" " int a[5];\n" @@ -926,8 +898,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Buffer overrun\n", "", errout.str()); } - void array_index_19() - { + void array_index_19() { // "One Past the End" is legal, as long as pointer is not dereferenced. check("void f()\n" "{\n" @@ -945,8 +916,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2]' index 3 out of bounds\n", errout.str()); } - void array_index_20() - { + void array_index_20() { check("void f()\n" "{\n" " char a[8];\n" @@ -957,8 +927,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_21() - { + void array_index_21() { check("class A {\n" " int indices[2];\n" " void foo(int indices[3]);\n" @@ -972,8 +941,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_22() - { + void array_index_22() { check("#include \n" "int main() {\n" " size_t indices[2];\n" @@ -982,8 +950,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'indices[2]' index 2 out of bounds\n", errout.str()); } - void array_index_23() - { + void array_index_23() { check("void foo()\n" "{\n" " char c[10];\n" @@ -992,8 +959,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'c[10]' index 8388608 out of bounds\n", errout.str()); } - void array_index_24() - { + void array_index_24() { // ticket #1492 and #1539 // CHAR_MAX can be equal to SCHAR_MAX or UCHAR_MAX depending on the environment. // This test should work for both environments. @@ -1047,8 +1013,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[32768]' index 32768 out of bounds\n" "[test.cpp:3]: (error) Array index -1 is out of bounds\n", errout.str()); - if (sizeof(int) == 4) - { + if (sizeof(int) == 4) { check("void f(int n) {\n" " int a[n];\n" // n <= INT_MAX " a[-1] = 0;\n" // negative index @@ -1069,8 +1034,7 @@ private: } } - void array_index_25() - { + void array_index_25() { // ticket #1536 check("void foo()\n" "{\n" @@ -1079,8 +1043,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_26() - { + void array_index_26() { check("void f()\n" "{\n" " int a[3];\n" @@ -1098,8 +1061,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_27() - { + void array_index_27() { check("void f()\n" "{\n" " int a[10];\n" @@ -1109,8 +1071,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' index -1 out of bounds\n", errout.str()); } - void array_index_28() - { + void array_index_28() { // ticket #1418 check("void f()\n" "{\n" @@ -1121,8 +1082,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Array ip[-10] out of bounds\n", "", errout.str()); } - void array_index_29() - { + void array_index_29() { // ticket #1724 check("void f()\n" "{\n" @@ -1134,8 +1094,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Array ii[10] out of bounds\n", "", errout.str()); } - void array_index_30() - { + void array_index_30() { // ticket #2086 - unknown type check("void f() {\n" " UINT8 x[2];\n" @@ -1144,8 +1103,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Array 'x[2]' index 5 out of bounds\n", errout.str()); } - void array_index_31() - { + void array_index_31() { // ticket #2120 - sub function, unknown type check("struct s1 {\n" " unknown_type_t delay[3];\n" @@ -1185,8 +1143,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_32() - { + void array_index_32() { check("class X\n" "{\n" " public:\n" @@ -1200,16 +1157,14 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Array 'm_x[1]' index 1 out of bounds\n", errout.str()); } - void array_index_33() - { + void array_index_33() { check("void foo(char bar[][4]) {\n" " baz(bar[5]);\n" "}\n"); ASSERT_EQUALS("", errout.str()); } - void array_index_34() // ticket #3063 - { + void array_index_34() { // ticket #3063 check("void foo() {\n" " int y[2][2][2];\n" " y[0][2][0] = 0;\n" @@ -1262,8 +1217,7 @@ private: "[test.cpp:13]: (error) Array 'ptest.a[10][5]' index ptest.a[0][50] out of bounds\n", errout.str()); } - void array_index_35() // ticket #2889 - { + void array_index_35() { // ticket #2889 check("void f() {\n" " struct Struct { unsigned m_Var[1]; } s;\n" " s.m_Var[1] = 1;\n" @@ -1285,8 +1239,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_36() // ticket #2960 - { + void array_index_36() { // ticket #2960 check("class Fred {\n" " Fred(const Fred &);\n" "private:\n" @@ -1299,8 +1252,7 @@ private: "[test.cpp:7]: (error) Array 'rhs.m_b[2]' index 2 out of bounds\n", errout.str()); } - void array_index_37() - { + void array_index_37() { check("class Fred {\n" " char x[X];\n" " Fred() {\n" @@ -1311,8 +1263,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_multidim() - { + void array_index_multidim() { check("void f()\n" "{\n" " char a[2][2];\n" @@ -1412,8 +1363,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_switch_in_for() - { + void array_index_switch_in_for() { check("void f()\n" "{\n" " int ar[10];\n" @@ -1451,8 +1401,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:12]: (error) Array index out of bounds\n", "", errout.str()); } - void array_index_for_in_for() - { + void array_index_for_in_for() { check("void f() {\n" " int a[5];\n" " for (int i = 0; i < 10; ++i) {\n" @@ -1464,8 +1413,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_calculation() - { + void array_index_calculation() { // #1193 - false negative: array out of bounds in loop when there is calculation check("void f()\n" "{\n" @@ -1487,8 +1435,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'arr[5]' index 11 out of bounds\n", errout.str()); } - void array_index_negative1() - { + void array_index_negative1() { // #948 - array index out of bound not detected 'a[-1] = 0' check("void f()\n" "{\n" @@ -1527,8 +1474,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_negative2() // ticket #3063 - { + void array_index_negative2() { // ticket #3063 check("struct TEST { char a[10]; };\n" "void foo() {\n" " TEST test;\n" @@ -1537,8 +1483,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 'test.a[10]' index -1 out of bounds\n", errout.str()); } - void array_index_for_decr() - { + void array_index_for_decr() { check("void f()\n" "{\n" " char data[8];\n" @@ -1568,8 +1513,7 @@ private: } - void array_index_varnames() - { + void array_index_varnames() { check("struct A {\n" " char data[4];\n" " struct B { char data[3]; };\n" @@ -1585,8 +1529,7 @@ private: } - void array_index_for_break() - { + void array_index_for_break() { check("void f() {\n" " int a[2];\n" " for (int i = 0; i <= 2; ++i) {\n" @@ -1599,8 +1542,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_for() - { + void array_index_for() { // Ticket #2370 - No false negative when there is no "break" check("void f() {\n" " int a[10];\n" @@ -1625,8 +1567,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_for_neq() - { + void array_index_for_neq() { // Ticket #2211 - for loop using != in the condition check("void f() {\n" " int a[5];\n" @@ -1637,8 +1578,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Buffer access out-of-bounds: a\n", errout.str()); } - void array_index_for_question() - { + void array_index_for_question() { // Ticket #2561 - using ?: inside for loop check("void f() {\n" " int a[10];\n" @@ -1649,16 +1589,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void array_index_extern() - { + void array_index_extern() { // Ticket #1684. FP when using 'extern'. check("extern char arr[15];\n" "char arr[15] = \"abc\";"); ASSERT_EQUALS("", errout.str()); } - void array_index_cast() - { + void array_index_cast() { // Ticket #2841. FP when using cast. // Different types => no error @@ -1682,8 +1620,7 @@ private: ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (error) Array 'x[2]' index 4 out of bounds\n", errout.str()); } - void buffer_overrun_1() - { + void buffer_overrun_1() { check("void f()\n" "{\n" " char str[3];\n" @@ -1817,8 +1754,7 @@ private: } - void buffer_overrun_2() - { + void buffer_overrun_2() { check("struct ABC\n" "{\n" " char str[5];\n" @@ -1877,8 +1813,7 @@ private: } - void buffer_overrun_3() - { + void buffer_overrun_3() { check("int a[10];\n" "\n" "void foo()\n" @@ -1891,8 +1826,7 @@ private: } - void buffer_overrun_4() - { + void buffer_overrun_4() { check("void foo()\n" "{\n" " const char *p[2];\n" @@ -1934,8 +1868,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_5() - { + void buffer_overrun_5() { check("void f()\n" "{\n" " char n[5];\n" @@ -1945,8 +1878,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_6() - { + void buffer_overrun_6() { check("void f()\n" "{\n" " char n[5];\n" @@ -1963,8 +1895,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Buffer access out-of-bounds: n\n", errout.str()); } - void buffer_overrun_7() - { + void buffer_overrun_7() { // ticket #731 check("void f()\n" "{\n" @@ -1974,8 +1905,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_8() - { + void buffer_overrun_8() { // ticket #714 check("void f()\n" "{\n" @@ -2008,8 +1938,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_9() - { + void buffer_overrun_9() { // ticket #738 check("void f()\n" "{\n" @@ -2023,8 +1952,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_10() - { + void buffer_overrun_10() { // ticket #740 check("void f()\n" "{\n" @@ -2037,8 +1965,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_11() - { + void buffer_overrun_11() { check("void f()\n" "{\n" " char a[4];\n" @@ -2067,8 +1994,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_12() - { + void buffer_overrun_12() { // ticket #900 check("void f() {\n" " char *a = new char(30);\n" @@ -2078,8 +2004,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Buffer access out-of-bounds\n", errout.str()); } - void buffer_overrun_13() - { + void buffer_overrun_13() { // ticket #836 check("void f() {\n" " char a[10];\n" @@ -2094,8 +2019,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Buffer access out-of-bounds: a\n", errout.str()); } - void buffer_overrun_14() - { + void buffer_overrun_14() { check("void f(char *a) {\n" " char *b = new char[strlen(a)];\n" " strcpy(b, a);\n" @@ -2171,8 +2095,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Buffer access out-of-bounds\n", errout.str()); } - void buffer_overrun_15() // ticket #1787 - { + void buffer_overrun_15() { // ticket #1787 check("class A : public B {\n" " char val[12];\n" " void f(int i, int ii);\n" @@ -2184,8 +2107,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Buffer access out-of-bounds\n", errout.str()); } - void buffer_overrun_16() - { + void buffer_overrun_16() { // unknown types check("void f() {\n" " struct Foo foo[5];\n" @@ -2207,8 +2129,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_17() // ticket #2548 - { + void buffer_overrun_17() { // ticket #2548 check("void f() {\n" " char t[8];\n" " sprintf(t, \"%s\", \"foo bar\");\n" @@ -2216,8 +2137,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Buffer access out-of-bounds\n", errout.str()); } - void buffer_overrun_18() // ticket #2576 - { + void buffer_overrun_18() { // ticket #2576 check("class A {\n" " void foo();\n" " bool b[7];\n" @@ -2243,8 +2163,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) Array 'b[7]' index 7 out of bounds\n", errout.str()); } - void buffer_overrun_19() // #2597 - class member with unknown type - { + void buffer_overrun_19() { // #2597 - class member with unknown type check("class A {\n" "public:\n" " u8 buf[10];\n" @@ -2257,14 +2176,12 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_20() // #2986(segmentation fault) - { + void buffer_overrun_20() { // #2986(segmentation fault) check("x[y]\n"); ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_21() - { + void buffer_overrun_21() { check("void foo()\n" "{ { {\n" " char dst[4];\n" @@ -2275,8 +2192,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Buffer access out-of-bounds: dst\n", errout.str()); } - void buffer_overrun_22() // ticket #3124 - { + void buffer_overrun_22() { // ticket #3124 check("class A {\n" "public:\n" " char b[5][6];\n" @@ -2300,8 +2216,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Buffer access out-of-bounds: a.b\n", errout.str()); } - void buffer_overrun_23() // ticket #3153 - { + void buffer_overrun_23() { // ticket #3153 check("void foo() {\n" " double dest = 23.0;\n" " char* const source = (char*) malloc(sizeof(dest));\n" @@ -2319,8 +2234,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void buffer_overrun_bailoutIfSwitch() - { + void buffer_overrun_bailoutIfSwitch() { // No false positive check("void f1(char *s) {\n" " if (x) s[100] = 0;\n" @@ -2357,8 +2271,7 @@ private: ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (error) Array 'a[10]' index 100 out of bounds\n", errout.str()); } - void possible_buffer_overrun_1() // #3035 - { + void possible_buffer_overrun_1() { // #3035 check("void foo() {\n" " char * data = (char *)alloca(50);\n" " char src[100];\n" @@ -2420,8 +2333,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void pointer_out_of_bounds_1() - { + void pointer_out_of_bounds_1() { check("void f() {\n" " char a[10];\n" " char *p = a + 100;\n" @@ -2429,8 +2341,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour: pointer arithmetic result does not point into or just past the end of the array\n", errout.str()); } - void pointer_out_of_bounds_2() - { + void pointer_out_of_bounds_2() { check("void f() {\n" " char *p = malloc(10);\n" " p += 100;\n" @@ -2465,8 +2376,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf1() - { + void sprintf1() { check("void f()\n" "{\n" " char str[3];\n" @@ -2483,8 +2393,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Buffer access out-of-bounds\n", errout.str()); } - void sprintf2() - { + void sprintf2() { check("int getnumber();\n" "void f()\n" "{\n" @@ -2494,8 +2403,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Buffer access out-of-bounds\n", errout.str()); } - void sprintf3() - { + void sprintf3() { check("void f()\n" "{\n" " char str[3];\n" @@ -2511,8 +2419,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf4() - { + void sprintf4() { // ticket #690 check("void f()\n" "{\n" @@ -2522,8 +2429,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf5() - { + void sprintf5() { // ticket #729 check("void f(int condition)\n" "{\n" @@ -2533,8 +2439,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf6() - { + void sprintf6() { check("void f(int condition)\n" "{\n" " char buf[3];\n" @@ -2543,8 +2448,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer access out-of-bounds\n", "", errout.str()); } - void sprintf7() - { + void sprintf7() { check("struct Foo { char a[1]; };\n" "void f()\n" "{\n" @@ -2572,8 +2476,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf8() - { + void sprintf8() { check("struct Foo { char a[3]; };\n" "void f()\n" "{\n" @@ -2583,8 +2486,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf9() - { + void sprintf9() { check("void f()\n" "{\n" " gchar str[3];\n" @@ -2593,8 +2495,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf10() - { + void sprintf10() { check("void f()\n" "{\n" " TString str = \"\";\n" @@ -2603,8 +2504,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf1() - { + void snprintf1() { check("void f()\n" "{\n" " char str[5];\n" @@ -2613,8 +2513,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) snprintf size is out of bounds: Supplied size 10 is larger than actual size of 5\n", errout.str()); } - void snprintf2() - { + void snprintf2() { check("void f()\n" "{\n" " char str[5];\n" @@ -2623,8 +2522,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf3() - { + void snprintf3() { check("void f()\n" "{\n" " char str[5];\n" @@ -2633,8 +2531,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf4() - { + void snprintf4() { check("void f(int x)\n" "{\n" " char str[5];\n" @@ -2643,8 +2540,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf5() - { + void snprintf5() { check("struct Foo { char a[1]; };\n" "void f()\n" "{\n" @@ -2672,8 +2568,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf6() - { + void snprintf6() { check("struct Foo { char a[3]; };\n" "void f()\n" "{\n" @@ -2683,8 +2578,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf7() - { + void snprintf7() { check("void x() {\n" " const int nBezString = 1024;\n" " sal_Char pString[nBezString];\n" @@ -2693,8 +2587,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void strncat1() - { + void strncat1() { check("void f(char *a, char *b)\n" "{\n" " char str[16];\n" @@ -2704,8 +2597,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (warning) Dangerous usage of strncat - 3rd parameter is the maximum number of characters to append.\n", errout.str()); } - void strncat2() - { + void strncat2() { check("void f(char *a)\n" "{\n" " char str[5];\n" @@ -2714,8 +2606,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) Dangerous usage of strncat - 3rd parameter is the maximum number of characters to append.\n", errout.str()); } - void strncat3() - { + void strncat3() { check("struct Foo { char a[4]; };\n" "void f(char *a)\n" "{\n" @@ -2726,8 +2617,7 @@ private: } - void strcat1() - { + void strcat1() { check("struct Foo { char a[4]; };\n" "void f()\n" "{\n" @@ -2738,8 +2628,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Buffer access out-of-bounds\n", errout.str()); } - void strcat2() - { + void strcat2() { check("struct Foo { char a[5]; };\n" "void f()\n" "{\n" @@ -2750,8 +2639,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void strcat3() - { + void strcat3() { check("void f() {\n" " INT str[10];\n" " strcat(str, \"aa\");\n" @@ -2761,8 +2649,7 @@ private: // memchr/memset/memcpy/etc - void memfunc1() - { + void memfunc1() { check("struct S {\n" " char a[5];\n" "};\n" @@ -2804,8 +2691,7 @@ private: } // ticket #2121 - buffer access out of bounds when using uint32_t - void memfunc2() - { + void memfunc2() { check("void f()\n" "{\n" " unknown_type_t buf[4];\n" @@ -2814,8 +2700,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varid1() - { + void varid1() { check("void foo()\n" "{\n" " char str[10];\n" @@ -2829,8 +2714,7 @@ private: } - void varid2() - { + void varid2() { check("void foo()\n" "{\n" " char str[10];\n" @@ -2843,8 +2727,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign1() - { + void assign1() { check("char str[3] = {'a', 'b', 'c'};\n" "\n" "void foo()\n" @@ -2854,8 +2737,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'str[3]' index 3 out of bounds\n", errout.str()); } - void alloc1() - { + void alloc1() { check("void foo()\n" "{\n" " char *s = new char[10];\n" @@ -2922,8 +2804,7 @@ private: } // data is allocated with malloc - void alloc2() - { + void alloc2() { check("void foo()\n" "{\n" " char *s = (char *)malloc(10);\n" @@ -2948,8 +2829,7 @@ private: } // statically allocated buffer - void alloc3() - { + void alloc3() { check("void foo()\n" "{\n" " const char *s = \"123\";\n" @@ -2973,8 +2853,7 @@ private: } // data is allocated with alloca - void alloc4() - { + void alloc4() { check("void foo()\n" "{\n" " char *s = (char *)alloca(10);\n" @@ -2983,8 +2862,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' index 10 out of bounds\n", errout.str()); } - void malloc_memset() - { + void malloc_memset() { check("void f() {\n" " char *p = malloc(10);\n" " memset(p,0,100);\n" @@ -2992,8 +2870,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Buffer access out-of-bounds\n", errout.str()); } - void memset1() - { + void memset1() { check("void foo()\n" "{\n" " char s[10];\n" @@ -3009,8 +2886,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void memset2() - { + void memset2() { check("class X {\n" " char* array[2];\n" " X();\n" @@ -3021,8 +2897,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void counter_test() - { + void counter_test() { std::list unknownParameter; unknownParameter.push_back(0); @@ -3100,8 +2975,7 @@ private: } - void strncpy1() - { + void strncpy1() { check("void f()\n" "{\n" " char a[6];\n" @@ -3151,8 +3025,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void unknownType() - { + void unknownType() { check("void f()\n" "{\n" " UnknownType *a = malloc(4);\n" @@ -3160,8 +3033,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void terminateStrncpy1() - { + void terminateStrncpy1() { check("void foo ( char *bar )\n" "{\n" " char baz[100];\n" @@ -3193,8 +3065,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) The buffer 'baz' may not be zero-terminated after the call to strncpy().\n", errout.str()); } - void terminateStrncpy2() - { + void terminateStrncpy2() { check("char *foo ( char *bar )\n" "{\n" " char baz[100];\n" @@ -3205,8 +3076,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) The buffer 'baz' may not be zero-terminated after the call to strncpy().\n", errout.str()); } - void terminateStrncpy3() - { + void terminateStrncpy3() { // Ticket #2170 - false positive // The function bar is risky. But it might work that way intentionally. check("char str[100];\n" @@ -3221,8 +3091,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) The buffer 'str' may not be zero-terminated after the call to strncpy().\n", errout.str()); } - void recursive_long_time() - { + void recursive_long_time() { // Just test that recursive check doesn't take long time check("char *f2 ( char *b )\n" "{\n" @@ -3252,8 +3121,7 @@ private: // Ticket #1587 - crash - void crash1() - { + void crash1() { check("struct struct A\n" "{\n" " int alloclen;\n" @@ -3267,13 +3135,11 @@ private: ASSERT_EQUALS("", errout.str()); } - void crash2() - { + void crash2() { check("struct C {} {} x"); } - void crash3() - { + void crash3() { check("void a(char *p) {\n" " f( { if(finally_arg); } );\n" "}\n" @@ -3285,8 +3151,7 @@ private: } - void epcheck(const char code[]) - { + void epcheck(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -3304,8 +3169,7 @@ private: } - void executionPaths1() - { + void executionPaths1() { epcheck("void f(int a)\n" "{\n" " int buf[10];\n" @@ -3327,8 +3191,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Array 'buf[10][5]' index 1000 out of bounds\n", errout.str()); } - void executionPaths2() - { + void executionPaths2() { epcheck("void foo()\n" "{\n" " char a[64];\n" @@ -3339,8 +3202,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void executionPaths3() - { + void executionPaths3() { epcheck("void f(char *VLtext)\n" "{\n" " if ( x ) {\n" @@ -3353,8 +3215,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void executionPaths4() - { + void executionPaths4() { // Ticket #2386 - Segmentation fault upon strange syntax epcheck("void f() {\n" " switch ( x ) {\n" @@ -3364,8 +3225,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void executionPaths5() - { + void executionPaths5() { // No false positive epcheck("class A {\n" " void foo() {\n" @@ -3378,8 +3238,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void cmdLineArgs1() - { + void cmdLineArgs1() { check("int main(int argc, char* argv[])\n" "{\n" " char prog[10];\n" @@ -3488,8 +3347,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void scope() - { + void scope() { check("class A {\n" "private:\n" " struct X { char buf[10]; };\n" @@ -3515,15 +3373,13 @@ private: TODO_ASSERT_EQUALS("[test.cpp:9]: (error) Array 'x.buf[10]' index 10 out of bounds\n", "", errout.str()); } - void getErrorMessages() - { + void getErrorMessages() { // Ticket #2292: segmentation fault when using --errorlist CheckBufferOverrun c; c.getErrorMessages(this, 0); } - void unknownMacroNoDecl() - { + void unknownMacroNoDecl() { check("void f() {\n" " int a[10];\n" " AAA a[0] = 0;\n" // <- not a valid array declaration @@ -3532,8 +3388,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void arrayIndexThenCheck() - { + void arrayIndexThenCheck() { check("void f(const char s[]) {\n" " if (s[i] == 'x' && i < y) {\n" " }" @@ -3547,8 +3402,7 @@ private: ASSERT_EQUALS("[test.cpp:2]: (style) Array index i is used before limits check\n", errout.str()); } - void bufferNotZeroTerminated() - { + void bufferNotZeroTerminated() { check("void f()\n" "{\n" " char c[6];\n" diff --git a/test/testcharvar.cpp b/test/testcharvar.cpp index 7b7a8b206..e1d2571fc 100644 --- a/test/testcharvar.cpp +++ b/test/testcharvar.cpp @@ -24,8 +24,7 @@ extern std::ostringstream errout; -class TestCharVar : public TestFixture -{ +class TestCharVar : public TestFixture { public: TestCharVar() : TestFixture("TestCharVar") { } @@ -33,8 +32,7 @@ public: private: - void run() - { + void run() { TEST_CASE(array_index); TEST_CASE(bitop1); TEST_CASE(bitop2); @@ -44,8 +42,7 @@ private: TEST_CASE(pointer); } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -63,8 +60,7 @@ private: checkOther.checkCharVariable(); } - void array_index() - { + void array_index() { check("void foo()\n" "{\n" " unsigned char ch = 0x80;\n" @@ -100,8 +96,7 @@ private: } - void bitop1() - { + void bitop1() { check("void foo()\n" "{\n" " int result = 0;\n" @@ -111,8 +106,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) When using char variables in bit operations, sign extension can generate unexpected results.\n", errout.str()); } - void bitop2() - { + void bitop2() { check("void foo()\n" "{\n" " char ch;\n" @@ -121,8 +115,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void return1() - { + void return1() { check("void foo()\n" "{\n" " char c;\n" @@ -132,8 +125,7 @@ private: } - void assignChar() - { + void assignChar() { check("void foo()\n" "{\n" " char c;\n" @@ -142,8 +134,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void and03() - { + void and03() { check("void foo()\n" "{\n" " char c;\n" @@ -152,8 +143,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void pointer() - { + void pointer() { // ticket #2866 check("void f(char *p) {\n" " int ret = 0;\n" diff --git a/test/testclass.cpp b/test/testclass.cpp index 50d12cdcc..6b53fc10d 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -25,16 +25,14 @@ extern std::ostringstream errout; -class TestClass : public TestFixture -{ +class TestClass : public TestFixture { public: TestClass() : TestFixture("TestClass") { } private: - void run() - { + void run() { TEST_CASE(virtualDestructor1); // Base class not found => no error TEST_CASE(virtualDestructor2); // Base class doesn't have a destructor TEST_CASE(virtualDestructor3); // Base class has a destructor, but it's not virtual @@ -210,8 +208,7 @@ private: } // Check the operator Equal - void checkOpertorEq(const char code[]) - { + void checkOpertorEq(const char code[]) { // Clear the error log errout.str(""); @@ -229,8 +226,7 @@ private: checkClass.operatorEq(); } - void operatorEq1() - { + void operatorEq1() { checkOpertorEq("class A\n" "{\n" "public:\n" @@ -281,8 +277,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) 'A::operator=' should return 'A &'\n", errout.str()); } - void operatorEq2() - { + void operatorEq2() { checkOpertorEq("class A\n" "{\n" "public:\n" @@ -312,8 +307,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) 'A::operator=' should return 'A &'\n", errout.str()); } - void operatorEq3() // ticket #3051 - { + void operatorEq3() { // ticket #3051 checkOpertorEq("class A\n" "{\n" "public:\n" @@ -322,8 +316,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEq4() // ticket #3114 (infinite loop) - { + void operatorEq4() { // ticket #3114 (infinite loop) checkOpertorEq("struct A {\n" " A& operator=(A const& a) { return operator=(&a); }\n" " A& operator=(const A*) { return *this; }\n" @@ -332,8 +325,7 @@ private: } // Check that operator Equal returns reference to this - void checkOpertorEqRetRefThis(const char code[]) - { + void checkOpertorEqRetRefThis(const char code[]) { // Clear the error log errout.str(""); @@ -351,8 +343,7 @@ private: checkClass.operatorEqRetRefThis(); } - void operatorEqRetRefThis1() - { + void operatorEqRetRefThis1() { checkOpertorEqRetRefThis( "class A\n" "{\n" @@ -456,8 +447,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (style) 'operator=' should return reference to self\n", errout.str()); } - void operatorEqRetRefThis2() - { + void operatorEqRetRefThis2() { // ticket # 1323 checkOpertorEqRetRefThis( "class szp\n" @@ -475,8 +465,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) 'operator=' should return reference to self\n", errout.str()); } - void operatorEqRetRefThis3() - { + void operatorEqRetRefThis3() { // ticket # 1405 checkOpertorEqRetRefThis( "class A {\n" @@ -525,8 +514,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqRetRefThis4() - { + void operatorEqRetRefThis4() { // ticket # 1451 checkOpertorEqRetRefThis( "P& P::operator = (const P& pc)\n" @@ -536,8 +524,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqRetRefThis5() - { + void operatorEqRetRefThis5() { // ticket # 1550 checkOpertorEqRetRefThis( "class A {\n" @@ -555,8 +542,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) 'operator=' should return reference to self\n", errout.str()); } - void operatorEqRetRefThis6() // ticket #2478 (segmentation fault) - { + void operatorEqRetRefThis6() { // ticket #2478 (segmentation fault) checkOpertorEqRetRefThis( "class UString {\n" "public:\n" @@ -573,8 +559,7 @@ private: } // Check that operator Equal checks for assignment to self - void checkOpertorEqToSelf(const char code[]) - { + void checkOpertorEqToSelf(const char code[]) { // Clear the error log errout.str(""); @@ -592,8 +577,7 @@ private: checkClass.operatorEqToSelf(); } - void operatorEqToSelf1() - { + void operatorEqToSelf1() { // this test has an assignment test but it is not needed checkOpertorEqToSelf( "class A\n" @@ -720,8 +704,7 @@ private: } - void operatorEqToSelf2() - { + void operatorEqToSelf2() { // this test has an assignment test but doesn't need it checkOpertorEqToSelf( "class A\n" @@ -859,8 +842,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (warning) 'operator=' should check for assignment to self\n", errout.str()); } - void operatorEqToSelf3() - { + void operatorEqToSelf3() { // this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it checkOpertorEqToSelf( "class A : public B, public C\n" @@ -912,8 +894,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqToSelf4() - { + void operatorEqToSelf4() { // this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it checkOpertorEqToSelf( "class A\n" @@ -981,8 +962,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqToSelf5() - { + void operatorEqToSelf5() { // ticket # 1233 checkOpertorEqToSelf( "class A\n" @@ -1265,8 +1245,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqToSelf6() - { + void operatorEqToSelf6() { // ticket # 1550 checkOpertorEqToSelf( "class A\n" @@ -1335,8 +1314,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (warning) 'operator=' should check for assignment to self\n", errout.str()); } - void operatorEqToSelf7() - { + void operatorEqToSelf7() { checkOpertorEqToSelf( "class A\n" "{\n" @@ -1353,8 +1331,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqToSelf8() - { + void operatorEqToSelf8() { checkOpertorEqToSelf( "class FMat\n" "{\n" @@ -1373,8 +1350,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqToSelf9() - { + void operatorEqToSelf9() { checkOpertorEqToSelf( "class Foo\n" "{\n" @@ -1394,8 +1370,7 @@ private: } // Check that base classes have virtual destructors - void checkVirtualDestructor(const char code[]) - { + void checkVirtualDestructor(const char code[]) { // Clear the error log errout.str(""); @@ -1412,8 +1387,7 @@ private: checkClass.virtualDestructor(); } - void virtualDestructor1() - { + void virtualDestructor1() { // Base class not found checkVirtualDestructor("class Derived : public Base { };\n" @@ -1427,8 +1401,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructor2() - { + void virtualDestructor2() { // Base class doesn't have a destructor checkVirtualDestructor("class Base { };\n" @@ -1456,8 +1429,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructor3() - { + void virtualDestructor3() { // Base class has a destructor, but it's not virtual checkVirtualDestructor("class Base { public: ~Base(); };\n" @@ -1479,8 +1451,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (error) Class Base which is inherited by class Derived does not have a virtual destructor\n", errout.str()); } - void virtualDestructor4() - { + void virtualDestructor4() { // Derived class doesn't have a destructor => no error checkVirtualDestructor("class Base { public: ~Base(); };\n" @@ -1496,8 +1467,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructor5() - { + void virtualDestructor5() { // Derived class has empty destructor => no error checkVirtualDestructor("class Base { public: ~Base(); };\n" @@ -1513,8 +1483,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructor6() - { + void virtualDestructor6() { // Only report error if base class pointer is deleted that // points at derived class @@ -1529,8 +1498,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructorProtected() - { + void virtualDestructorProtected() { // Base class has protected destructor, it makes Base *p = new Derived(); fail // during compilation time, so error is not possible. => no error checkVirtualDestructor("class A\n" @@ -1547,8 +1515,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void virtualDestructorInherited() - { + void virtualDestructorInherited() { // class A inherits virtual destructor from class Base -> no error checkVirtualDestructor("class Base\n" "{\n" @@ -1642,8 +1609,7 @@ private: "", errout.str()); } - void virtualDestructorTemplate() - { + void virtualDestructorTemplate() { checkVirtualDestructor("template class A\n" "{\n" " public:\n" @@ -1664,8 +1630,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (error) Class AA which is inherited by class B does not have a virtual destructor\n", errout.str()); } - void checkUninitVar(const char code[]) - { + void checkUninitVar(const char code[]) { // Clear the error log errout.str(""); @@ -1683,8 +1648,7 @@ private: checkClass.constructors(); } - void uninitVar1() - { + void uninitVar1() { checkUninitVar("enum ECODES\n" "{\n" " CODE_1 = 0,\n" @@ -1728,8 +1692,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar2() - { + void uninitVar2() { checkUninitVar("class John\n" "{\n" "public:\n" @@ -1740,8 +1703,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar3() - { + void uninitVar3() { // No FP when struct has constructor checkUninitVar("class Foo\n" "{\n" @@ -1769,8 +1731,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Foo::bars' is not initialized in the constructor.\n", errout.str()); } - void uninitVar4() - { + void uninitVar4() { checkUninitVar("class Foo\n" "{\n" "public:\n" @@ -1784,8 +1745,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar5() - { + void uninitVar5() { checkUninitVar("class Foo\n" "{\n" "public:\n" @@ -1797,8 +1757,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar6() - { + void uninitVar6() { checkUninitVar("class Foo : public Bar\n" "{\n" "public:\n" @@ -1809,8 +1768,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar7() - { + void uninitVar7() { checkUninitVar("class Foo {\n" " int a;\n" "public:\n" @@ -1831,8 +1789,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar8() - { + void uninitVar8() { checkUninitVar("class Foo {\n" " int a;\n" "public:\n" @@ -1849,8 +1806,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'Foo::a' is not assigned a value in 'Foo::operator='\n", errout.str()); } - void uninitVar9() // ticket #1730 - { + void uninitVar9() { // ticket #1730 checkUninitVar("class Prefs {\n" "private:\n" " int xasd;\n" @@ -1864,8 +1820,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Prefs::xasd' is not initialized in the constructor.\n", errout.str()); } - void uninitVar10() // ticket #1993 - { + void uninitVar10() { // ticket #1993 checkUninitVar("class A {\n" "public:\n" " A();\n" @@ -1877,8 +1832,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'A::var2' is not initialized in the constructor.\n", errout.str()); } - void uninitVar11() - { + void uninitVar11() { checkUninitVar("class A {\n" "public:\n" " A(int a = 0);\n" @@ -1889,8 +1843,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'A::var' is not initialized in the constructor.\n", errout.str()); } - void uninitVar12() // ticket #2078 - { + void uninitVar12() { // ticket #2078 checkUninitVar("class Point\n" "{\n" "public:\n" @@ -1907,8 +1860,7 @@ private: "[test.cpp:4]: (warning) Member variable 'Point::y' is not initialized in the constructor.\n", errout.str()); } - void uninitVar13() // ticket #1195 - { + void uninitVar13() { // ticket #1195 checkUninitVar("class A {\n" "private:\n" " std::vector *ints;\n" @@ -1919,8 +1871,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'A::ints' is not initialized in the constructor.\n", errout.str()); } - void uninitVar14() // ticket #2149 - { + void uninitVar14() { // ticket #2149 // no namespace checkUninitVar("class Foo\n" "{\n" @@ -2106,8 +2057,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar15() - { + void uninitVar15() { checkUninitVar("class Fred\n" "{\n" " int a;\n" @@ -2121,8 +2071,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar16() - { + void uninitVar16() { checkUninitVar("struct Foo\n" "{\n" " int a;\n" @@ -2155,8 +2104,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Bar::foo' is not initialized in the constructor.\n", errout.str()); } - void uninitVar17() - { + void uninitVar17() { checkUninitVar("struct Foo\n" "{\n" " int a;\n" @@ -2187,8 +2135,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'Bar::foo' is not initialized in the constructor.\n", errout.str()); } - void uninitVar18() // ticket #2465 - { + void uninitVar18() { // ticket #2465 checkUninitVar("struct Altren\n" "{\n" " Altren(int _a = 0) : value(0) { }\n" @@ -2218,8 +2165,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'A::value' is not initialized in the constructor.\n", errout.str()); } - void uninitVar19() // ticket #2792 - { + void uninitVar19() { // ticket #2792 checkUninitVar("class mystring\n" "{\n" " char* m_str;\n" @@ -2243,8 +2189,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar20() // ticket #2867 - { + void uninitVar20() { // ticket #2867 checkUninitVar("Object::MemFunc() {\n" " class LocalClass {\n" " public:\n" @@ -2276,8 +2221,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'LocalClass::bitsInData_' is not initialized in the constructor.\n", errout.str()); } - void uninitVar21() // ticket #2947 - { + void uninitVar21() { // ticket #2947 checkUninitVar("class Fred {\n" "private:\n" " int a[23];\n" @@ -2290,8 +2234,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVar22() // ticket #3043 - { + void uninitVar22() { // ticket #3043 checkUninitVar("class Fred {\n" " public:\n" " Fred & operator=(const Fred &);\n" @@ -2322,8 +2265,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::x' is not assigned a value in 'Fred::operator='\n", errout.str()); } - void uninitVarArray1() - { + void uninitVarArray1() { checkUninitVar("class John\n" "{\n" "public:\n" @@ -2382,8 +2324,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'John::a' is not initialized in the constructor.\n", errout.str()); } - void uninitVarArray2() - { + void uninitVarArray2() { checkUninitVar("class John\n" "{\n" "public:\n" @@ -2395,8 +2336,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray3() - { + void uninitVarArray3() { checkUninitVar("class John\n" "{\n" "private:\n" @@ -2413,8 +2353,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray4() - { + void uninitVarArray4() { checkUninitVar("class John\n" "{\n" "private:\n" @@ -2431,8 +2370,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray5() - { + void uninitVarArray5() { checkUninitVar("class Foo\n" "{\n" "private:\n" @@ -2444,8 +2382,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray6() - { + void uninitVarArray6() { checkUninitVar("class Foo\n" "{\n" "public:\n" @@ -2457,8 +2394,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray7() - { + void uninitVarArray7() { checkUninitVar("class Foo\n" "{\n" " int array[10];\n" @@ -2484,8 +2420,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarArray2D() - { + void uninitVarArray2D() { checkUninitVar("class John\n" "{\n" "public:\n" @@ -2497,8 +2432,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarStruct1() // ticket #2172 - { + void uninitVarStruct1() { // ticket #2172 checkUninitVar("class A\n" "{\n" "private:\n" @@ -2543,8 +2477,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarStruct2() // ticket #838 - { + void uninitVarStruct2() { // ticket #838 checkUninitVar("struct POINT\n" "{\n" " int x;\n" @@ -2593,8 +2526,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitMissingFuncDef() - { + void uninitMissingFuncDef() { // Unknown member function checkUninitVar("class Fred\n" "{\n" @@ -2650,8 +2582,7 @@ private: } - void uninitVarEnum() - { + void uninitVarEnum() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2664,8 +2595,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout.str()); } - void uninitVarStream() - { + void uninitVarStream() { checkUninitVar("#include \n" "class Foo\n" "{\n" @@ -2682,8 +2612,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarTypedef() - { + void uninitVarTypedef() { checkUninitVar("class Foo\n" "{\n" "public:\n" @@ -2695,8 +2624,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarMemset() - { + void uninitVarMemset() { checkUninitVar("class Foo\n" "{\n" "public:\n" @@ -2716,8 +2644,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void privateCtor1() - { + void privateCtor1() { checkUninitVar("class Foo {\n" " int foo;\n" " Foo() { }\n" @@ -2725,8 +2652,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void privateCtor2() - { + void privateCtor2() { checkUninitVar("class Foo\n" "{\n" "private:\n" @@ -2740,8 +2666,7 @@ private: } - void function() - { + void function() { checkUninitVar("class A\n" "{\n" "public:\n" @@ -2762,8 +2687,7 @@ private: } - void uninitVarHeader1() - { + void uninitVarHeader1() { checkUninitVar("#file \"fred.h\"\n" "class Fred\n" "{\n" @@ -2776,8 +2700,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarHeader2() - { + void uninitVarHeader2() { checkUninitVar("#file \"fred.h\"\n" "class Fred\n" "{\n" @@ -2790,8 +2713,7 @@ private: ASSERT_EQUALS("[fred.h:6]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout.str()); } - void uninitVarHeader3() - { + void uninitVarHeader3() { checkUninitVar("#file \"fred.h\"\n" "class Fred\n" "{\n" @@ -2805,8 +2727,7 @@ private: } // Borland C++: No FP for published pointers - they are automatically initialized - void uninitVarPublished() - { + void uninitVarPublished() { checkUninitVar("class Fred\n" "{\n" "__published:\n" @@ -2817,8 +2738,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitOperator() - { + void uninitOperator() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2828,8 +2748,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitFunction1() - { + void uninitFunction1() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2855,8 +2774,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout.str()); } - void uninitFunction2() - { + void uninitFunction2() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2882,8 +2800,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout.str()); } - void uninitFunction3() - { + void uninitFunction3() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2909,8 +2826,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", errout.str()); } - void uninitFunction4() - { + void uninitFunction4() { checkUninitVar("class Fred\n" "{\n" "public:\n" @@ -2936,8 +2852,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout.str()); } - void uninitSameClassName() - { + void uninitSameClassName() { checkUninitVar("class B\n" "{\n" "public:\n" @@ -3053,8 +2968,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitFunctionOverload() - { + void uninitFunctionOverload() { // Ticket #1783 - overloaded "init" functions checkUninitVar("class A\n" "{\n" @@ -3093,8 +3007,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'A::i' is not initialized in the constructor.\n", "", errout.str()); } - void checkUninitVarJava(const char code[]) - { + void checkUninitVarJava(const char code[]) { // Clear the error log errout.str(""); @@ -3112,8 +3025,7 @@ private: checkClass.constructors(); } - void uninitJava() - { + void uninitJava() { checkUninitVarJava("class A {\n" " private: int i = 0;\n" " public: A() { }\n" @@ -3121,8 +3033,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarOperatorEqual() // ticket #2415 - { + void uninitVarOperatorEqual() { // ticket #2415 checkUninitVar("struct A {\n" " int a;\n" " A() { a=0; }\n" @@ -3153,8 +3064,7 @@ private: "[test.cpp:5]: (warning) Member variable 'A::a' is not assigned a value in 'A::operator='\n", errout.str()); } - void checkNoConstructor(const char code[]) - { + void checkNoConstructor(const char code[]) { // Clear the error log errout.str(""); @@ -3172,8 +3082,7 @@ private: checkClass.constructors(); } - void noConstructor1() - { + void noConstructor1() { // There are nonstatic member variables - constructor is needed checkNoConstructor("class Fred\n" "{\n" @@ -3182,8 +3091,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (style) The class 'Fred' does not have a constructor.\n", errout.str()); } - void noConstructor2() - { + void noConstructor2() { checkNoConstructor("class Fred\n" "{\n" "public:\n" @@ -3195,8 +3103,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void noConstructor3() - { + void noConstructor3() { checkNoConstructor("class Fred\n" "{\n" "private:\n" @@ -3205,8 +3112,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void noConstructor4() - { + void noConstructor4() { checkNoConstructor("class Fred\n" "{\n" "public:\n" @@ -3215,8 +3121,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void noConstructor5() - { + void noConstructor5() { checkNoConstructor("namespace Foo\n" "{\n" " int i;\n" @@ -3224,8 +3129,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void checkNoMemset(const char code[]) - { + void checkNoMemset(const char code[]) { // Clear the error log errout.str(""); @@ -3241,8 +3145,7 @@ private: checkClass.noMemset(); } - void memsetOnClass() - { + void memsetOnClass() { checkNoMemset("class Fred\n" "{\n" "};\n" @@ -3410,8 +3313,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (error) Using 'memset' on class that contains a 'std::string'\n", errout.str()); } - void memsetOnStruct() - { + void memsetOnStruct() { checkNoMemset("struct A\n" "{\n" "};\n" @@ -3487,8 +3389,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (error) Using 'memset' on struct that contains a 'std::string'\n", errout.str()); } - void memsetVector() - { + void memsetVector() { checkNoMemset("class A\n" "{ std::vector ints; };\n" "\n" @@ -3571,8 +3472,7 @@ private: } - void checkThisSubtraction(const char code[]) - { + void checkThisSubtraction(const char code[]) { // Clear the error log errout.str(""); @@ -3590,8 +3490,7 @@ private: checkClass.thisSubtraction(); } - void this_subtraction() - { + void this_subtraction() { checkThisSubtraction("; this-x ;"); ASSERT_EQUALS("[test.cpp:1]: (warning) Suspicious pointer subtraction\n", errout.str()); @@ -3609,8 +3508,7 @@ private: "[test.cpp:3]: (warning) Suspicious pointer subtraction\n", errout.str()); } - void checkConst(const char code[], const Settings *s = 0) - { + void checkConst(const char code[], const Settings *s = 0) { // Clear the error log errout.str(""); @@ -3631,8 +3529,7 @@ private: checkClass.checkConst(); } - void const1() - { + void const1() { checkConst("class Fred {\n" " int a;\n" " int getA() { return a; }\n" @@ -3689,8 +3586,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const2() - { + void const2() { // ticket 1344 // assignment to variable can't be const checkConst("class Fred {\n" @@ -3742,8 +3638,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const3() - { + void const3() { // assignment to function argument pointer can be const checkConst("class Fred {\n" " int s;\n" @@ -3787,8 +3682,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const4() - { + void const4() { checkConst("class Fred {\n" " int a;\n" " int getA();\n" @@ -4071,8 +3965,7 @@ private: } // operator< can often be const - void constoperator1() - { + void constoperator1() { checkConst("struct Fred {\n" " int a;\n" " bool operator<(const Fred &f) { return (a < f.a); }\n" @@ -4081,8 +3974,7 @@ private: } // operator<< - void constoperator2() - { + void constoperator2() { checkConst("struct Foo {\n" " void operator<<(int);\n" "};\n" @@ -4096,8 +3988,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void constoperator3() - { + void constoperator3() { checkConst("struct Fred {\n" " int array[10];\n" " int const & operator [] (unsigned int index) const { return array[index]; }\n" @@ -4112,8 +4003,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'Fred::operator[]' can be const.\n", errout.str()); } - void constoperator4() - { + void constoperator4() { checkConst("struct Fred {\n" " int array[10];\n" " typedef int* (Fred::*UnspecifiedBoolType);\n" @@ -4129,8 +4019,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const5() - { + void const5() { // ticket #1482 checkConst("class A {\n" " int a;\n" @@ -4144,8 +4033,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'A::foo' can be const.\n", errout.str()); } - void const6() - { + void const6() { // ticket # 1491 checkConst("class foo {\n" "public:\n" @@ -4175,8 +4063,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const7() - { + void const7() { checkConst("class foo {\n" " int a;\n" "public:\n" @@ -4187,8 +4074,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const8() - { + void const8() { // ticket #1517 checkConst("class A {\n" "public:\n" @@ -4200,8 +4086,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Technically the member function 'A::strGetString' can be const.\n", errout.str()); } - void const9() - { + void const9() { // ticket #1515 checkConst("class wxThreadInternal {\n" "public:\n" @@ -4212,8 +4097,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const10() - { + void const10() { // ticket #1522 checkConst("class A {\n" "public:\n" @@ -4240,8 +4124,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const11() - { + void const11() { // ticket #1529 checkConst("class A {\n" "public:\n" @@ -4252,8 +4135,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const12() - { + void const12() { // ticket #1525 checkConst("class A {\n" "public:\n" @@ -4264,8 +4146,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'A::foo' can be const.\n", errout.str()); } - void const13() - { + void const13() { // ticket #1519 checkConst("class A {\n" "public:\n" @@ -4292,8 +4173,7 @@ private: "[test.cpp:5]: (style) Technically the member function 'A::GetPair' can be const.\n", errout.str()); } - void const14() - { + void const14() { // extends ticket 1519 checkConst("class A {\n" "public:\n" @@ -4676,8 +4556,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'A::foo' can be const.\n", errout.str()); } - void const15() - { + void const15() { checkConst("class Fred {\n" " unsigned long long int a;\n" " unsigned long long int getA() { return a; }\n" @@ -4718,8 +4597,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const16() - { + void const16() { // ticket #1551 checkConst("class Fred {\n" " int a;\n" @@ -4728,8 +4606,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const17() - { + void const17() { // ticket #1552 checkConst("class Fred {\n" "public:\n" @@ -4740,8 +4617,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const18() - { + void const18() { // ticket #1563 checkConst("class Fred {\n" "static int x;\n" @@ -4751,8 +4627,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const19() - { + void const19() { // ticket #1612 checkConst("using namespace std;\n" "class Fred {\n" @@ -4764,8 +4639,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const20() - { + void const20() { // ticket #1602 checkConst("class Fred {\n" " int x : 3;\n" @@ -4803,8 +4677,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Technically the member function 'Fred::get' can be const.\n", errout.str()); } - void const21() - { + void const21() { // ticket #1683 checkConst("class A\n" "{\n" @@ -4820,8 +4693,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const22() - { + void const22() { checkConst("class A\n" "{\n" "private:\n" @@ -4841,8 +4713,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const23() - { + void const23() { checkConst("class Class {\n" "public:\n" " typedef Template Type;\n" @@ -4854,8 +4725,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const24() - { + void const24() { checkConst("class Class {\n" "public:\n" "void Settings::SetSetting(QString strSetting, QString strNewVal)\n" @@ -4869,8 +4739,7 @@ private: } - void const25() // ticket #1724 - { + void const25() { // ticket #1724 checkConst("class A{\n" "public:\n" "A(){m_strVal="";}\n" @@ -4929,8 +4798,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Technically the member function 'A::strGetEmpty' can be const.\n", errout.str()); } - void const26() // ticket #1847 - { + void const26() { // ticket #1847 checkConst("class DelayBase {\n" "public:\n" "void swapSpecificDelays(int index1, int index2) {\n" @@ -4942,8 +4810,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const27() // ticket #1882 - { + void const27() { // ticket #1882 checkConst("class A {\n" "public:\n" " A(){m_d=1.0; m_iRealVal=2.0;}\n" @@ -4962,8 +4829,7 @@ private: ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:4]: (style) Technically the member function 'A::dGetValue' can be const.\n", errout.str()); } - void const28() // ticket #1883 - { + void const28() { // ticket #1883 checkConst("class P {\n" "public:\n" " P() { x=0.0; y=0.0; }\n" @@ -5002,8 +4868,7 @@ private: } - void const29() // ticket #1922 - { + void const29() { // ticket #1922 checkConst("class test {\n" " public:\n" " test();\n" @@ -5027,8 +4892,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const30() - { + void const30() { // check for false negatives checkConst("class Base {\n" "public:\n" @@ -5151,8 +5015,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const31() - { + void const31() { checkConst("namespace std { }\n" "class Fred {\n" "public:\n" @@ -5162,8 +5025,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) Technically the member function 'Fred::get' can be const.\n", errout.str()); } - void const32() - { + void const32() { checkConst("class Fred {\n" "public:\n" " std::string a[10];\n" @@ -5172,8 +5034,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const33() - { + void const33() { checkConst("class derived : public base {\n" "public:\n" " void f(){}\n" @@ -5181,8 +5042,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const34() // ticket #1964 - { + void const34() { // ticket #1964 checkConst("class Bar {\n" " void init(Foo * foo) {\n" " foo.bar = this;\n" @@ -5191,8 +5051,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const35() // ticket #2001 - { + void const35() { // ticket #2001 checkConst("namespace N\n" "{\n" " class Base\n" @@ -5252,8 +5111,7 @@ private: "", errout.str()); } - void const36() // ticket #2003 - { + void const36() { // ticket #2003 checkConst("class Foo {\n" "public:\n" " Blue::Utility::Size m_MaxQueueSize;\n" @@ -5265,8 +5123,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const37() // ticket #2081 and #2085 - { + void const37() { // ticket #2081 and #2085 checkConst("class A\n" "{\n" "public:\n" @@ -5295,8 +5152,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (style) Technically the member function 'Fred::isValid' can be const.\n", errout.str()); } - void const38() // ticket #2135 - { + void const38() { // ticket #2135 checkConst("class Foo {\n" "public:\n" " ~Foo() { delete oArq; }\n" @@ -5312,8 +5168,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const39() - { + void const39() { checkConst("class Foo\n" "{\n" " int * p;\n" @@ -5334,8 +5189,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const40() // ticket #2228 - { + void const40() { // ticket #2228 checkConst("class SharedPtrHolder\n" "{\n" " private:\n" @@ -5352,8 +5206,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const41() // ticket #2255 - { + void const41() { // ticket #2255 checkConst("class Fred\n" "{\n" " ::std::string m_name;\n" @@ -5429,8 +5282,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const42() // ticket #2282 - { + void const42() { // ticket #2282 checkConst("class Fred\n" "{\n" "public:\n" @@ -5506,8 +5358,7 @@ private: ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:8]: (style) Technically the member function 'Foo::Fred::f' can be const.\n", errout.str()); } - void const43() // ticket 2377 - { + void const43() { // ticket 2377 checkConst("class A\n" "{\n" "public:\n" @@ -5565,8 +5416,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const44() // ticket 2595 - { + void const44() { // ticket 2595 checkConst("class A\n" "{\n" "public:\n" @@ -5580,8 +5430,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const45() // ticket 2664 - { + void const45() { // ticket 2664 checkConst("namespace wraps {\n" " class BaseLayout {};\n" "}\n" @@ -5598,8 +5447,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (style) Technically the member function 'tools::WorkspaceControl::toGrid' can be const.\n", errout.str()); } - void const46() // ticket 2663 - { + void const46() { // ticket 2663 checkConst("class Altren {\n" "public:\n" " int fun1() {\n" @@ -5615,8 +5463,7 @@ private: "[test.cpp:7]: (style) Technically the member function 'Altren::fun2' can be const.\n", errout.str()); } - void const47() // ticket 2670 - { + void const47() { // ticket 2670 checkConst("class Altren {\n" "public:\n" " void foo() { delete this; }\n" @@ -5636,8 +5483,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) Technically the member function 'Altren::bar' can be const.\n", errout.str()); } - void const48() // ticket 2672 - { + void const48() { // ticket 2672 checkConst("class S0 {\n" " class S1 {\n" " class S2 {\n" @@ -5659,8 +5505,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const49() // ticket 2795 - { + void const49() { // ticket 2795 checkConst("class A {\n" " private:\n" " std::map _hash;\n" @@ -5674,8 +5519,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const50() // ticket 2943 - { + void const50() { // ticket 2943 checkConst("class Altren\n" "{\n" " class SubClass : public std::vector\n" @@ -5691,8 +5535,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const51() // ticket 3040 - { + void const51() { // ticket 3040 checkConst("class PSIPTable {\n" "public:\n" " PSIPTable() : _pesdata(0) { }\n" @@ -5720,8 +5563,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const52() // ticket 3049 - { + void const52() { // ticket 3049 checkConst("class A {\n" " public:\n" " A() : foo(false) {};\n" @@ -5737,8 +5579,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const53() // ticket 3052 - { + void const53() { // ticket 3052 checkConst("class Example {\n" " public:\n" " void Clear(void) { Example tmp; (*this) = tmp; }\n" @@ -5746,8 +5587,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const54() - { + void const54() { checkConst("class MyObject {\n" " int tmp;\n" " MyObject() : tmp(0) {}\n" @@ -5757,8 +5597,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void const55() // ticket #3149 - { + void const55() { // ticket #3149 checkConst("class MyObject {\n" "public:\n" " void foo(int x) {\n" @@ -5819,8 +5658,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'MyObject::foo' can be const.\n", errout.str()); } - void assigningPointerToPointerIsNotAConstOperation() - { + void assigningPointerToPointerIsNotAConstOperation() { checkConst("struct s\n" "{\n" " int** v;\n" @@ -5833,8 +5671,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assigningArrayElementIsNotAConstOperation() - { + void assigningArrayElementIsNotAConstOperation() { checkConst("struct s\n" "{\n" " ::std::string v[3];\n" @@ -5848,8 +5685,7 @@ private: } // increment/decrement => not const - void constincdec() - { + void constincdec() { checkConst("class Fred {\n" " int a;\n" " void nextA() { return ++a; }\n" @@ -5899,8 +5735,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'Fred::nextA' can be const.\n", errout.str()); } - void constassign1() - { + void constassign1() { checkConst("class Fred {\n" " int a;\n" " void nextA() { return a=1; }\n" @@ -5962,8 +5797,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'Fred::nextA' can be const.\n", errout.str()); } - void constassign2() - { + void constassign2() { checkConst("class Fred {\n" " struct A { int a; } s;\n" " void nextA() { return s.a=1; }\n" @@ -6055,8 +5889,7 @@ private: } // increment/decrement array element => not const - void constincdecarray() - { + void constincdecarray() { checkConst("class Fred {\n" " int a[2];\n" " void nextA() { return ++a[0]; }\n" @@ -6106,8 +5939,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Technically the member function 'Fred::nextA' can be const.\n", errout.str()); } - void constassignarray() - { + void constassignarray() { checkConst("class Fred {\n" " int a[2];\n" " void nextA() { return a[0]=1; }\n" @@ -6170,8 +6002,7 @@ private: } // return pointer/reference => not const - void constReturnReference() - { + void constReturnReference() { checkConst("class Fred {\n" " int a;\n" " int &getR() { return a; }\n" @@ -6181,8 +6012,7 @@ private: } // delete member variable => not const (but technically it can, it compiles without errors) - void constDelete() - { + void constDelete() { checkConst("class Fred {\n" " int *a;\n" " void clean() { delete a; }\n" @@ -6191,8 +6021,7 @@ private: } // A function that returns LPVOID can't be const - void constLPVOID() - { + void constLPVOID() { checkConst("class Fred {\n" " LPVOID a() { return 0; };\n" "};\n"); @@ -6206,8 +6035,7 @@ private: } // a function that calls const functions can be const - void constFunc() - { + void constFunc() { checkConst("class Fred {\n" " void f() const { };\n" " void a() { f(); };\n" @@ -6236,8 +6064,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (style) Technically the member function 'A::GetVecEmpty' can be const.\n", errout.str()); } - void constVirtualFunc() - { + void constVirtualFunc() { // base class has no virtual function checkConst("class A { };\n" "class B : public A {\n" @@ -6464,8 +6291,7 @@ private: "[test.cpp:21] -> [test.cpp:19]: (style) Technically the member function 'Z::getZ' can be const.\n", errout.str()); } - void constIfCfg() - { + void constIfCfg() { const char code[] = "class foo {\n" " void f() { }\n" "};"; @@ -6482,8 +6308,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void constFriend() // ticket #1921 - { + void constFriend() { // ticket #1921 const char code[] = "class foo {\n" " friend void f() { }\n" "};"; @@ -6491,8 +6316,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void constUnion() // ticket #2111 - { + void constUnion() { // ticket #2111 checkConst("class foo {\n" "public:\n" " union {\n" @@ -6506,8 +6330,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void checkInitializerList(const char code[]) - { + void checkInitializerList(const char code[]) { // Clear the error log errout.str(""); @@ -6526,8 +6349,7 @@ private: checkClass.initializerList(); } - void initializerList() - { + void initializerList() { checkInitializerList("class Fred {\n" " int a, b, c;\n" "public:\n" diff --git a/test/testcmdlineparser.cpp b/test/testcmdlineparser.cpp index 73ab69919..d634f6c16 100644 --- a/test/testcmdlineparser.cpp +++ b/test/testcmdlineparser.cpp @@ -21,16 +21,14 @@ #include "settings.h" #include "redirect.h" -class TestCmdlineParser : public TestFixture -{ +class TestCmdlineParser : public TestFixture { public: TestCmdlineParser() : TestFixture("TestCmdlineParser") { } private: - void run() - { + void run() { TEST_CASE(nooptions); TEST_CASE(helpshort); TEST_CASE(helplong); @@ -115,8 +113,7 @@ private: } - void nooptions() - { + void nooptions() { REDIRECT; const char *argv[] = {"cppcheck"}; Settings settings; @@ -125,8 +122,7 @@ private: ASSERT_EQUALS(true, parser.GetShowHelp()); } - void helpshort() - { + void helpshort() { REDIRECT; const char *argv[] = {"cppcheck", "-h"}; Settings settings; @@ -135,8 +131,7 @@ private: ASSERT_EQUALS(true, parser.GetShowHelp()); } - void helplong() - { + void helplong() { REDIRECT; const char *argv[] = {"cppcheck", "--help"}; Settings settings; @@ -145,8 +140,7 @@ private: ASSERT_EQUALS(true, parser.GetShowHelp()); } - void showversion() - { + void showversion() { REDIRECT; const char *argv[] = {"cppcheck", "--version"}; Settings settings; @@ -155,8 +149,7 @@ private: ASSERT_EQUALS(true, parser.GetShowVersion()); } - void onefile() - { + void onefile() { REDIRECT; const char *argv[] = {"cppcheck", "file.cpp"}; Settings settings; @@ -166,8 +159,7 @@ private: ASSERT_EQUALS("file.cpp", parser.GetPathNames().at(0)); } - void onepath() - { + void onepath() { REDIRECT; const char *argv[] = {"cppcheck", "src"}; Settings settings; @@ -177,8 +169,7 @@ private: ASSERT_EQUALS("src", parser.GetPathNames().at(0)); } - void optionwithoutfile() - { + void optionwithoutfile() { REDIRECT; const char *argv[] = {"cppcheck", "-v"}; Settings settings; @@ -187,8 +178,7 @@ private: ASSERT_EQUALS(0, (int)parser.GetPathNames().size()); } - void verboseshort() - { + void verboseshort() { REDIRECT; const char *argv[] = {"cppcheck", "-v", "file.cpp"}; Settings settings; @@ -197,8 +187,7 @@ private: ASSERT_EQUALS(true, settings._verbose); } - void verboselong() - { + void verboselong() { REDIRECT; const char *argv[] = {"cppcheck", "--verbose", "file.cpp"}; Settings settings; @@ -207,8 +196,7 @@ private: ASSERT_EQUALS(true, settings._verbose); } - void debug() - { + void debug() { REDIRECT; const char *argv[] = {"cppcheck", "--debug", "file.cpp"}; Settings settings; @@ -217,8 +205,7 @@ private: ASSERT_EQUALS(true, settings.debug); } - void debugwarnings() - { + void debugwarnings() { REDIRECT; const char *argv[] = {"cppcheck", "--debug-warnings", "file.cpp"}; Settings settings; @@ -227,8 +214,7 @@ private: ASSERT_EQUALS(true, settings.debugwarnings); } - void forceshort() - { + void forceshort() { REDIRECT; const char *argv[] = {"cppcheck", "-f", "file.cpp"}; Settings settings; @@ -237,8 +223,7 @@ private: ASSERT_EQUALS(true, settings._force); } - void forcelong() - { + void forcelong() { REDIRECT; const char *argv[] = {"cppcheck", "--force", "file.cpp"}; Settings settings; @@ -247,8 +232,7 @@ private: ASSERT_EQUALS(true, settings._force); } - void quietshort() - { + void quietshort() { REDIRECT; const char *argv[] = {"cppcheck", "-q", "file.cpp"}; Settings settings; @@ -257,8 +241,7 @@ private: ASSERT_EQUALS(true, settings._errorsOnly); } - void quietlong() - { + void quietlong() { REDIRECT; const char *argv[] = {"cppcheck", "--quiet", "file.cpp"}; Settings settings; @@ -267,8 +250,7 @@ private: ASSERT_EQUALS(true, settings._errorsOnly); } - void defines_noarg() - { + void defines_noarg() { REDIRECT; const char *argv[] = {"cppcheck", "-D"}; Settings settings; @@ -277,8 +259,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(2, argv)); } - void defines_noarg2() - { + void defines_noarg2() { REDIRECT; const char *argv[] = {"cppcheck", "-D", "-v", "file.cpp"}; Settings settings; @@ -287,8 +268,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(4, argv)); } - void defines_noarg3() - { + void defines_noarg3() { REDIRECT; const char *argv[] = {"cppcheck", "-D", "--quiet", "file.cpp"}; Settings settings; @@ -297,8 +277,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(4, argv)); } - void defines() - { + void defines() { REDIRECT; const char *argv[] = {"cppcheck", "-D_WIN32", "file.cpp"}; Settings settings; @@ -307,8 +286,7 @@ private: ASSERT_EQUALS("_WIN32", settings.userDefines); } - void defines2() - { + void defines2() { REDIRECT; const char *argv[] = {"cppcheck", "-D_WIN32", "-DNODEBUG", "file.cpp"}; Settings settings; @@ -317,8 +295,7 @@ private: ASSERT_EQUALS("_WIN32;NODEBUG", settings.userDefines); } - void defines3() - { + void defines3() { REDIRECT; const char *argv[] = {"cppcheck", "-D", "DEBUG", "file.cpp"}; Settings settings; @@ -327,8 +304,7 @@ private: ASSERT_EQUALS("DEBUG", settings.userDefines); } - void includesnopath() - { + void includesnopath() { REDIRECT; const char *argv[] = {"cppcheck", "-I", "file.cpp"}; Settings settings; @@ -337,8 +313,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(3, argv)); } - void includes() - { + void includes() { REDIRECT; const char *argv[] = {"cppcheck", "-I", "include", "file.cpp"}; Settings settings; @@ -347,8 +322,7 @@ private: ASSERT_EQUALS("include/", settings._includePaths.front()); } - void includesslash() - { + void includesslash() { REDIRECT; const char *argv[] = {"cppcheck", "-I", "include/", "file.cpp"}; Settings settings; @@ -357,8 +331,7 @@ private: ASSERT_EQUALS("include/", settings._includePaths.front()); } - void includesbackslash() - { + void includesbackslash() { REDIRECT; const char *argv[] = {"cppcheck", "-I", "include\\", "file.cpp"}; Settings settings; @@ -367,8 +340,7 @@ private: ASSERT_EQUALS("include/", settings._includePaths.front()); } - void includesnospace() - { + void includesnospace() { REDIRECT; const char *argv[] = {"cppcheck", "-Iinclude", "file.cpp"}; Settings settings; @@ -377,8 +349,7 @@ private: ASSERT_EQUALS("include/", settings._includePaths.front()); } - void includes2() - { + void includes2() { REDIRECT; const char *argv[] = {"cppcheck", "-I", "include/", "-I", "framework/", "file.cpp"}; Settings settings; @@ -389,8 +360,7 @@ private: ASSERT_EQUALS("framework/", settings._includePaths.front()); } - void enabledAll() - { + void enabledAll() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=all", "file.cpp"}; Settings settings; @@ -401,8 +371,7 @@ private: ASSERT(settings.isEnabled("missingInclude")); } - void enabledStyle() - { + void enabledStyle() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=style", "file.cpp"}; Settings settings; @@ -415,8 +384,7 @@ private: ASSERT(!settings.isEnabled("missingInclude")); } - void enabledPerformance() - { + void enabledPerformance() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=performance", "file.cpp"}; Settings settings; @@ -429,8 +397,7 @@ private: ASSERT(!settings.isEnabled("missingInclude")); } - void enabledPortability() - { + void enabledPortability() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=portability", "file.cpp"}; Settings settings; @@ -443,8 +410,7 @@ private: ASSERT(!settings.isEnabled("missingInclude")); } - void enabledUnusedFunction() - { + void enabledUnusedFunction() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=unusedFunction", "file.cpp"}; Settings settings; @@ -453,8 +419,7 @@ private: ASSERT(settings.isEnabled("unusedFunction")); } - void enabledMissingInclude() - { + void enabledMissingInclude() { REDIRECT; const char *argv[] = {"cppcheck", "--enable=missingInclude", "file.cpp"}; Settings settings; @@ -463,8 +428,7 @@ private: ASSERT(settings.isEnabled("missingInclude")); } - void errorExitcode() - { + void errorExitcode() { REDIRECT; const char *argv[] = {"cppcheck", "--error-exitcode=5", "file.cpp"}; Settings settings; @@ -473,8 +437,7 @@ private: ASSERT_EQUALS(5, settings._exitCode); } - void errorExitcodeMissing() - { + void errorExitcodeMissing() { REDIRECT; const char *argv[] = {"cppcheck", "--error-exitcode=", "file.cpp"}; Settings settings; @@ -483,8 +446,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(3, argv)); } - void errorExitcodeStr() - { + void errorExitcodeStr() { REDIRECT; const char *argv[] = {"cppcheck", "--error-exitcode=foo", "file.cpp"}; Settings settings; @@ -493,8 +455,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(3, argv)); } - void exitcodeSuppressionsOld() - { + void exitcodeSuppressionsOld() { // TODO: Fails since cannot open the file REDIRECT; const char *argv[] = {"cppcheck", "--exitcode-suppressions", "suppr.txt", "file.cpp"}; @@ -503,8 +464,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(4, argv)); } - void exitcodeSuppressions() - { + void exitcodeSuppressions() { // TODO: Fails since cannot open the file REDIRECT; const char *argv[] = {"cppcheck", "--exitcode-suppressions=suppr.txt", "file.cpp"}; @@ -513,8 +473,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(3, argv)); } - void exitcodeSuppressionsNoFile() - { + void exitcodeSuppressionsNoFile() { // TODO: Fails since cannot open the file REDIRECT; const char *argv[] = {"cppcheck", "--exitcode-suppressions", "file.cpp"}; @@ -523,8 +482,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(3, argv)); } - void fileList() - { + void fileList() { // TODO: Fails since cannot open the file REDIRECT; const char *argv[] = {"cppcheck", "--file-list", "files.txt", "file.cpp"}; @@ -533,8 +491,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(4, argv)); } - void fileListStdin() - { + void fileListStdin() { // TODO: Give it some stdin to read from, fails because the list of // files in stdin (_pathnames) is empty REDIRECT; @@ -544,8 +501,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(3, argv)); } - void inlineSuppr() - { + void inlineSuppr() { REDIRECT; const char *argv[] = {"cppcheck", "--inline-suppr", "file.cpp"}; Settings settings; @@ -553,8 +509,7 @@ private: ASSERT(parser.ParseFromArgs(3, argv)); } - void jobs() - { + void jobs() { REDIRECT; const char *argv[] = {"cppcheck", "-j", "3", "file.cpp"}; Settings settings; @@ -563,8 +518,7 @@ private: ASSERT_EQUALS(3, settings._jobs); } - void jobsMissingCount() - { + void jobsMissingCount() { REDIRECT; const char *argv[] = {"cppcheck", "-j", "file.cpp"}; Settings settings; @@ -573,8 +527,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(3, argv)); } - void jobsInvalid() - { + void jobsInvalid() { REDIRECT; const char *argv[] = {"cppcheck", "-j", "e", "file.cpp"}; Settings settings; @@ -583,8 +536,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(4, argv)); } - void reportProgressTest() - { + void reportProgressTest() { REDIRECT; const char *argv[] = {"cppcheck", "--report-progress", "file.cpp"}; Settings settings; @@ -593,8 +545,7 @@ private: ASSERT(settings.reportProgress); } - void stdposix() - { + void stdposix() { REDIRECT; const char *argv[] = {"cppcheck", "--std=posix", "file.cpp"}; Settings settings; @@ -603,8 +554,7 @@ private: ASSERT(settings.posix); } - void stdc99() - { + void stdc99() { REDIRECT; const char *argv[] = {"cppcheck", "--std=c99", "file.cpp"}; Settings settings; @@ -613,8 +563,7 @@ private: ASSERT(settings.c99); } - void suppressionsOld() - { + void suppressionsOld() { // TODO: Fails because there is no suppr.txt file! REDIRECT; const char *argv[] = {"cppcheck", "--suppressions", "suppr.txt", "file.cpp"}; @@ -623,8 +572,7 @@ private: ASSERT(!parser.ParseFromArgs(4, argv)); } - void suppressions() - { + void suppressions() { // TODO: Fails because there is no suppr.txt file! REDIRECT; const char *argv[] = {"cppcheck", "--suppressions-list=suppr.txt", "file.cpp"}; @@ -633,8 +581,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(3, argv)); } - void suppressionsNoFile() - { + void suppressionsNoFile() { // TODO: Fails because there is no suppr.txt file! REDIRECT; const char *argv[] = {"cppcheck", "--suppressions-list=", "file.cpp"}; @@ -643,8 +590,7 @@ private: TODO_ASSERT_EQUALS(true, false, parser.ParseFromArgs(3, argv)); } - void suppressionSingle() - { + void suppressionSingle() { REDIRECT; const char *argv[] = {"cppcheck", "--suppress=uninitvar", "file.cpp"}; Settings settings; @@ -653,8 +599,7 @@ private: ASSERT_EQUALS(true, settings.nomsg.isSuppressed("uninitvar", "file.cpp", 1U)); } - void suppressionSingleFile() - { + void suppressionSingleFile() { REDIRECT; const char *argv[] = {"cppcheck", "--suppress=uninitvar:file.cpp", "file.cpp"}; Settings settings; @@ -663,8 +608,7 @@ private: ASSERT_EQUALS(true, settings.nomsg.isSuppressed("uninitvar", "file.cpp", 1U)); } - void suppressionTwo() - { + void suppressionTwo() { REDIRECT; const char *argv[] = {"cppcheck", "--suppress=uninitvar,unnecessaryQualification", "file.cpp"}; Settings settings; @@ -674,8 +618,7 @@ private: TODO_ASSERT_EQUALS(true, false, settings.nomsg.isSuppressed("unnecessaryQualification", "file.cpp", 1U)); } - void suppressionTwoSeparate() - { + void suppressionTwoSeparate() { REDIRECT; const char *argv[] = {"cppcheck", "--suppress=uninitvar", "--suppress=unnecessaryQualification", "file.cpp"}; Settings settings; @@ -685,8 +628,7 @@ private: ASSERT_EQUALS(true, settings.nomsg.isSuppressed("unnecessaryQualification", "file.cpp", 1U)); } - void templates() - { + void templates() { REDIRECT; const char *argv[] = {"cppcheck", "--template", "{file}:{line},{severity},{id},{message}", "file.cpp"}; Settings settings; @@ -695,8 +637,7 @@ private: ASSERT_EQUALS("{file}:{line},{severity},{id},{message}", settings._outputFormat); } - void templatesGcc() - { + void templatesGcc() { REDIRECT; const char *argv[] = {"cppcheck", "--template", "gcc", "file.cpp"}; Settings settings; @@ -705,8 +646,7 @@ private: ASSERT_EQUALS("{file}:{line}: {severity}: {message}", settings._outputFormat); } - void templatesVs() - { + void templatesVs() { REDIRECT; const char *argv[] = {"cppcheck", "--template", "vs", "file.cpp"}; Settings settings; @@ -715,8 +655,7 @@ private: ASSERT_EQUALS("{file}({line}): {severity}: {message}", settings._outputFormat); } - void xml() - { + void xml() { REDIRECT; const char *argv[] = {"cppcheck", "--xml", "file.cpp"}; Settings settings; @@ -726,8 +665,7 @@ private: ASSERT_EQUALS(1, settings._xml_version); } - void xmlver1() - { + void xmlver1() { REDIRECT; const char *argv[] = {"cppcheck", "--xml-version=1", "file.cpp"}; Settings settings; @@ -737,8 +675,7 @@ private: ASSERT_EQUALS(1, settings._xml_version); } - void xmlver2() - { + void xmlver2() { REDIRECT; const char *argv[] = {"cppcheck", "--xml-version=2", "file.cpp"}; Settings settings; @@ -748,8 +685,7 @@ private: ASSERT_EQUALS(2, settings._xml_version); } - void xmlver2both() - { + void xmlver2both() { REDIRECT; const char *argv[] = {"cppcheck", "--xml", "--xml-version=2", "file.cpp"}; Settings settings; @@ -759,8 +695,7 @@ private: ASSERT_EQUALS(2, settings._xml_version); } - void xmlver2both2() - { + void xmlver2both2() { REDIRECT; const char *argv[] = {"cppcheck", "--xml-version=2", "--xml", "file.cpp"}; Settings settings; @@ -770,8 +705,7 @@ private: ASSERT_EQUALS(2, settings._xml_version); } - void xmlverunknown() - { + void xmlverunknown() { REDIRECT; const char *argv[] = {"cppcheck", "--xml", "--xml-version=3", "file.cpp"}; Settings settings; @@ -780,8 +714,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(4, argv)); } - void xmlverinvalid() - { + void xmlverinvalid() { REDIRECT; const char *argv[] = {"cppcheck", "--xml", "--xml-version=a", "file.cpp"}; Settings settings; @@ -790,8 +723,7 @@ private: ASSERT_EQUALS(false, parser.ParseFromArgs(4, argv)); } - void errorlist1() - { + void errorlist1() { REDIRECT; const char *argv[] = {"cppcheck", "--errorlist"}; Settings settings; @@ -799,8 +731,7 @@ private: ASSERT(parser.ParseFromArgs(2, argv)); } - void errorlistverbose1() - { + void errorlistverbose1() { REDIRECT; const char *argv[] = {"cppcheck", "--verbose", "--errorlist"}; Settings settings; @@ -809,8 +740,7 @@ private: ASSERT(settings._verbose); } - void errorlistverbose2() - { + void errorlistverbose2() { REDIRECT; const char *argv[] = {"cppcheck", "--errorlist", "--verbose"}; Settings settings; @@ -819,8 +749,7 @@ private: ASSERT(settings._verbose); } - void ignorepathsnopath() - { + void ignorepathsnopath() { REDIRECT; const char *argv[] = {"cppcheck", "-i"}; Settings settings; @@ -830,8 +759,7 @@ private: ASSERT_EQUALS(0, parser.GetIgnoredPaths().size()); } - void ignorepaths1() - { + void ignorepaths1() { REDIRECT; const char *argv[] = {"cppcheck", "-isrc", "file.cpp"}; Settings settings; @@ -841,8 +769,7 @@ private: ASSERT_EQUALS("src/", parser.GetIgnoredPaths()[0]); } - void ignorepaths2() - { + void ignorepaths2() { REDIRECT; const char *argv[] = {"cppcheck", "-i", "src", "file.cpp"}; Settings settings; @@ -852,8 +779,7 @@ private: ASSERT_EQUALS("src/", parser.GetIgnoredPaths()[0]); } - void ignorepaths3() - { + void ignorepaths3() { REDIRECT; const char *argv[] = {"cppcheck", "-isrc", "-imodule", "file.cpp"}; Settings settings; @@ -864,8 +790,7 @@ private: ASSERT_EQUALS("module/", parser.GetIgnoredPaths()[1]); } - void ignorepaths4() - { + void ignorepaths4() { REDIRECT; const char *argv[] = {"cppcheck", "-i", "src", "-i", "module", "file.cpp"}; Settings settings; @@ -876,8 +801,7 @@ private: ASSERT_EQUALS("module/", parser.GetIgnoredPaths()[1]); } - void ignorefilepaths1() - { + void ignorefilepaths1() { REDIRECT; const char *argv[] = {"cppcheck", "-ifoo.cpp", "file.cpp"}; Settings settings; @@ -887,8 +811,7 @@ private: ASSERT_EQUALS("foo.cpp", parser.GetIgnoredPaths()[0]); } - void ignorefilepaths2() - { + void ignorefilepaths2() { REDIRECT; const char *argv[] = {"cppcheck", "-isrc/foo.cpp", "file.cpp"}; Settings settings; @@ -898,8 +821,7 @@ private: ASSERT_EQUALS("src/foo.cpp", parser.GetIgnoredPaths()[0]); } - void checkconfig() - { + void checkconfig() { REDIRECT; const char *argv[] = {"cppcheck", "--check-config", "file.cpp"}; Settings settings; @@ -908,8 +830,7 @@ private: ASSERT_EQUALS(true, settings.checkConfiguration); } - void unknownParam() - { + void unknownParam() { REDIRECT; const char *argv[] = {"cppcheck", "--foo", "file.cpp"}; Settings settings; diff --git a/test/testconstructors.cpp b/test/testconstructors.cpp index ddab2a1e6..1c20bcd36 100644 --- a/test/testconstructors.cpp +++ b/test/testconstructors.cpp @@ -25,8 +25,7 @@ extern std::ostringstream errout; -class TestConstructors : public TestFixture -{ +class TestConstructors : public TestFixture { public: TestConstructors() : TestFixture("TestConstructors") { } @@ -34,8 +33,7 @@ public: private: - void check(const char code[], bool showAll = false) - { + void check(const char code[], bool showAll = false) { // Clear the error buffer.. errout.str(""); @@ -54,8 +52,7 @@ private: checkClass.constructors(); } - void run() - { + void run() { TEST_CASE(simple1); TEST_CASE(simple2); TEST_CASE(simple3); @@ -87,8 +84,7 @@ private: } - void simple1() - { + void simple1() { check("class Fred\n" "{\n" "public:\n" @@ -118,8 +114,7 @@ private: } - void simple2() - { + void simple2() { check("class Fred\n" "{\n" "public:\n" @@ -167,8 +162,7 @@ private: } - void simple3() - { + void simple3() { check("class Fred\n" "{\n" "public:\n" @@ -228,8 +222,7 @@ private: } - void simple4() - { + void simple4() { check("class Fred\n" "{\n" "public:\n" @@ -260,8 +253,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout.str()); } - void simple5() // ticket #2560 - { + void simple5() { // ticket #2560 check("namespace Nsp\n" "{\n" " class B { };\n" @@ -278,8 +270,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_with_this() - { + void initvar_with_this() { check("class Fred\n" "{\n" "public:\n" @@ -298,8 +289,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_if() - { + void initvar_if() { check("class Fred\n" "{\n" "public:\n" @@ -329,8 +319,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_operator_eq1() - { + void initvar_operator_eq1() { // Bug 2190376 - False positive, Uninitialized member variable with operator= check("class Fred\n" @@ -406,8 +395,7 @@ private: } - void initvar_operator_eq2() - { + void initvar_operator_eq2() { check("class Fred\n" "{\n" "public:\n" @@ -426,8 +414,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::i' is not assigned a value in 'Fred::operator='\n", errout.str()); } - void initvar_operator_eq3() - { + void initvar_operator_eq3() { check("class Fred\n" "{\n" "public:\n" @@ -450,8 +437,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_operator_eq4() - { + void initvar_operator_eq4() { check("class Fred\n" "{\n" " int i;\n" @@ -513,8 +499,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_same_classname() - { + void initvar_same_classname() { // Bug 2208157 - False positive: Uninitialized variable, same class name check("void func1()\n" @@ -623,8 +608,7 @@ private: "[test.cpp:16]: (warning) Member variable 'Fred::b' is not initialized in the constructor.\n", errout.str()); } - void initvar_chained_assign() - { + void initvar_chained_assign() { // Bug 2270433 - Uninitialized variable false positive on chained assigns check("class c\n" @@ -659,8 +643,7 @@ private: } - void initvar_2constructors() - { + void initvar_2constructors() { check("class c\n" "{\n" " c();\n" @@ -723,8 +706,7 @@ private: } - void initvar_constvar() - { + void initvar_constvar() { check("class Fred\n" "{\n" "public:\n" @@ -784,8 +766,7 @@ private: } - void initvar_staticvar() - { + void initvar_staticvar() { check("class Fred\n" "{\n" "public:\n" @@ -796,8 +777,7 @@ private: } - void initvar_union() - { + void initvar_union() { check("class Fred\n" "{\n" " union\n" @@ -829,8 +809,7 @@ private: } - void initvar_private_constructor() - { + void initvar_private_constructor() { check("class Fred\n" "{\n" "private:\n" @@ -842,8 +821,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void initvar_copy_constructor() // ticket #1611 - { + void initvar_copy_constructor() { // ticket #1611 check("class Fred\n" "{\n" "private:\n" @@ -867,8 +845,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Fred::var' is not initialized in the constructor.\n", errout.str()); } - void initvar_nested_constructor() // ticket #1375 - { + void initvar_nested_constructor() { // ticket #1375 check("class A {\n" "public:\n" " A();\n" @@ -958,8 +935,7 @@ private: "[test.cpp:24]: (warning) Member variable 'D::d' is not initialized in the constructor.\n", errout.str()); } - void initvar_nocopy1() // ticket #2474 - { + void initvar_nocopy1() { // ticket #2474 check("class B\n" "{\n" " B (const B & Var);\n" @@ -1004,8 +980,7 @@ private: "[test.cpp:7]: (warning) Member variable 'A::m_SemVar' is not assigned a value in 'A::operator='\n", errout.str()); } - void initvar_nocopy2() // ticket #2484 - { + void initvar_nocopy2() { // ticket #2484 check("class B\n" "{\n" " B (B & Var);\n" @@ -1039,8 +1014,7 @@ private: "[test.cpp:13]: (warning) Member variable 'A::m_SemVar' is not assigned a value in 'A::operator='\n", errout.str()); } - void initvar_destructor() - { + void initvar_destructor() { check("class Fred\n" "{\n" "private:\n" @@ -1052,8 +1026,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void operatorEqSTL() - { + void operatorEqSTL() { check("class Fred\n" "{\n" "private:\n" diff --git a/test/testcppcheck.cpp b/test/testcppcheck.cpp index 56a033efc..1e3c63247 100644 --- a/test/testcppcheck.cpp +++ b/test/testcppcheck.cpp @@ -37,54 +37,44 @@ extern std::ostringstream errout; extern std::ostringstream output; -class TestCppcheck : public TestFixture -{ +class TestCppcheck : public TestFixture { public: TestCppcheck() : TestFixture("TestCppcheck") { } private: - class ErrorLogger2 : public ErrorLogger - { + class ErrorLogger2 : public ErrorLogger { public: std::list id; - void reportOut(const std::string & /*outmsg*/) - { + void reportOut(const std::string & /*outmsg*/) { } - void reportErr(const ErrorLogger::ErrorMessage &msg) - { + void reportErr(const ErrorLogger::ErrorMessage &msg) { id.push_back(msg._id); } - void reportStatus(unsigned int /*fileindex*/, unsigned int /*filecount*/, long /*sizedone*/, long /*sizetotal*/) - { + void reportStatus(unsigned int /*fileindex*/, unsigned int /*filecount*/, long /*sizedone*/, long /*sizetotal*/) { } }; - void run() - { + void run() { TEST_CASE(instancesSorted); TEST_CASE(getErrorMessages); } - void instancesSorted() - { - for (std::list::iterator i = Check::instances().begin(); i != Check::instances().end(); ++i) - { + void instancesSorted() { + for (std::list::iterator i = Check::instances().begin(); i != Check::instances().end(); ++i) { std::list::iterator j = i; ++j; - if (j != Check::instances().end()) - { + if (j != Check::instances().end()) { ASSERT_EQUALS(true, (*i)->name() < (*j)->name()); } } } - void getErrorMessages() - { + void getErrorMessages() { ErrorLogger2 errorLogger; CppCheck cppCheck(errorLogger, true); cppCheck.getErrorMessages(); @@ -94,10 +84,8 @@ private: std::string duplicate; for (std::list::iterator it = errorLogger.id.begin(); it != errorLogger.id.end(); - ++it) - { - if (std::find(errorLogger.id.begin(), it, *it) != it) - { + ++it) { + if (std::find(errorLogger.id.begin(), it, *it) != it) { duplicate = "Duplicate ID: " + *it; break; } diff --git a/test/testdivision.cpp b/test/testdivision.cpp index 0f264eb37..49757ce98 100644 --- a/test/testdivision.cpp +++ b/test/testdivision.cpp @@ -29,15 +29,13 @@ extern std::ostringstream errout; -class TestDivision : public TestFixture -{ +class TestDivision : public TestFixture { public: TestDivision() : TestFixture("TestDivision") { } private: - void check(const char code[], bool style = true) - { + void check(const char code[], bool style = true) { // Clear the error buffer.. errout.str(""); @@ -55,8 +53,7 @@ private: checkOther.checkUnsignedDivision(); } - void run() - { + void run() { TEST_CASE(division1); TEST_CASE(division2); TEST_CASE(division4); @@ -68,8 +65,7 @@ private: TEST_CASE(division10); } - void division1() - { + void division1() { check("void f()\n" "{\n" " int ivar = -2;\n" @@ -80,8 +76,7 @@ private: "", errout.str()); } - void division2() - { + void division2() { check("void f()\n" "{\n" " int ivar = -2;\n" @@ -92,8 +87,7 @@ private: "", errout.str()); } - void division4() - { + void division4() { check("void f1()\n" "{\n" " int i1;\n" @@ -118,8 +112,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void division5() - { + void division5() { check("#define USER_HASH (16)\n" "void foo()\n" "{\n" @@ -129,8 +122,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void division6() - { + void division6() { check("void foo()\n" "{\n" " unsigned int val = 32;\n" @@ -139,8 +131,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Unsigned division. The result will be wrong.\n", errout.str()); } - void division7() - { + void division7() { check("void foo()\n" "{\n" " unsigned int val = 32;\n" @@ -148,8 +139,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Unsigned division. The result will be wrong.\n", errout.str()); } - void division8() - { + void division8() { check("void foo(int b)\n" "{\n" " if (b > 0)\n" @@ -180,8 +170,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void division9() - { + void division9() { check("void f()\n" "{\n" " int ivar = -2;\n" @@ -201,8 +190,7 @@ private: "", errout.str()); } - void division10() - { + void division10() { // Ticket: #2932 - don't segfault check("i / i"); ASSERT_EQUALS("", errout.str()); diff --git a/test/testerrorlogger.cpp b/test/testerrorlogger.cpp index b7a00c1c2..3b1a5e898 100644 --- a/test/testerrorlogger.cpp +++ b/test/testerrorlogger.cpp @@ -21,16 +21,14 @@ #include "testsuite.h" #include "errorlogger.h" -class TestErrorLogger : public TestFixture -{ +class TestErrorLogger : public TestFixture { public: TestErrorLogger() : TestFixture("TestErrorLogger") { } private: - void run() - { + void run() { TEST_CASE(FileLocationDefaults); TEST_CASE(FileLocationSetFile); TEST_CASE(ErrorMessageConstruct); @@ -54,23 +52,20 @@ private: TEST_CASE(SerializeInconclusiveMessage); } - void FileLocationDefaults() - { + void FileLocationDefaults() { ErrorLogger::ErrorMessage::FileLocation loc; ASSERT_EQUALS("", loc.getfile()); ASSERT_EQUALS(0, loc.line); } - void FileLocationSetFile() - { + void FileLocationSetFile() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); ASSERT_EQUALS("foo.cpp", loc.getfile()); ASSERT_EQUALS(0, loc.line); } - void ErrorMessageConstruct() - { + void ErrorMessageConstruct() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -84,8 +79,7 @@ private: ASSERT_EQUALS("[foo.cpp:5]: (error) Programming error.", msg.toString(true)); } - void ErrorMessageConstructLocations() - { + void ErrorMessageConstructLocations() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -103,8 +97,7 @@ private: ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Programming error.", msg.toString(true)); } - void ErrorMessageVerbose() - { + void ErrorMessageVerbose() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -118,8 +111,7 @@ private: ASSERT_EQUALS("[foo.cpp:5]: (error) Verbose error", msg.toString(true)); } - void ErrorMessageVerboseLocations() - { + void ErrorMessageVerboseLocations() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -137,8 +129,7 @@ private: ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Verbose error", msg.toString(true)); } - void CustomFormat() - { + void CustomFormat() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -152,8 +143,7 @@ private: ASSERT_EQUALS("foo.cpp:5,error,errorId,Verbose error", msg.toString(true, "{file}:{line},{severity},{id},{message}")); } - void CustomFormat2() - { + void CustomFormat2() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -167,8 +157,7 @@ private: ASSERT_EQUALS("Verbose error - foo.cpp(5):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})")); } - void CustomFormatLocations() - { + void CustomFormatLocations() { // Check that first location from location stack is used in template ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); @@ -187,8 +176,7 @@ private: ASSERT_EQUALS("Verbose error - bar.cpp(8):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})")); } - void ToXml() - { + void ToXml() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -200,8 +188,7 @@ private: ASSERT_EQUALS("", msg.toXML(false,1)); } - void ToXmlLocations() - { + void ToXmlLocations() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -217,8 +204,7 @@ private: ASSERT_EQUALS("", msg.toXML(false,1)); } - void ToVerboseXml() - { + void ToVerboseXml() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -230,8 +216,7 @@ private: ASSERT_EQUALS("", msg.toXML(true,1)); } - void ToVerboseXmlLocations() - { + void ToVerboseXmlLocations() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -247,8 +232,7 @@ private: ASSERT_EQUALS("", msg.toXML(true,1)); } - void ToXmlV2() - { + void ToXmlV2() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -267,8 +251,7 @@ private: ASSERT_EQUALS(message, msg.toXML(false, 2)); } - void ToXmlV2Locations() - { + void ToXmlV2Locations() { ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); loc.line = 5; @@ -292,8 +275,7 @@ private: ASSERT_EQUALS(message, msg.toXML(false, 2)); } - void InconclusiveXml() - { + void InconclusiveXml() { // Location ErrorLogger::ErrorMessage::FileLocation loc; loc.setfile("foo.cpp"); @@ -311,8 +293,7 @@ private: ASSERT_EQUALS("", msg.toXML(false, 2)); } - void SerializeInconclusiveMessage() - { + void SerializeInconclusiveMessage() { // Inconclusive error message std::list locs; ErrorMessage msg(locs, Severity::error, "Programming error", "errorId", true); diff --git a/test/testexceptionsafety.cpp b/test/testexceptionsafety.cpp index 6a926e5ae..9d3e233d5 100644 --- a/test/testexceptionsafety.cpp +++ b/test/testexceptionsafety.cpp @@ -24,16 +24,14 @@ extern std::ostringstream errout; -class TestExceptionSafety : public TestFixture -{ +class TestExceptionSafety : public TestFixture { public: TestExceptionSafety() : TestFixture("TestExceptionSafety") { } private: - void run() - { + void run() { TEST_CASE(destructors); TEST_CASE(deallocThrow1); TEST_CASE(deallocThrow2); @@ -42,8 +40,7 @@ private: TEST_CASE(rethrowCopy3); } - void check(const std::string &code) - { + void check(const std::string &code) { // Clear the error buffer.. errout.str(""); @@ -61,8 +58,7 @@ private: checkExceptionSafety.runSimplifiedChecks(&tokenizer, &settings, this); } - void destructors() - { + void destructors() { check("x::~x()\n" "{\n" " throw e;\n" @@ -70,8 +66,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Throwing exception in destructor\n", errout.str()); } - void deallocThrow1() - { + void deallocThrow1() { check("int * p;\n" "void f(int x)\n" "{\n" @@ -83,8 +78,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Throwing exception in invalid state, p points at deallocated memory\n", errout.str()); } - void deallocThrow2() - { + void deallocThrow2() { check("void f() {\n" " int* p = 0;\n" " delete p;\n" @@ -94,8 +88,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void rethrowCopy1() - { + void rethrowCopy1() { check("void f() {\n" " try\n" " {\n" @@ -109,8 +102,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception\n", errout.str()); } - void rethrowCopy2() - { + void rethrowCopy2() { check("void f() {\n" " try\n" " {\n" @@ -124,8 +116,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception\n", errout.str()); } - void rethrowCopy3() - { + void rethrowCopy3() { check("void f() {\n" " try\n" " {\n" diff --git a/test/testfilelister.cpp b/test/testfilelister.cpp index 14ce6ac2d..7382dbe7e 100644 --- a/test/testfilelister.cpp +++ b/test/testfilelister.cpp @@ -21,16 +21,14 @@ #include #include -class TestFileLister: public TestFixture -{ +class TestFileLister: public TestFixture { public: TestFileLister() :TestFixture("TestFileLister") {} private: - void run() - { + void run() { // bail out if the tests are not executed from the base folder { std::ifstream fin("test/testfilelister.cpp"); @@ -42,28 +40,24 @@ private: TEST_CASE(recursiveAddFiles); } - void isDirectory() - { + void isDirectory() { ASSERT_EQUALS(false, FileLister::isDirectory("readme.txt")); ASSERT_EQUALS(true, FileLister::isDirectory("lib")); } - void recursiveAddFiles() - { + void recursiveAddFiles() { // Recursively add add files.. std::vector filenames; std::map filesizes; FileLister::recursiveAddFiles(filenames, filesizes, "."); // Ensure a size entry is present for each listed file - for (std::vector::const_iterator i = filenames.begin(); i != filenames.end(); ++i) - { + for (std::vector::const_iterator i = filenames.begin(); i != filenames.end(); ++i) { ASSERT(filesizes.find(*i) != filesizes.end()); } // In case there are leading "./".. - for (unsigned int i = 0; i < filenames.size(); ++i) - { + for (unsigned int i = 0; i < filenames.size(); ++i) { if (filenames[i].compare(0,2,"./") == 0) filenames[i].erase(0,2); } diff --git a/test/testincompletestatement.cpp b/test/testincompletestatement.cpp index 45d0e66da..e6dbbf18d 100644 --- a/test/testincompletestatement.cpp +++ b/test/testincompletestatement.cpp @@ -29,15 +29,13 @@ extern std::ostringstream errout; -class TestIncompleteStatement : public TestFixture -{ +class TestIncompleteStatement : public TestFixture { public: TestIncompleteStatement() : TestFixture("TestIncompleteStatement") { } private: - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -55,8 +53,7 @@ private: checkOther.checkIncompleteStatement(); } - void run() - { + void run() { TEST_CASE(test1); TEST_CASE(test2); TEST_CASE(test3); @@ -72,8 +69,7 @@ private: TEST_CASE(cast); // #3009 : (struct Foo *)123.a = 1; } - void test1() - { + void test1() { check("void foo()\n" "{\n" " const char def[] =\n" @@ -87,8 +83,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void test2() - { + void test2() { check("void foo()\n" "{\n" " \"abc\";\n" @@ -97,8 +92,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with string constant\n", errout.str()); } - void test3() - { + void test3() { check("void foo()\n" "{\n" " const char *str[] = { \"abc\" };\n" @@ -107,8 +101,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void test4() - { + void test4() { check("void foo()\n" "{\n" "const char *a =\n" @@ -122,8 +115,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void test5() - { + void test5() { check("void foo()\n" "{\n" " 50;\n" @@ -132,8 +124,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with numeric constant\n", errout.str()); } - void test_numeric() - { + void test_numeric() { check("struct P\n" "{\n" "double a;\n" @@ -150,14 +141,12 @@ private: ASSERT_EQUALS("", errout.str()); } - void intarray() - { + void intarray() { check("int arr[] = { 100/2, 1*100 };\n"); ASSERT_EQUALS("", errout.str()); } - void structarraynull() - { + void structarraynull() { check("struct st arr[] = {\n" " { 100/2, 1*100 }\n" " { 90, 70 }\n" @@ -165,8 +154,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structarray() - { + void structarray() { check("struct st arr[] = {\n" " { 100/2, 1*100 }\n" " { 90, 70 }\n" @@ -174,16 +162,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void conditionalcall() - { + void conditionalcall() { check("void f() {\n" " 0==x ? X() : Y();\n" "}\n"); ASSERT_EQUALS("", errout.str()); } - void structinit() - { + void structinit() { // #2462 - C++0x struct initialization check("void f() {\n" " ABC abc{1,2,3};\n" @@ -195,16 +181,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void returnstruct() - { + void returnstruct() { check("struct s foo() {\n" " return (struct s){0,0};\n" "}"); ASSERT_EQUALS("", errout.str()); } - void cast() - { + void cast() { check("void f() {\n" " ((struct foo *)(0x1234))->xy = 1;\n" "}"); diff --git a/test/testmathlib.cpp b/test/testmathlib.cpp index f68b1c98c..e33d5573b 100644 --- a/test/testmathlib.cpp +++ b/test/testmathlib.cpp @@ -21,16 +21,14 @@ #include "mathlib.h" #include "testsuite.h" -class TestMathLib : public TestFixture -{ +class TestMathLib : public TestFixture { public: TestMathLib() : TestFixture("TestMathLib") { } private: - void run() - { + void run() { TEST_CASE(calculate); TEST_CASE(convert); TEST_CASE(isint); @@ -44,49 +42,42 @@ private: TEST_CASE(isLessEqual) } - void isGreater() - { + void isGreater() { ASSERT_EQUALS(true , MathLib::isGreater("1.0", "0.001")); ASSERT_EQUALS(false, MathLib::isGreater("-1.0", "0.001")); } - void isGreaterEqual() - { + void isGreaterEqual() { ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.00", "1.0")); ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.001", "1.0")); ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.0", "0.001")); ASSERT_EQUALS(false, MathLib::isGreaterEqual("-1.0", "0.001")); } - void isEqual() - { + void isEqual() { ASSERT_EQUALS(true , MathLib::isEqual("1.0", "1.0")); ASSERT_EQUALS(false , MathLib::isEqual("1.", "1.01")); ASSERT_EQUALS(true , MathLib::isEqual("0.1","1.0E-1")); } - void isNotEqual() - { + void isNotEqual() { ASSERT_EQUALS(false , MathLib::isNotEqual("1.0", "1.0")); ASSERT_EQUALS(true , MathLib::isNotEqual("1.", "1.01")); } - void isLess() - { + void isLess() { ASSERT_EQUALS(false , MathLib::isLess("1.0", "0.001")); ASSERT_EQUALS(true , MathLib::isLess("-1.0", "0.001")); } - void isLessEqual() - { + void isLessEqual() { ASSERT_EQUALS(true , MathLib::isLessEqual("1.00", "1.0")); ASSERT_EQUALS(false , MathLib::isLessEqual("1.001", "1.0")); ASSERT_EQUALS(false , MathLib::isLessEqual("1.0", "0.001")); ASSERT_EQUALS(true , MathLib::isLessEqual("-1.0", "0.001")); } - void calculate() - { + void calculate() { // addition ASSERT_EQUALS("256", MathLib::add("0xff", "1")); ASSERT_EQUALS("249", MathLib::add("250", "-1")); @@ -130,8 +121,7 @@ private: } - void convert() - { + void convert() { // ------------------ // tolong conversion: // ------------------ @@ -195,8 +185,7 @@ private: } - void isint() - { + void isint() { // zero tests ASSERT_EQUALS(true , MathLib::isInt("0")); ASSERT_EQUALS(false, MathLib::isInt("0.")); @@ -273,8 +262,7 @@ private: ASSERT_EQUALS(false, MathLib::isInt("LL")); } - void isnegative() - { + void isnegative() { ASSERT_EQUALS(true, MathLib::isNegative("-1")); ASSERT_EQUALS(true, MathLib::isNegative("-1.")); ASSERT_EQUALS(true, MathLib::isNegative("-1.0")); @@ -288,8 +276,7 @@ private: ASSERT_EQUALS(false, MathLib::isNegative("+1.0E-2")); } - void isfloat() - { + void isfloat() { ASSERT_EQUALS(false, MathLib::isFloat("0")); ASSERT_EQUALS(true , MathLib::isFloat("0.")); ASSERT_EQUALS(true , MathLib::isFloat("0.0")); diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp index 4838f7220..17cee2906 100644 --- a/test/testmemleak.cpp +++ b/test/testmemleak.cpp @@ -27,21 +27,18 @@ extern std::ostringstream errout; -class TestMemleak : private TestFixture -{ +class TestMemleak : private TestFixture { public: TestMemleak() : TestFixture("TestMemleak") { } private: - void run() - { + void run() { TEST_CASE(testFunctionReturnType); TEST_CASE(open); } - CheckMemoryLeak::AllocType functionReturnType(const char code[]) - { + CheckMemoryLeak::AllocType functionReturnType(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -56,8 +53,7 @@ private: return ((const CheckMemoryLeak *)0)->functionReturnType(tokenizer.tokens()); } - void testFunctionReturnType() - { + void testFunctionReturnType() { { const char code[] = "const char *foo()\n" "{ return 0; }"; @@ -86,8 +82,7 @@ private: } } - void open() - { + void open() { const char code[] = "class A {\n" " static int open() {\n" " return 1;\n" @@ -120,15 +115,13 @@ static TestMemleak testMemleak; -class TestMemleakInFunction : public TestFixture -{ +class TestMemleakInFunction : public TestFixture { public: TestMemleakInFunction() : TestFixture("TestMemleakInFunction") { } private: - void check(const char code[], bool experimental = false) - { + void check(const char code[], bool experimental = false) { // Clear the error buffer.. errout.str(""); @@ -151,8 +144,7 @@ private: } - void run() - { + void run() { // Check that getcode works correctly.. TEST_CASE(testgetcode); @@ -357,8 +349,7 @@ private: - std::string getcode(const char code[], const char varname[], bool classfunc=false) const - { + std::string getcode(const char code[], const char varname[], bool classfunc=false) const { // Clear the error buffer.. errout.str(""); @@ -394,8 +385,7 @@ private: - void testgetcode() - { + void testgetcode() { // alloc; ASSERT_EQUALS(";;alloc;", getcode("int *a = malloc(100);", "a")); ASSERT_EQUALS(";;alloc;", getcode("int *a = new int;", "a")); @@ -556,8 +546,7 @@ private: } - void call_func() - { + void call_func() { // whitelist.. ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list("qsort")); ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list("scanf")); @@ -581,8 +570,7 @@ private: ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list("snprintf")); ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list("vsnprintf")); - static const char * const call_func_white_list[] = - { + static const char * const call_func_white_list[] = { "access", "asprintf", "atof", "atoi", "atol", "chdir", "chmod", "clearerr", "chown", "delete" , "fchmod", "fcntl", "fdatasync", "feof", "ferror", "fflush", "fgetc", "fgetpos", "fgets" , "flock", "for", "fprintf", "fputc", "fputs", "fread", "free", "freopen", "fscanf", "fseek" @@ -606,16 +594,14 @@ private: , "readlink", "regcomp", "strxfrm", "wordexp", "sizeof", "strtok" }; - for (unsigned int i = 0; i < (sizeof(call_func_white_list) / sizeof(char *)); ++i) - { + for (unsigned int i = 0; i < (sizeof(call_func_white_list) / sizeof(char *)); ++i) { bool ret = CheckMemoryLeakInFunction::test_white_list(call_func_white_list[i]); ASSERT_EQUALS("", ret ? "" : call_func_white_list[i]); } } - std::string simplifycode(const char code[]) const - { + std::string simplifycode(const char code[]) const { // Clear the error buffer.. errout.str(""); @@ -628,16 +614,13 @@ private: Token *tokens = const_cast(tokenizer.tokens()); // replace "if ( ! var )" => "if(!var)" - for (Token *tok = tokens; tok; tok = tok->next()) - { - if (Token::Match(tok, "if|while ( var )")) - { + for (Token *tok = tokens; tok; tok = tok->next()) { + if (Token::Match(tok, "if|while ( var )")) { Token::eraseTokens(tok, tok->tokAt(4)); tok->str(tok->str() + "(var)"); } - else if (Token::Match(tok, "if|while ( ! var )")) - { + else if (Token::Match(tok, "if|while ( ! var )")) { Token::eraseTokens(tok, tok->tokAt(5)); tok->str(tok->str() + "(!var)"); } @@ -655,8 +638,7 @@ private: // Test that the CheckMemoryLeaksInFunction::simplifycode works - void simplifycode() - { + void simplifycode() { ASSERT_EQUALS(";", simplifycode("; ; ; ;")); ASSERT_EQUALS(";", simplifycode("; if ;")); ASSERT_EQUALS("alloc ;", simplifycode("alloc ; if ; if(var) ; ifv ; if(!var) ;")); @@ -781,8 +763,7 @@ private: // is there a leak in given code? if so, return the linenr - unsigned int dofindleak(const char code[]) const - { + unsigned int dofindleak(const char code[]) const { // Clear the error buffer.. errout.str(""); @@ -795,21 +776,17 @@ private: tokenizer.tokenize(istr, "test.cpp"); // replace "if ( ! var )" => "if(!var)" - for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) - { - if (tok->str() == "if_var") - { + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { + if (tok->str() == "if_var") { tok->str("if(var)"); } - else if (Token::simpleMatch(tok, "if ( var )")) - { + else if (Token::simpleMatch(tok, "if ( var )")) { Token::eraseTokens(tok, tok->tokAt(4)); tok->str("if(var)"); } - else if (Token::simpleMatch(tok, "if ( ! var )")) - { + else if (Token::simpleMatch(tok, "if ( ! var )")) { Token::eraseTokens(tok, tok->tokAt(5)); tok->str("if(!var)"); } @@ -819,8 +796,7 @@ private: return (tok ? tok->linenr() : (unsigned int)(-1)); } - void findleak() - { + void findleak() { static const unsigned int notfound = (unsigned int)(-1); ASSERT_EQUALS(1, dofindleak("alloc;")); @@ -871,8 +847,7 @@ private: } - void simple5() - { + void simple5() { check("static char *f()\n" "{\n" " struct *str = new strlist;\n" @@ -882,8 +857,7 @@ private: } - void simple7() - { + void simple7() { // A garbage collector may delete f automaticly check("class Fred;\n" "void foo()\n" @@ -894,8 +868,7 @@ private: } - void simple9() - { + void simple9() { check("void foo()\n" "{\n" " MyClass *c = new MyClass();\n" @@ -905,8 +878,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simple11() - { + void simple11() { check("void Fred::aaa()\n" "{ }\n" "\n" @@ -929,8 +901,7 @@ private: - void new_nothrow() - { + void new_nothrow() { check("void f()\n" "{\n" " int *p = new(std::nothrow) int;\n" @@ -1000,8 +971,7 @@ private: } - void staticvar() - { + void staticvar() { check("int f()\n" "{\n" " static char *s = 0;\n" @@ -1012,8 +982,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void externvar() - { + void externvar() { check("void f()\n" "{\n" " extern char *s;\n" @@ -1024,8 +993,7 @@ private: - void alloc_alloc_1() - { + void alloc_alloc_1() { check("void foo()\n" "{\n" " char *str;\n" @@ -1045,8 +1013,7 @@ private: - void ifelse6() - { + void ifelse6() { check("static char *f()\n" "{\n" " char *s = new char[100];\n" @@ -1060,8 +1027,7 @@ private: } - void ifelse7() - { + void ifelse7() { check("static char *f()\n" "{\n" " char *s;\n" @@ -1075,8 +1041,7 @@ private: } - void ifelse8() - { + void ifelse8() { check("static char *f()\n" "{\n" " char *s = new char[10];\n" @@ -1089,8 +1054,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ifelse10() - { + void ifelse10() { check("static char *f()\n" "{\n" " char *s = new char[10];\n" @@ -1108,8 +1072,7 @@ private: - void if4() - { + void if4() { check("void f()\n" "{\n" " char *s;\n" @@ -1122,8 +1085,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if7() - { + void if7() { check("void f( bool b )\n" "{\n" " int *a=0;\n" @@ -1139,8 +1101,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if8() - { + void if8() { check("static void f(int i)\n" "{\n" " char *c = malloc(50);\n" @@ -1158,8 +1119,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Memory leak: c\n", errout.str()); } - void if9() - { + void if9() { check("static void f()\n" "{\n" " char *buf = NULL, *tmp;\n" @@ -1174,8 +1134,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if10() - { + void if10() { check("static void f()\n" "{\n" " char *buf = malloc(10);\n" @@ -1188,8 +1147,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Common realloc mistake: \'buf\' nulled but not freed upon failure\n", errout.str()); } - void if11() - { + void if11() { check("void foo()\n" "{\n" " int *x = new int[10];\n" @@ -1204,8 +1162,7 @@ private: } - void forwhile5() - { + void forwhile5() { check("void f(const char **a)\n" "{\n" " char *str = 0;\n" @@ -1219,8 +1176,7 @@ private: } - void forwhile6() - { + void forwhile6() { check("void f(const char **a)\n" "{\n" " char *str = 0;\n" @@ -1233,8 +1189,7 @@ private: } - void forwhile8() - { + void forwhile8() { check("char *f()\n" "{\n" " char *a = 0;\n" @@ -1259,8 +1214,7 @@ private: } - void forwhile9() - { + void forwhile9() { check("char *f()\n" "{\n" " char *a = 0;\n" @@ -1280,8 +1234,7 @@ private: } - void forwhile10() - { + void forwhile10() { check("char *f()\n" "{\n" " char *a = 0;\n" @@ -1302,8 +1255,7 @@ private: } - void forwhile11() - { + void forwhile11() { check("int main()\n" "{\n" " FILE *stream=NULL;\n" @@ -1317,8 +1269,7 @@ private: - void switch2() - { + void switch2() { const std::string code("void f()\n" "{\n" " char *str = new char[10];\n" @@ -1335,8 +1286,7 @@ private: ASSERT_EQUALS("[test.cpp:12]: (error) Memory leak: str\n", errout.str()); } - void switch3() - { + void switch3() { check("void f()\n" "{\n" " char *str = new char[10];\n" @@ -1353,8 +1303,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (error) Memory leak: str\n", errout.str()); } - void switch4() - { + void switch4() { check("void f() {\n" " switch MAKEWORD(1)\n" " {\n" @@ -1365,8 +1314,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret5() - { + void ret5() { check("static char * f()\n" "{\n" " char *c = new char[50];\n" @@ -1375,8 +1323,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret6() - { + void ret6() { check("void foo()\n" "{\n" " char *c = new char[50];\n" @@ -1385,8 +1332,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret7() - { + void ret7() { check("void foo()\n" "{\n" " char *c = new char[50];\n" @@ -1395,8 +1341,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret8() - { + void ret8() { check("char *foo()\n" "{\n" " char *c = new char[50];\n" @@ -1406,8 +1351,7 @@ private: } - void mismatch1() - { + void mismatch1() { check("void f()\n" "{\n" " int *a = new int[10];\n" @@ -1431,8 +1375,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Mismatching allocation and deallocation: a\n", errout.str()); } - void mismatch2() - { + void mismatch2() { check("void f()\n" "{\n" " FILE *fp;\n" @@ -1446,8 +1389,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void mismatch3() - { + void mismatch3() { check("void f()\n" "{\n" " FILE *fp;\n" @@ -1461,8 +1403,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void mismatch4() - { + void mismatch4() { check("void f()\n" "{\n" " char *p = 0;\n" @@ -1476,8 +1417,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Mismatching allocation and deallocation: p\n", errout.str()); } - void mismatch5() - { + void mismatch5() { check("void f() {\n" " C *c = new C;\n" " delete c;\n" @@ -1487,8 +1427,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void mismatchSize() - { + void mismatchSize() { check("void f(char *buf)\n" "{\n" " int i;\n" @@ -1505,8 +1444,7 @@ private: //////////////////////////////////////////////// - void func3() - { + void func3() { check("static void foo(const char *str)\n" "{ }\n" "\n" @@ -1519,8 +1457,7 @@ private: } - void func4() - { + void func4() { check("static void foo(char *str)\n" "{\n" " delete [] str;\n" @@ -1535,8 +1472,7 @@ private: } - void func5() - { + void func5() { check("static void foo(char *str)\n" "{\n" " delete str;\n" @@ -1552,8 +1488,7 @@ private: } - void func6() - { + void func6() { check("static void foo(char *str)\n" "{\n" " goto abc;\n" @@ -1568,8 +1503,7 @@ private: } - void func7() - { + void func7() { check("static void foo(char *str)\n" "{\n" " if (abc)\n" @@ -1587,8 +1521,7 @@ private: } - void func9() - { + void func9() { check("int b()\n" "{\n" " return 0;\n" @@ -1604,8 +1537,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func10() - { + void func10() { check("static void f(void (*fnc)(char*))\n" "{\n" " char *c = malloc(50);\n" @@ -1614,8 +1546,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func11() - { + void func11() { check("static void f(struct1 *s1)\n" "{\n" " char *c = malloc(50);\n" @@ -1624,8 +1555,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func12() - { + void func12() { check("void add_list(struct mmtimer *n)\n" "{\n" " rb_link_node(&n->list, parent, link);\n" @@ -1644,8 +1574,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func13() - { + void func13() { check("static void f()\n" "{\n" " char *p = malloc(100);\n" @@ -1654,8 +1583,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func14() - { + void func14() { // It is not known what the "foo" that only takes one parameter does.. check("static void foo(char *a, char *b)\n" "{\n" @@ -1671,8 +1599,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func15() - { + void func15() { check("static void a()\n" "{ return true; }\n" "\n" @@ -1685,8 +1612,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Memory leak: p\n", errout.str()); } - void func16() - { + void func16() { check("static void a( bo_t *p_bo)\n" "{\n" " p_bo->buffer = realloc( p_bo->buffer, 100 );\n" @@ -1706,8 +1632,7 @@ private: } - void func17() - { + void func17() { // The "bar" function must be reduced to "use" check("bool bar(char **parent, char *res, bool a)\n" @@ -1732,8 +1657,7 @@ private: } - void func18() - { + void func18() { // No false positive // The "free_pointers" will deallocate all pointers check("static void free_pointers(int arg_count, ...)\n" @@ -1760,8 +1684,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func19() - { + void func19() { // Ticket #2056 check("bool a(int *p) {\n" " return p;\n" @@ -1775,8 +1698,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func20() - { + void func20() { // Ticket #2182 - false positive when there is unused class. // If the unused class is removed the false positive goes away. // [test.cpp:12]: (error) Deallocating a deallocated pointer: p @@ -1813,8 +1735,7 @@ private: } //# Ticket 2569 - void func21() - { + void func21() { // checking for lstat function: // ---------------------------- check("void foo ()\n" @@ -2107,8 +2028,7 @@ private: } // # 2668 - void func22() - { + void func22() { check("void foo()\n" "{\n" " char * cpFile;\n" @@ -2154,8 +2074,7 @@ private: } // # 2667 - void func23() - { + void func23() { // check open() function // ---------------------- @@ -2250,8 +2169,7 @@ private: } // #2705 - void func24() - { + void func24() { check("void f(void) \n" "{\n" " std::string *x = new std::string;\n" @@ -2266,8 +2184,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void func25() // ticket #2904 - { + void func25() { // ticket #2904 check("class Fred { };\n" "void f(void) \n" "{\n" @@ -2299,8 +2216,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: f\n", errout.str()); } - void allocfunc1() - { + void allocfunc1() { check("static char *a()\n" "{\n" " return new char[100];\n" @@ -2332,8 +2248,7 @@ private: ASSERT_EQUALS(std::string("[test.cpp:8]: (error) Memory leak: p\n"), errout.str()); } - void allocfunc2() - { + void allocfunc2() { check("static char *a(int size)\n" "{\n" " return new char[size];\n" @@ -2373,8 +2288,7 @@ private: ASSERT_EQUALS(std::string(""), errout.str()); } - void allocfunc3() - { + void allocfunc3() { check("static char *a()\n" "{\n" " char *data = malloc(10);;" @@ -2387,8 +2301,7 @@ private: ASSERT_EQUALS(std::string("[test.cpp:8]: (error) Memory leak: p\n"), errout.str()); } - void allocfunc4() - { + void allocfunc4() { check("char* foo()\n" "{\n" " char *str = NULL;\n" @@ -2417,8 +2330,7 @@ private: ASSERT_EQUALS(std::string("[test.cpp:11]: (error) Mismatching allocation and deallocation: p\n"), errout.str()); } - void allocfunc5() - { + void allocfunc5() { check("void foo(char **str)\n" "{\n" " *str = malloc(20);\n" @@ -2506,8 +2418,7 @@ private: } - void allocfunc6() - { + void allocfunc6() { check("static FILE* data()\n" "{\n" " return fopen(\"data.txt\",\"rt\");\n" @@ -2527,8 +2438,7 @@ private: } - void allocfunc7() - { + void allocfunc7() { // Ticket #2374 - no false positive check("char *data()\n" "{\n" @@ -2544,8 +2454,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void allocfunc8() - { + void allocfunc8() { // Ticket #2213 - calling alloc function twice check("FILE *foo() {\n" " return fopen(a,b);\n" @@ -2559,8 +2468,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Resource leak: f\n", errout.str()); } - void allocfunc9() - { + void allocfunc9() { // Ticket #2673 - address is taken in alloc func check("char *addstring(const char *s) {\n" " char *ret = strdup(s);\n" @@ -2574,8 +2482,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void allocfunc10() - { + void allocfunc10() { // Ticket #2921 - static pointer check("char *getstr() {\n" " static char *ret = malloc(100);\n" @@ -2588,8 +2495,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void throw1() - { + void throw1() { check("void foo()\n" "{\n" " char *str = new char[10];\n" @@ -2601,8 +2507,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: str\n", errout.str()); } - void throw2() - { + void throw2() { check("void foo()\n" "{\n" " char *str = 0;\n" @@ -2625,8 +2530,7 @@ private: - void linux_list_1() - { + void linux_list_1() { check("struct AB\n" "{\n" " int a;\n" @@ -2643,8 +2547,7 @@ private: - void sizeof1() - { + void sizeof1() { check("void f()\n" "{\n" " struct s_t s1;\n" @@ -2667,8 +2570,7 @@ private: } - void realloc1() - { + void realloc1() { check("void foo()\n" "{\n" " char *a = (char *)malloc(10);\n" @@ -2678,8 +2580,7 @@ private: "[test.cpp:5]: (error) Memory leak: a\n", errout.str()); } - void realloc2() - { + void realloc2() { check("void foo()\n" "{\n" " char *a = (char *)malloc(10);\n" @@ -2690,8 +2591,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout.str()); } - void realloc3() - { + void realloc3() { check("void foo()\n" "{\n" " char *a = 0;\n" @@ -2703,8 +2603,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc4() - { + void realloc4() { check("void foo()\n" "{\n" " static char *a = 0;\n" @@ -2719,8 +2618,7 @@ private: errout.str()); } - void realloc5() - { + void realloc5() { check("void foo()\n" "{\n" " char *buf;\n" @@ -2735,14 +2633,12 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc6() - { + void realloc6() { ASSERT_EQUALS(";;realloc;;", getcode("char *buf; buf=realloc(buf,100);", "buf")); ASSERT_EQUALS(";;alloc;", getcode("char *buf; buf=realloc(0,100);", "buf")); } - void realloc7() - { + void realloc7() { check("bool foo(size_t nLen, char* pData)\n" "{\n" " pData = (char*) realloc(pData, sizeof(char) + (nLen + 1)*sizeof(char));\n" @@ -2756,8 +2652,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc8() - { + void realloc8() { check("void foo()\n" "{\n" " char *origBuf = m_buf;\n" @@ -2769,8 +2664,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc9() - { + void realloc9() { check("void foo()\n" "{\n" " x = realloc(x,100);\n" @@ -2778,8 +2672,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc10() - { + void realloc10() { check("void foo() {\n" " char *pa, *pb;\n" " pa = pb = malloc(10);\n" @@ -2789,8 +2682,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc11() - { + void realloc11() { check("void foo() {\n" " char *p;\n" " p = realloc(p, size);\n" @@ -2801,8 +2693,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc12() - { + void realloc12() { check("void foo(int x)\n" "{\n" " char *a = 0;\n" @@ -2813,8 +2704,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void realloc13() - { + void realloc13() { check("void foo()\n" "{\n" " char **str;\n" @@ -2824,8 +2714,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'str\' nulled but not freed upon failure\n", errout.str()); } - void realloc14() - { + void realloc14() { check("void foo() {\n" " char *p;\n" " p = realloc(p, size + 1);\n" @@ -2836,8 +2725,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign1() - { + void assign1() { check("void foo()\n" "{\n" " char *a = (char *)malloc(10);\n" @@ -2892,8 +2780,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign2() - { + void assign2() { // #2806 - FP when there is redundant assignment check("void foo() {\n" " gchar *bar;\n" @@ -2904,8 +2791,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varid() - { + void varid() { check("void foo()\n" "{\n" " char *p = malloc(100);\n" @@ -2918,8 +2804,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void cast1() - { + void cast1() { check("void foo()\n" "{\n" " char *a = reinterpret_cast(malloc(10));\n" @@ -2930,8 +2815,7 @@ private: - void dealloc_use() - { + void dealloc_use() { // It is ok to take the address.. check("void f()\n" "{\n" @@ -3008,8 +2892,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void dealloc_use_2() - { + void dealloc_use_2() { // #3041 - assigning pointer when it's used check("void f(char *s) {\n" " free(s);\n" @@ -3018,8 +2901,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void dealloc_use_3() - { + void dealloc_use_3() { check("void foo()\n" "{\n" " char *str = malloc(10);\n" @@ -3037,8 +2919,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Dereferencing 'str' after it is deallocated / released\n", errout.str()); } - void freefree1() - { + void freefree1() { check("void foo()\n" "{\n" " char *str = malloc(100);\n" @@ -3048,8 +2929,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Deallocating a deallocated pointer: str\n", errout.str()); } - void freefree2() - { + void freefree2() { check("void foo()\n" "{\n" " FILE *fd = fopen(\"test.txt\", \"wb\");\n" @@ -3059,8 +2939,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void strcpy_result_assignment() - { + void strcpy_result_assignment() { check("void foo()\n" "{\n" " char *p1 = malloc(10);\n" @@ -3069,8 +2948,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void strcat_result_assignment() - { + void strcat_result_assignment() { check("void foo()\n" "{\n" " char *p = malloc(10);\n" @@ -3084,8 +2962,7 @@ private: - void all1() - { + void all1() { check("void foo()\n" "{\n" " Fred *f = new Fred;\n" @@ -3095,8 +2972,7 @@ private: - void malloc_constant_1() - { + void malloc_constant_1() { check("void foo()\n" "{\n" " int *p = malloc(3);\n" @@ -3107,8 +2983,7 @@ private: - void unknownFunction1() - { + void unknownFunction1() { check("void foo()\n" "{\n" " int *p = new int[100];\n" @@ -3122,8 +2997,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void unknownFunction2() - { + void unknownFunction2() { check("void foo()\n" "{\n" " int *p = new int[100];\n" @@ -3144,8 +3018,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: p\n", errout.str()); } - void unknownFunction4() - { + void unknownFunction4() { check("void foo()\n" "{\n" " int *p = new int[100];\n" @@ -3156,8 +3029,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: p\n", errout.str()); } - void unknownFunction5() - { + void unknownFunction5() { check("static void foo()\n" "{\n" " char *p = NULL;\n" @@ -3175,8 +3047,7 @@ private: } - void checkvcl(const char code[]) - { + void checkvcl(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -3196,8 +3067,7 @@ private: } - void class1() - { + void class1() { check("class Fred\n" "{\n" "public:\n" @@ -3209,8 +3079,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Memory leak: p\n", errout.str()); } - void class2() - { + void class2() { check("class Fred {\n" "public:\n" " Fred() : rootNode(0) {}\n" @@ -3241,8 +3110,7 @@ private: } - void autoptr1() - { + void autoptr1() { check("std::auto_ptr foo()\n" "{\n" " int *i = new int;\n" @@ -3251,8 +3119,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if_with_and() - { + void if_with_and() { check("void f()\n" "{\n" " char *a = new char[10];\n" @@ -3274,8 +3141,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign_pclose() - { + void assign_pclose() { check("void f()\n" "{\n" " FILE *f = popen (\"test\", \"w\");\n" @@ -3284,8 +3150,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void exit2() - { + void exit2() { check("void f()\n" "{\n" " char *out = new char[100];\n" @@ -3302,8 +3167,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void exit4() - { + void exit4() { check("void f()\n" "{\n" " char *p = malloc(100);\n" @@ -3315,8 +3179,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) Memory leak: p\n", errout.str()); } - void exit5() - { + void exit5() { check("void f()\n" "{\n" " char *p = malloc(100);\n" @@ -3329,8 +3192,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void exit6() - { + void exit6() { check("int main(int argc, char *argv[]) {\n" " FILE *sfile;\n" " unsigned long line;\n" @@ -3348,8 +3210,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void exit7() - { + void exit7() { check("int a(int x) {\n" " if (x == 0) {\n" " exit(0);\n" @@ -3364,8 +3225,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Memory leak: p\n", errout.str()); } - void noreturn() - { + void noreturn() { check("void fatal_error()\n" "{ exit(1); }\n" "\n" @@ -3389,8 +3249,7 @@ private: - void stdstring() - { + void stdstring() { check("void f(std::string foo)\n" "{\n" " char *out = new char[11];\n" @@ -3400,8 +3259,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: out\n", errout.str()); } - void strndup_function() - { + void strndup_function() { check("void f()\n" "{\n" " char *out = strndup(\"text\", 3);\n" @@ -3409,8 +3267,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: out\n", errout.str()); } - void tmpfile_function() - { + void tmpfile_function() { check("void f()\n" "{\n" " FILE *f = tmpfile();\n" @@ -3448,8 +3305,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void fcloseall_function() - { + void fcloseall_function() { check("void f()\n" "{\n" " FILE *f = fopen(fname, str);\n" @@ -3465,8 +3321,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void open_function() - { + void open_function() { check("void f(const char *path)\n" "{\n" " int fd = open(path, O_RDONLY);\n" @@ -3501,8 +3356,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void open_fdopen() - { + void open_fdopen() { // Ticket #2830 check("void f(const char *path)\n" "{\n" @@ -3513,8 +3367,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void creat_function() - { + void creat_function() { check("void f(const char *path)\n" "{\n" " int fd = creat(path, S_IRWXU);\n" @@ -3522,8 +3375,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Resource leak: fd\n", errout.str()); } - void close_function() - { + void close_function() { check("void f(const char *path)\n" "{\n" " int fd = open(path, O_RDONLY);\n" @@ -3583,8 +3435,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Resource leak: handle\n", errout.str()); } - void fd_functions() - { + void fd_functions() { check("void f(const char *path)\n" "{\n" " int fd = open(path, O_RDONLY);\n" @@ -3612,8 +3463,7 @@ private: ASSERT_EQUALS("[test.cpp:24]: (error) Resource leak: fd\n", errout.str()); } - void opendir_function() - { + void opendir_function() { check("void f()\n" "{\n" " DIR *f = opendir(\".\");\n" @@ -3621,8 +3471,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Resource leak: f\n", errout.str()); } - void fdopendir_function() - { + void fdopendir_function() { check("void f(int fd)\n" "{\n" " DIR *f = fdopendir(fd);\n" @@ -3630,8 +3479,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Resource leak: f\n", errout.str()); } - void closedir_function() - { + void closedir_function() { check("void f()\n" "{\n" " DIR *f = opendir(\".\");\n" @@ -3654,8 +3502,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void dir_functions() - { + void dir_functions() { check("void f()\n" "{\n" " DIR *f = opendir(dir);\n" @@ -3669,8 +3516,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (error) Resource leak: f\n", errout.str()); } - void file_functions() - { + void file_functions() { check("void f()\n" "{\n" "FILE *f = fopen(fname, str);\n" @@ -3696,8 +3542,7 @@ private: ASSERT_EQUALS("[test.cpp:22]: (error) Resource leak: f\n", errout.str()); } - void getc_function() - { + void getc_function() { { check("void f()\n" "{" @@ -3720,8 +3565,7 @@ private: } } - void pointer_to_pointer() - { + void pointer_to_pointer() { check("void f(char **data)\n" "{\n" " char *c = new char[12];\n" @@ -3731,8 +3575,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void dealloc_and_alloc_in_func() - { + void dealloc_and_alloc_in_func() { check("char *f( const char *x )\n" "{\n" " delete [] x;\n" @@ -3751,8 +3594,7 @@ private: } - void unknownSyntax1() - { + void unknownSyntax1() { // I don't know what this syntax means so cppcheck should bail out check("void foo()\n" "{\n" @@ -3769,8 +3611,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void knownFunctions() - { + void knownFunctions() { check("void foo()\n" "{\n" " int *p = new int[100];\n" @@ -3779,8 +3620,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: p\n", errout.str()); } - void same_function_name() - { + void same_function_name() { check("void a(char *p)\n" "{ }\n" "void b()\n" @@ -3791,8 +3631,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void functionParameter() - { + void functionParameter() { check("void a(char *p)\n" "{\n" " p = malloc(100);\n" @@ -3801,8 +3640,7 @@ private: } // Ticket #2014 - setjmp / longjmp - void jmp() - { + void jmp() { check("int main()\n" "{\n" " jmp_buf env;\n" @@ -3824,8 +3662,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void trac1949() - { + void trac1949() { check("\n" "\n" "int fn()\n" @@ -3841,8 +3678,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (error) Memory leak: buff\n", errout.str()); } - void trac2662() - { + void trac2662() { // segfault because of endless recursion // call_func -> getAllocationType -> functionReturnType -> call_func .. @@ -3879,8 +3715,7 @@ private: } //ticket # 3083 - void redundantCodeAfterReturnGoto() - { + void redundantCodeAfterReturnGoto() { check("void foo()\n" "{\n" " char * data;\n" @@ -3912,8 +3747,7 @@ static TestMemleakInFunction testMemleakInFunction; -class TestMemleakInClass : public TestFixture -{ +class TestMemleakInClass : public TestFixture { public: TestMemleakInClass() : TestFixture("TestMemleakInClass") { } @@ -3923,8 +3757,7 @@ private: * Tokenize and execute leak check for given code * @param code Source code */ - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -3945,8 +3778,7 @@ private: checkMemoryLeak.check(); } - void run() - { + void run() { TEST_CASE(class1); TEST_CASE(class2); TEST_CASE(class3); @@ -3981,8 +3813,7 @@ private: } - void class1() - { + void class1() { check("class Fred\n" "{\n" "private:\n" @@ -4024,8 +3855,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: Fred::str1\n", errout.str()); } - void class2() - { + void class2() { check("class Fred\n" "{\n" "private:\n" @@ -4063,8 +3893,7 @@ private: ASSERT_EQUALS("[test.cpp:12]: (error) Mismatching allocation and deallocation: Fred::str1\n", errout.str()); } - void class3() - { + void class3() { check("class Token;\n" "\n" "class Tokenizer\n" @@ -4130,8 +3959,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class4() - { + void class4() { check("struct ABC;\n" "class Fred\n" "{\n" @@ -4171,8 +3999,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class6() - { + void class6() { check("class Fred\n" "{\n" "public:\n" @@ -4200,8 +4027,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class7() - { + void class7() { check("class Fred\n" "{\n" "public:\n" @@ -4236,8 +4062,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class8() - { + void class8() { check("class A\n" "{\n" "public:\n" @@ -4267,8 +4092,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class9() - { + void class9() { check("class A\n" "{\n" "public:\n" @@ -4296,8 +4120,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class10() - { + void class10() { check("class A\n" "{\n" "public:\n" @@ -4317,8 +4140,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: A::p\n", errout.str()); } - void class11() - { + void class11() { check("class A\n" "{\n" "public:\n" @@ -4339,8 +4161,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: A::p\n", errout.str()); } - void class12() - { + void class12() { check("class A\n" "{\n" "private:\n" @@ -4376,8 +4197,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: A::p\n", errout.str()); } - void class13() - { + void class13() { check("class A\n" "{\n" "private:\n" @@ -4413,8 +4233,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n", errout.str()); } - void class14() - { + void class14() { check("class A\n" "{\n" " int *p;\n" @@ -4484,8 +4303,7 @@ private: "[test.cpp:3]: (error) Memory leak: A::p\n", errout.str()); } - void class15() - { + void class15() { check("class A\n" "{\n" " int *p;\n" @@ -4552,8 +4370,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class16() - { + void class16() { // Ticket #1510 check("class A\n" "{\n" @@ -4566,8 +4383,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class17() - { + void class17() { // Ticket #1557 check("class A {\n" "private:\n" @@ -4610,8 +4426,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 'pd' is not deallocated before it is allocated.\n", errout.str()); } - void class18() - { + void class18() { // Ticket #853 check("class A : public x\n" "{\n" @@ -4641,8 +4456,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class19() - { + void class19() { // Ticket #2219 check("class Foo\n" "{\n" @@ -4699,8 +4513,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void class20() - { + void class20() { check("namespace ns1 {\n" " class Fred\n" " {\n" @@ -4821,8 +4634,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Memory leak: Fred::str1\n", errout.str()); } - void class21() // ticket #2517 - { + void class21() { // ticket #2517 check("struct B { };\n" "struct C\n" "{\n" @@ -4860,8 +4672,7 @@ private: "[test.cpp:10]: (error) Memory leak: A::c\n", errout.str()); } - void class22() // ticket #3012 - false positive - { + void class22() { // ticket #3012 - false positive check("class Fred {\n" "private:\n" " int * a;\n" @@ -4872,8 +4683,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void staticvar() - { + void staticvar() { check("class A\n" "{\n" "private:\n" @@ -4889,8 +4699,7 @@ private: } - void free_member_in_sub_func() - { + void free_member_in_sub_func() { // Member function check("class Tokenizer\n" "{\n" @@ -4948,8 +4757,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void mismatch1() - { + void mismatch1() { check("class A\n" "{\n" "public:\n" @@ -4974,8 +4782,7 @@ private: ASSERT_EQUALS("[test.cpp:14]: (error) Mismatching allocation and deallocation: A::pkt_buffer\n", errout.str()); } - void func1() - { + void func1() { check("class Fred\n" "{\n" "private:\n" @@ -5001,8 +4808,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (warning) Possible leak in public function. The pointer 's' is not deallocated before it is allocated.\n", errout.str()); } - void func2() - { + void func2() { check("class Fred\n" "{\n" "private:\n" @@ -5025,15 +4831,13 @@ static TestMemleakInClass testMemleakInClass; -class TestMemleakStructMember : public TestFixture -{ +class TestMemleakStructMember : public TestFixture { public: TestMemleakStructMember() : TestFixture("TestMemleakStructMember") { } private: - void check(const char code[], const char fname[] = 0) - { + void check(const char code[], const char fname[] = 0) { // Clear the error buffer.. errout.str(""); @@ -5050,8 +4854,7 @@ private: checkMemoryLeakStructMember.check(); } - void run() - { + void run() { // testing that errors are detected TEST_CASE(err); @@ -5085,8 +4888,7 @@ private: TEST_CASE(localvar); } - void err() - { + void err() { check("static void foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5128,8 +4930,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (error) Memory leak: abc.a\n", errout.str()); } - void goto_() - { + void goto_() { check("static void foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5145,8 +4946,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret1() - { + void ret1() { check("static ABC * foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5162,8 +4962,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ret2() - { + void ret2() { check("static ABC * foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5173,8 +4972,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign1() - { + void assign1() { check("static void foo()\n" "{\n" " struct ABC *abc = abc1;\n" @@ -5202,8 +5000,7 @@ private: } - void assign2() - { + void assign2() { check("static void foo() {\n" " struct ABC *abc = malloc(123);\n" " abc->a = abc->b = malloc(10);\n" @@ -5211,8 +5008,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assign3() - { + void assign3() { check("void f(struct s *f1) {\n" " struct s f2;\n" " f2.a = malloc(100);\n" @@ -5221,8 +5017,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void failedAllocation() - { + void failedAllocation() { check("static struct ABC * foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5237,8 +5032,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void function1() - { + void function1() { // Not found function => assume that the function may deallocate check("static void foo()\n" "{\n" @@ -5258,8 +5052,7 @@ private: } // #2848: Taking address in function 'assign' - void function2() - { + void function2() { check("void f() {\n" " A a = { 0 };\n" " a.foo = (char *) malloc(10);\n" @@ -5269,8 +5062,7 @@ private: } // #3024: kernel list - void function3() - { + void function3() { check("void f() {\n" " struct ABC *abc = kmalloc(100);\n" " abc.a = (char *) kmalloc(10);\n" @@ -5280,8 +5072,7 @@ private: } // #3038: deallocating in function - void function4() - { + void function4() { check("void a(char *p) { char *x = p; free(x); }\n" "void b() {\n" " struct ABC abc;\n" @@ -5291,8 +5082,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void ifelse() - { + void ifelse() { check("static void foo()\n" "{\n" " struct ABC *abc = malloc(sizeof(struct ABC));\n" @@ -5311,8 +5101,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void globalvar() - { + void globalvar() { check("struct ABC *abc;\n" "\n" "static void foo()\n" @@ -5324,8 +5113,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar() - { + void localvar() { const char code[] = "void foo() {\n" " struct ABC abc;\n" " abc.a = malloc(10);\n" @@ -5345,15 +5133,13 @@ static TestMemleakStructMember testMemleakStructMember; -class TestMemleakNoVar : public TestFixture -{ +class TestMemleakNoVar : public TestFixture { public: TestMemleakNoVar() : TestFixture("TestMemleakNoVar") { } private: - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -5370,14 +5156,12 @@ private: checkMemoryLeakNoVar.check(); } - void run() - { + void run() { // pass allocated memory to function.. TEST_CASE(functionParameter); } - void functionParameter() - { + void functionParameter() { // standard function.. check("void x() {\n" " strcpy(a, strdup(p));\n" diff --git a/test/testnonreentrantfunctions.cpp b/test/testnonreentrantfunctions.cpp index 5dbcc7016..e86f95c31 100644 --- a/test/testnonreentrantfunctions.cpp +++ b/test/testnonreentrantfunctions.cpp @@ -25,21 +25,18 @@ extern std::ostringstream errout; -class TestNonReentrantFunctions : public TestFixture -{ +class TestNonReentrantFunctions : public TestFixture { public: TestNonReentrantFunctions() : TestFixture("TestNonReentrantFunctions") { } private: - void run() - { + void run() { TEST_CASE(test_crypt); } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -64,8 +61,7 @@ private: checkNonReentrantFunctions.nonReentrantFunctions(); } - void test_crypt() - { + void test_crypt() { check("void f(char *pwd)\n" "{\n" " char *cpwd;" diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index 54b02c5aa..f5fda9642 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -23,8 +23,7 @@ extern std::ostringstream errout; -class TestNullPointer : public TestFixture -{ +class TestNullPointer : public TestFixture { public: TestNullPointer() : TestFixture("TestNullPointer") { } @@ -32,8 +31,7 @@ public: private: - void run() - { + void run() { TEST_CASE(nullpointerAfterLoop); TEST_CASE(nullpointer1); TEST_CASE(nullpointer2); @@ -56,8 +54,7 @@ private: TEST_CASE(scanf_with_invalid_va_argument); } - void check(const char code[], bool inconclusive = false) - { + void check(const char code[], bool inconclusive = false) { // Clear the error buffer.. errout.str(""); @@ -79,8 +76,7 @@ private: } - void nullpointerAfterLoop() - { + void nullpointerAfterLoop() { check("int foo(const Token *tok)\n" "{\n" " while (tok);\n" @@ -172,8 +168,7 @@ private: } } - void nullpointer1() - { + void nullpointer1() { // ticket #1923 - no false positive when using else if check("void f(A *a)\n" "{\n" @@ -206,8 +201,7 @@ private: } - void nullpointer2() - { + void nullpointer2() { // Null pointer dereference can only happen with pointers check("void foo()\n" "{\n" @@ -221,8 +215,7 @@ private: // Dereferencing a struct and then checking if it is null // This is checked by this function: // CheckOther::nullPointerStructByDeRefAndChec - void structDerefAndCheck() - { + void structDerefAndCheck() { // errors.. check("void foo(struct ABC *abc)\n" "{\n" @@ -418,8 +411,7 @@ private: } // Dereferencing a pointer and then checking if it is null - void pointerDerefAndCheck() - { + void pointerDerefAndCheck() { // errors.. check("void foo(int *p)\n" "{\n" @@ -673,8 +665,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void nullpointer5() - { + void nullpointer5() { // errors.. check("void foo(A &a)\n" "{\n" @@ -686,8 +677,7 @@ private: } // Execution paths.. - void nullpointerExecutionPaths() - { + void nullpointerExecutionPaths() { // errors.. check("static void foo()\n" "{\n" @@ -910,8 +900,7 @@ private: } // Ticket #2350 - void nullpointerExecutionPathsLoop() - { + void nullpointerExecutionPathsLoop() { // No false positive: check("void foo() {\n" " int n;\n" @@ -959,8 +948,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (error) Possible null pointer dereference: p\n", errout.str()); } - void nullpointer7() - { + void nullpointer7() { check("void foo()\n" "{\n" " wxLongLong x = 0;\n" @@ -969,8 +957,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void nullpointer8() - { + void nullpointer8() { check("void foo()\n" "{\n" " const char * x = 0;\n" @@ -985,8 +972,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Possible null pointer dereference: x\n", errout.str()); } - void nullpointer9() //#ticket 1778 - { + void nullpointer9() { //#ticket 1778 check("void foo()\n" "{\n" " std::string * x = 0;\n" @@ -995,8 +981,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference\n", errout.str()); } - void nullpointer10() - { + void nullpointer10() { check("void foo()\n" "{\n" " struct my_type* p = 0;\n" @@ -1013,8 +998,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Possible null pointer dereference: p\n", errout.str()); } - void nullpointer11() // ticket #2812 - { + void nullpointer11() { // ticket #2812 check("int foo()\n" "{\n" " my_type* p = 0;\n" @@ -1047,8 +1031,7 @@ private: } // Check if pointer is null and the dereference it - void pointerCheckAndDeRef() - { + void pointerCheckAndDeRef() { check("void foo(char *p) {\n" " if (!p) {\n" " }\n" @@ -1310,8 +1293,7 @@ private: } // Test CheckNullPointer::nullConstantDereference - void nullConstantDereference() - { + void nullConstantDereference() { // Ticket #2090 check("void foo() {\n" " char *p = 0;\n" @@ -1332,8 +1314,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void gcc_statement_expression() - { + void gcc_statement_expression() { // Ticket #2621 check("void f(struct ABC *abc) {\n" " ({ if (abc) dbg(); })\n" @@ -1341,8 +1322,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf_with_zero_size() - { + void snprintf_with_zero_size() { // Ticket #2840 check("void f() {\n" " int bytes = snprintf(0, 0, \"%u\", 1);\n" @@ -1350,8 +1330,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void snprintf_with_non_zero_size() - { + void snprintf_with_non_zero_size() { // Ticket #2840 check("void f() {\n" " int bytes = snprintf(0, 10, \"%u\", 1);\n" @@ -1359,8 +1338,7 @@ private: ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout.str()); } - void printf_with_invalid_va_argument() - { + void printf_with_invalid_va_argument() { check("void f() {\n" " printf(\"%s\", 0);\n" "}"); @@ -1413,8 +1391,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void scanf_with_invalid_va_argument() - { + void scanf_with_invalid_va_argument() { check("void f(char* s) {\n" " sscanf(s, \"%s\", 0);\n" "}"); diff --git a/test/testobsoletefunctions.cpp b/test/testobsoletefunctions.cpp index 526306179..30763a4e2 100644 --- a/test/testobsoletefunctions.cpp +++ b/test/testobsoletefunctions.cpp @@ -25,16 +25,14 @@ extern std::ostringstream errout; -class TestObsoleteFunctions : public TestFixture -{ +class TestObsoleteFunctions : public TestFixture { public: TestObsoleteFunctions() : TestFixture("TestObsoleteFunctions") { } private: - void run() - { + void run() { TEST_CASE(testbsd_signal); TEST_CASE(testgethostbyname); TEST_CASE(testgethostbyaddr); @@ -65,8 +63,7 @@ private: } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -92,8 +89,7 @@ private: checkObsoleteFunctions.obsoleteFunctions(); } - void testbsd_signal() - { + void testbsd_signal() { check("void f()\n" "{\n" " bsd_signal(SIGABRT, SIG_IGN);\n" @@ -109,8 +105,7 @@ private: } - void testgethostbyname() - { + void testgethostbyname() { check("void f()\n" "{\n" " struct hostent *hp;\n" @@ -121,8 +116,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Found obsolete function 'gethostbyname'. It is recommended that new applications use the 'getaddrinfo' function\n", errout.str()); } - void testgethostbyaddr() - { + void testgethostbyaddr() { check("void f()\n" "{\n" " long addr;\n" @@ -134,8 +128,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) Found obsolete function 'gethostbyaddr'. It is recommended that new applications use the 'getnameinfo' function\n", errout.str()); } - void testusleep() - { + void testusleep() { check("void f()\n" "{\n" " usleep( 1000 );\n" @@ -143,8 +136,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Found obsolete function 'usleep'. It is recommended that new applications use the 'nanosleep' or 'setitimer' function\n", errout.str()); } - void testindex() - { + void testindex() { check("namespace n1 {\n" " int index(){};\n" @@ -185,16 +177,14 @@ private: errout.str()); } - void test_qt_index() - { + void test_qt_index() { check("void TDataModel::forceRowRefresh(int row) {\n" " emit dataChanged(index(row, 0), index(row, columnCount() - 1));\n" "}\n"); ASSERT_EQUALS("[test.cpp:2]: (style) Found obsolete function 'index'. It is recommended to use the function 'strchr' instead\n", errout.str()); } - void testrindex() - { + void testrindex() { check("void f()\n" "{\n" " int rindex( 0 );\n" @@ -210,8 +200,7 @@ private: } - void testvar() - { + void testvar() { check("class Fred {\n" "public:\n" " Fred() : index(0) { }\n" @@ -220,8 +209,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testgets() - { + void testgets() { check("void f()\n" "{\n" " char *x = gets();\n" @@ -229,8 +217,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Found obsolete function 'gets'. It is recommended to use the function 'fgets' instead\n", errout.str()); } - void testalloca() - { + void testalloca() { check("void f()\n" "{\n" " char *x = alloca(10);\n" @@ -239,8 +226,7 @@ private: } // ticket #3121 - void test_declared_function() - { + void test_declared_function() { check("ftime ( int a )\n" "{\n" " return a;\n" @@ -254,8 +240,7 @@ private: } // test std::gets - void test_std_gets() - { + void test_std_gets() { check("void f(char * str)\n" "{\n" " char *x = std::gets(str);\n" @@ -264,8 +249,7 @@ private: } // multiple use - void test_multiple() - { + void test_multiple() { check("void f(char * str)\n" "{\n" " char *x = std::gets(str);\n" @@ -274,8 +258,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Found obsolete function 'gets'. It is recommended to use the function 'fgets' instead\n[test.cpp:4]: (style) Found obsolete function 'usleep'. It is recommended that new applications use the 'nanosleep' or 'setitimer' function\n", errout.str()); } - void test_c_declaration() - { + void test_c_declaration() { check("char * gets ( char * c ) ;\n" "int main ()\n" "{\n" diff --git a/test/testoptions.cpp b/test/testoptions.cpp index 9d8f18d40..6cdedff4b 100644 --- a/test/testoptions.cpp +++ b/test/testoptions.cpp @@ -20,18 +20,15 @@ extern std::ostringstream errout; -class TestOptions: public TestFixture -{ +class TestOptions: public TestFixture { public: TestOptions() - :TestFixture("TestOptions") - { + :TestFixture("TestOptions") { } private: - void run() - { + void run() { TEST_CASE(which_test); TEST_CASE(which_test_method); TEST_CASE(no_test_method); @@ -43,64 +40,56 @@ private: } - void which_test() - { + void which_test() { const char* argv[] = {"./test_runner", "TestClass"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS("TestClass", args.which_test()); } - void which_test_method() - { + void which_test_method() { const char* argv[] = {"./test_runner", "TestClass::TestMethod"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS("TestClass::TestMethod", args.which_test()); } - void no_test_method() - { + void no_test_method() { const char* argv[] = {"./test_runner"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS("", args.which_test()); } - void not_quiet() - { + void not_quiet() { const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-v"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS(false, args.quiet()); } - void quiet() - { + void quiet() { const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-q"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS(true, args.quiet()); } - void gcc_errors() - { + void gcc_errors() { const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-g"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS(true, args.gcc_style_errors()); } - void multiple_testcases() - { + void multiple_testcases() { const char* argv[] = {"./test_runner", "TestClass::TestMethod", "Ignore::ThisOne"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS("TestClass::TestMethod", args.which_test()); } - void invalid_switches() - { + void invalid_switches() { const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-a", "-v", "-q", "-g"}; options args(sizeof argv / sizeof argv[0], argv); ASSERT_EQUALS("TestClass::TestMethod", args.which_test()); diff --git a/test/testother.cpp b/test/testother.cpp index cf00c3061..24d3c75a8 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -24,8 +24,7 @@ extern std::ostringstream errout; -class TestOther : public TestFixture -{ +class TestOther : public TestFixture { public: TestOther() : TestFixture("TestOther") { } @@ -33,8 +32,7 @@ public: private: - void run() - { + void run() { TEST_CASE(assignBoolToPointer); TEST_CASE(zeroDiv1); @@ -145,8 +143,7 @@ private: TEST_CASE(checkForSuspiciousSemicolon2); } - void check(const char code[], const char *filename = NULL) - { + void check(const char code[], const char *filename = NULL) { // Clear the error buffer.. errout.str(""); @@ -195,18 +192,15 @@ private: checkOther.checkAssignBoolToPointer(); } - class SimpleSuppressor: public ErrorLogger - { + class SimpleSuppressor: public ErrorLogger { public: SimpleSuppressor(Settings &settings, ErrorLogger *next) : _settings(settings), _next(next) { } - virtual void reportOut(const std::string &outmsg) - { + virtual void reportOut(const std::string &outmsg) { _next->reportOut(outmsg); } - virtual void reportErr(const ErrorLogger::ErrorMessage &msg) - { + virtual void reportErr(const ErrorLogger::ErrorMessage &msg) { if (!msg._callStack.empty() && !_settings.nomsg.isSuppressed(msg._id, msg._callStack.begin()->getfile(), msg._callStack.begin()->line)) _next->reportErr(msg); } @@ -215,8 +209,7 @@ private: ErrorLogger *_next; }; - void check_preprocess_suppress(const char precode[], const char *filename = NULL) - { + void check_preprocess_suppress(const char precode[], const char *filename = NULL) { // Clear the error buffer.. errout.str(""); @@ -252,8 +245,7 @@ private: } - void assignBoolToPointer() - { + void assignBoolToPointer() { check("void foo(bool *p) {\n" " p = false;\n" "}"); @@ -261,8 +253,7 @@ private: } - void zeroDiv1() - { + void zeroDiv1() { check("void foo()\n" "{\n" " int a = 0;\n" @@ -274,8 +265,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Division by zero\n", errout.str()); } - void zeroDiv2() - { + void zeroDiv2() { check("void foo()\n" "{\n" " int sum = 0;\n" @@ -295,8 +285,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void zeroDiv3() - { + void zeroDiv3() { check("void f()\n" "{\n" " div_t divresult = div (1,0);\n" @@ -304,8 +293,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero\n", errout.str()); } - void zeroDiv4() - { + void zeroDiv4() { check("void f()\n" "{\n" " long a = b / 0x6;\n" @@ -370,8 +358,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void zeroDiv5() - { + void zeroDiv5() { check("void f()\n" "{ { {\n" " long a = b / 0;\n" @@ -379,8 +366,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero\n", errout.str()); } - void zeroDiv6() - { + void zeroDiv6() { check("void f()\n" "{ { {\n" " int a = b % 0;\n" @@ -389,8 +375,7 @@ private: } - void sprintfUsage(const char code[]) - { + void sprintfUsage(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -409,8 +394,7 @@ private: checkOther.invalidFunctionUsage(); } - void sprintf1() - { + void sprintf1() { sprintfUsage("void foo()\n" "{\n" " char buf[100];\n" @@ -419,8 +403,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: variable is used as parameter and destination in s[n]printf().\n", errout.str()); } - void sprintf2() - { + void sprintf2() { sprintfUsage("void foo()\n" "{\n" " char buf[100];\n" @@ -429,8 +412,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf3() - { + void sprintf3() { sprintfUsage("void foo()\n" "{\n" " char buf[100];\n" @@ -440,8 +422,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sprintf4() - { + void sprintf4() { sprintfUsage("struct A\n" "{\n" " char filename[128];\n" @@ -460,8 +441,7 @@ private: - void strPlusChar(const char code[]) - { + void strPlusChar(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -478,8 +458,7 @@ private: checkOther.strPlusChar(); } - void strPlusChar1() - { + void strPlusChar1() { // Strange looking pointer arithmetic.. strPlusChar("void foo()\n" "{\n" @@ -488,8 +467,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Unusual pointer arithmetic\n", errout.str()); } - void strPlusChar2() - { + void strPlusChar2() { // Strange looking pointer arithmetic.. strPlusChar("void foo()\n" "{\n" @@ -508,8 +486,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void strPlusChar3() - { + void strPlusChar3() { // Strange looking pointer arithmetic.. strPlusChar("void foo()\n" "{\n" @@ -521,8 +498,7 @@ private: - void varScope(const char code[]) - { + void varScope(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -539,8 +515,7 @@ private: checkOther.checkVariableScope(); } - void varScope1() - { + void varScope1() { varScope("unsigned short foo()\n" "{\n" " test_client CClient;\n" @@ -570,8 +545,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope2() - { + void varScope2() { varScope("int foo()\n" "{\n" " Error e;\n" @@ -581,8 +555,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope3() - { + void varScope3() { varScope("void foo()\n" "{\n" " int i;\n" @@ -596,8 +569,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope4() - { + void varScope4() { varScope("void foo()\n" "{\n" " int i;\n" @@ -605,8 +577,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope5() - { + void varScope5() { varScope("void f(int x)\n" "{\n" " int i = 0;\n" @@ -627,8 +598,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'i' can be reduced\n", errout.str()); } - void varScope6() - { + void varScope6() { varScope("void f(int x)\n" "{\n" " int i = x;\n" @@ -668,8 +638,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope7() - { + void varScope7() { varScope("void f(int x)\n" "{\n" " int y = 0;\n" @@ -681,8 +650,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope8() - { + void varScope8() { varScope("void test() {\n" " float edgeResistance=1;\n" " std::vector edges;\n" @@ -693,8 +661,7 @@ private: ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'edgeResistance' can be reduced\n", errout.str()); } - void varScope9() - { + void varScope9() { // classes may have extra side effects varScope("class fred {\n" "public:\n" @@ -709,8 +676,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope10() - { + void varScope10() { // classes may have extra side effects varScope("int f()\n" "{\n" @@ -722,8 +688,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope11() - { + void varScope11() { varScope("int f() {\n" " int x = 0;\n" " AB ab = { x, 0 };\n" @@ -745,8 +710,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void varScope12() - { + void varScope12() { // #2770 varScope("void f() {\n" " int i = 0;\n" @@ -757,8 +721,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void checkOldStylePointerCast(const char code[]) - { + void checkOldStylePointerCast(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -783,8 +746,7 @@ private: checkOtherC.warningOldStylePointerCast(); } - void oldStylePointerCast() - { + void oldStylePointerCast() { checkOldStylePointerCast("class Base;\n" "void foo()\n" "{\n" @@ -835,8 +797,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void dangerousStrolUsage() - { + void dangerousStrolUsage() { { sprintfUsage("int f(const char *num)\n" "{\n" @@ -856,8 +817,7 @@ private: } } - void testPassedByValue(const char code[]) - { + void testPassedByValue(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -872,8 +832,7 @@ private: checkOther.checkConstantFunctionParameter(); } - void passedByValue() - { + void passedByValue() { testPassedByValue("void f(const std::string str) {}"); ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by reference.\n", errout.str()); @@ -912,8 +871,7 @@ private: } - void mathfunctionCall1() - { + void mathfunctionCall1() { // log|log10 check("void foo()\n" "{\n" @@ -1092,8 +1050,7 @@ private: } - void fflushOnInputStreamTest() - { + void fflushOnInputStreamTest() { check("void foo()\n" "{\n" " fflush(stdin);\n" @@ -1107,8 +1064,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sizeofsizeof() - { + void sizeofsizeof() { check("void foo()\n" "{\n" " int i = sizeof sizeof char;\n" @@ -1128,8 +1084,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (warning) Calling sizeof for 'sizeof'.\n", errout.str()); } - void sizeofCalculation() - { + void sizeofCalculation() { check("sizeof(a+b)"); ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof()\n", errout.str()); @@ -1140,8 +1095,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void switchRedundantAssignmentTest() - { + void switchRedundantAssignmentTest() { check("void foo()\n" "{\n" " int y = 1;\n" @@ -1373,8 +1327,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void switchFallThroughCase() - { + void switchFallThroughCase() { check_preprocess_suppress( "void foo() {\n" " switch (a) {\n" @@ -1679,8 +1632,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void duplicateBreak() - { + void duplicateBreak() { check("void foo(int a)\n" "{\n" " switch(a) {\n" @@ -1744,8 +1696,7 @@ private: } - void selfAssignment() - { + void selfAssignment() { check("void foo()\n" "{\n" " int x = 1;\n" @@ -1807,8 +1758,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testScanf1() - { + void testScanf1() { check("#include \n" "int main(int argc, char **argv)\n" "{\n" @@ -1824,8 +1774,7 @@ private: "[test.cpp:7]: (warning) scanf without field width limits can crash with huge input data\n", errout.str()); } - void testScanf2() - { + void testScanf2() { check("#include \n" "int main(int argc, char **argv)\n" "{\n" @@ -1841,8 +1790,7 @@ private: "[test.cpp:7]: (warning) scanf without field width limits can crash with huge input data\n", errout.str()); } - void trac1132() - { + void trac1132() { std::istringstream code("#include \n" "class Lock\n" "{\n" @@ -1878,8 +1826,7 @@ private: ASSERT_EQUALS("[trac1132.cpp:16]: (error) instance of \"Lock\" object destroyed immediately\n", errout.str()); } - void testMisusedScopeObjectDoesNotPickFunction1() - { + void testMisusedScopeObjectDoesNotPickFunction1() { check("int main ( )\n" "{\n" " CouldBeFunction ( 123 ) ;\n" @@ -1889,8 +1836,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectDoesNotPickFunction2() - { + void testMisusedScopeObjectDoesNotPickFunction2() { check("struct error {\n" " error() {}\n" "};\n" @@ -1907,8 +1853,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectPicksClass() - { + void testMisusedScopeObjectPicksClass() { check("class NotAFunction ;\n" "int function ( )\n" "{\n" @@ -1919,8 +1864,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) instance of \"NotAFunction\" object destroyed immediately\n", errout.str()); } - void testMisusedScopeObjectPicksStruct() - { + void testMisusedScopeObjectPicksStruct() { check("struct NotAClass;\n" "bool func ( )\n" "{\n" @@ -1931,8 +1875,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) instance of \"NotAClass\" object destroyed immediately\n", errout.str()); } - void testMisusedScopeObjectDoesNotPickIf() - { + void testMisusedScopeObjectDoesNotPickIf() { check("bool func( int a , int b , int c )\n" "{\n" " if ( a > b ) return c == a ;\n" @@ -1942,8 +1885,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectDoesNotPickConstructorDeclaration() - { + void testMisusedScopeObjectDoesNotPickConstructorDeclaration() { check("class Something : public SomthingElse\n" "{\n" "public:\n" @@ -1954,8 +1896,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectDoesNotPickFunctor() - { + void testMisusedScopeObjectDoesNotPickFunctor() { check("\n" "#include \n" "\n" @@ -1978,8 +1919,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectDoesNotPickLocalClassConstructors() - { + void testMisusedScopeObjectDoesNotPickLocalClassConstructors() { check("void f() {\n" " class Foo {\n" " Foo() { }\n" @@ -1992,8 +1932,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) instance of \"Foo\" object destroyed immediately\n", errout.str()); } - void testMisusedScopeObjectDoesNotPickUsedObject() - { + void testMisusedScopeObjectDoesNotPickUsedObject() { check("struct Foo {\n" " void bar() {\n" " }\n" @@ -2006,8 +1945,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testMisusedScopeObjectDoesNotPickPureC() - { + void testMisusedScopeObjectDoesNotPickPureC() { // Ticket #2352 const char code[] = "struct cb_watch_bool {\n" " int a;\n" @@ -2034,8 +1972,7 @@ private: ASSERT_EQUALS("",errout.str()); } - void testMisusedScopeObjectDoesNotPickNestedClass() - { + void testMisusedScopeObjectDoesNotPickNestedClass() { const char code[] = "class ios_base {\n" "public:\n" " class Init {\n" @@ -2055,8 +1992,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void trac2084() - { + void trac2084() { check("#include \n" "\n" "void f()\n" @@ -2070,8 +2006,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void trac2071() - { + void trac2071() { check("void f() {\n" " struct AB {\n" " AB(int a) { }\n" @@ -2083,8 +2018,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void assignmentInAssert() - { + void assignmentInAssert() { check("void f() {\n" " int a = 0;\n" " assert(a = 2);\n" @@ -2143,8 +2077,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout.str()); } - void incorrectLogicOperator1() - { + void incorrectLogicOperator1() { check("void f(int x) {\n" " if ((x != 1) || (x != 3))\n" " a++;\n" @@ -2251,8 +2184,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void incorrectLogicOperator2() - { + void incorrectLogicOperator2() { check("void f(int x) {\n" " if ((x == 1) && (x == 3))\n" " a++;\n" @@ -2422,8 +2354,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void secondAlwaysTrueFalseWhenFirstTrueError() - { + void secondAlwaysTrueFalseWhenFirstTrueError() { check("void f(int x) {\n" " if (x > 5 && x != 1)\n" " a++;\n" @@ -2538,8 +2469,7 @@ private: } - void comparisonOfBoolExpressionWithInt() - { + void comparisonOfBoolExpressionWithInt() { check("void f(int x) {\n" " if ((x && 0x0f)==6)\n" " a++;\n" @@ -2673,8 +2603,7 @@ private: } - void catchExceptionByValue() - { + void catchExceptionByValue() { check("void f() {\n" " try\n" " {\n" @@ -2767,8 +2696,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void memsetZeroBytes() - { + void memsetZeroBytes() { check("void f() {\n" " memset(p, 10, 0)\n" "}\n" @@ -2786,8 +2714,7 @@ private: "", errout.str()); } - void sizeofForArrayParameter() - { + void sizeofForArrayParameter() { check("void f() {\n" " int a[10];\n" " std::cout << sizeof(a) / sizeof(int) << std::endl;\n" @@ -2919,8 +2846,7 @@ private: } - void sizeofForNumericParameter() - { + void sizeofForNumericParameter() { check("void f() {\n" " std::cout << sizeof(10) << std::endl;\n" "}\n" @@ -2948,8 +2874,7 @@ private: } - void clarifyCalculation() - { + void clarifyCalculation() { check("int f(char c) {\n" " return 10 * (c == 0) ? 1 : 2;\n" "}"); @@ -2989,8 +2914,7 @@ private: } // clarify conditions with = and comparison - void clarifyCondition1() - { + void clarifyCondition1() { check("void f() {\n" " if (x = b() < 0) {}\n" "}"); @@ -3009,8 +2933,7 @@ private: } // clarify conditions with bitwise operator and comparison - void clarifyCondition2() - { + void clarifyCondition2() { check("void f() {\n" " if (x & 2 == 2) {}\n" "}"); @@ -3023,8 +2946,7 @@ private: } // clarify condition that uses ! operator and then bitwise operator - void clarifyCondition3() - { + void clarifyCondition3() { check("void f(int w) {\n" " if(!w & 0x8000) {}\n" "}"); @@ -3050,8 +2972,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void clarifyCondition4() // ticket #3110 - { + void clarifyCondition4() { // ticket #3110 check("typedef double SomeType;\n" "typedef std::pair PairType;\n" "struct S\n" @@ -3066,8 +2987,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void bitwiseOnBoolean() // 3062 - { + void bitwiseOnBoolean() { // 3062 check("void f(_Bool a, _Bool b) {\n" " if(a & b) {}\n" "}"); @@ -3123,8 +3043,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Boolean variable 'a' is used in bitwise operation. Did you mean || ?\n", errout.str()); } - void incorrectStringCompare() - { + void incorrectStringCompare() { check("int f() {\n" " return test.substr( 0 , 4 ) == \"Hello\" ? : 0 : 1 ;\n" "}"); @@ -3147,8 +3066,7 @@ private: } - void incrementBoolean() - { + void incrementBoolean() { check("bool bValue = true;\n" "bValue++;\n"); ASSERT_EQUALS("[test.cpp:2]: (style) The use of a variable of type bool with the ++ postfix operator is always true and deprecated by the C++ Standard.\n", errout.str()); @@ -3168,8 +3086,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void comparisonOfBoolWithInt1() - { + void comparisonOfBoolWithInt1() { check("void f(bool x) {\n" " if (x < 10) {\n" " printf(\"foo\");\n" @@ -3213,8 +3130,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void comparisonOfBoolWithInt2() - { + void comparisonOfBoolWithInt2() { check("void f(bool x, int y) {\n" " if (x == y) {\n" " printf(\"foo\");\n" @@ -3244,8 +3160,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void comparisonOfBoolWithInt3() - { + void comparisonOfBoolWithInt3() { check("void f(int y) {\n" " if (y > false) {\n" " printf(\"foo\");\n" @@ -3268,8 +3183,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void comparisonOfBoolWithInt4() - { + void comparisonOfBoolWithInt4() { check("void f(int x) {\n" " if (!x == 10) {\n" " printf(\"x not equal to 10\");\n" @@ -3313,8 +3227,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void duplicateIf() - { + void duplicateIf() { check("void f(int a, int &b) {\n" " if (a) { b = 1; }\n" " else if (a) { b = 2; }\n" @@ -3366,8 +3279,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void duplicateBranch() - { + void duplicateBranch() { check("void f(int a, int &b) {\n" " if (a)\n" " b = 1;\n" @@ -3398,8 +3310,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void duplicateExpression1() - { + void duplicateExpression1() { check("void foo() {\n" " if (a == a) { }\n" "}"); @@ -3420,8 +3331,7 @@ private: "[test.cpp:6] -> [test.cpp:6]: (style) Same expression on both sides of '<'.\n", errout.str()); } - void duplicateExpression2() // ticket #2730 - { + void duplicateExpression2() { // ticket #2730 check("int main()\n" "{\n" " long double ldbl;\n" @@ -3441,8 +3351,7 @@ private: "[test.cpp:9]: (error) Passing value -1.0 to sqrtf() leads to undefined result\n", errout.str()); } - void alwaysTrueFalseStringCompare() - { + void alwaysTrueFalseStringCompare() { check_preprocess_suppress( "#define MACRO \"00FF00\"\n" "int main()\n" @@ -3486,8 +3395,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void check_signOfUnsignedVariable(const char code[]) - { + void check_signOfUnsignedVariable(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -3504,8 +3412,7 @@ private: checkOther.checkSignOfUnsignedVariable(); } - void checkSignOfUnsignedVariable() - { + void checkSignOfUnsignedVariable() { check_signOfUnsignedVariable( "void foo() {\n" " for(unsigned char i = 10; i >= 0; i--)" @@ -3716,8 +3623,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void checkForSuspiciousSemicolon1() - { + void checkForSuspiciousSemicolon1() { check( "void foo() {\n" " for(int i = 0; i < 10; ++i);\n" @@ -3751,8 +3657,7 @@ private: ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious use of ; at the end of 'if/for/while' statement.\n", errout.str()); } - void checkForSuspiciousSemicolon2() - { + void checkForSuspiciousSemicolon2() { check( "void foo() {\n" " if (i == 1); {\n" diff --git a/test/testpath.cpp b/test/testpath.cpp index 340677d61..7f5633ea5 100644 --- a/test/testpath.cpp +++ b/test/testpath.cpp @@ -20,21 +20,18 @@ #include "testsuite.h" #include "path.h" -class TestPath : public TestFixture -{ +class TestPath : public TestFixture { public: TestPath() : TestFixture("TestPath") { } private: - void run() - { + void run() { TEST_CASE(simplify_path); } - void simplify_path() - { + void simplify_path() { // Path::simplifyPath() ASSERT_EQUALS("index.h", Path::simplifyPath("index.h")); ASSERT_EQUALS("index.h", Path::simplifyPath("./index.h")); diff --git a/test/testpathmatch.cpp b/test/testpathmatch.cpp index bfa6b107d..5d49570f9 100644 --- a/test/testpathmatch.cpp +++ b/test/testpathmatch.cpp @@ -21,16 +21,14 @@ #include "testsuite.h" #include "pathmatch.h" -class TestPathMatch : public TestFixture -{ +class TestPathMatch : public TestFixture { public: TestPathMatch() : TestFixture("TestPathMatch") { } private: - void run() - { + void run() { TEST_CASE(emptymaskemptyfile); TEST_CASE(emptymaskpath1); TEST_CASE(emptymaskpath2); @@ -56,124 +54,108 @@ private: TEST_CASE(filemaskpath4); } - void emptymaskemptyfile() - { + void emptymaskemptyfile() { std::vector masks; PathMatch match(masks); ASSERT(!match.Match("")); } - void emptymaskpath1() - { + void emptymaskpath1() { std::vector masks; PathMatch match(masks); ASSERT(!match.Match("src/")); } - void emptymaskpath2() - { + void emptymaskpath2() { std::vector masks; PathMatch match(masks); ASSERT(!match.Match("../src/")); } - void emptymaskpath3() - { + void emptymaskpath3() { std::vector masks; PathMatch match(masks); ASSERT(!match.Match("/home/user/code/src/")); } - void onemaskemptypath() - { + void onemaskemptypath() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(!match.Match("")); } - void onemasksamepath() - { + void onemasksamepath() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(match.Match("src/")); } - void onemasksamepathdifferentcase() - { + void onemasksamepathdifferentcase() { std::vector masks; masks.push_back("sRc/"); PathMatch match(masks); ASSERT(match.Match("srC/", false)); } - void onemasksamepathwithfile() - { + void onemasksamepathwithfile() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(match.Match("src/file.txt")); } - void onemaskdifferentdir1() - { + void onemaskdifferentdir1() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(!match.Match("srcfiles/file.txt")); } - void onemaskdifferentdir2() - { + void onemaskdifferentdir2() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(!match.Match("proj/srcfiles/file.txt")); } - void onemaskdifferentdir3() - { + void onemaskdifferentdir3() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(!match.Match("proj/mysrc/file.txt")); } - void onemaskdifferentdir4() - { + void onemaskdifferentdir4() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(!match.Match("proj/mysrcfiles/file.txt")); } - void onemasklongerpath1() - { + void onemasklongerpath1() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(match.Match("/tmp/src/")); } - void onemasklongerpath2() - { + void onemasklongerpath2() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(match.Match("src/module/")); } - void onemasklongerpath3() - { + void onemasklongerpath3() { std::vector masks; masks.push_back("src/"); PathMatch match(masks); ASSERT(match.Match("project/src/module/")); } - void twomasklongerpath1() - { + void twomasklongerpath1() { std::vector masks; masks.push_back("src/"); masks.push_back("module/"); @@ -181,8 +163,7 @@ private: ASSERT(!match.Match("project/")); } - void twomasklongerpath2() - { + void twomasklongerpath2() { std::vector masks; masks.push_back("src/"); masks.push_back("module/"); @@ -190,8 +171,7 @@ private: ASSERT(match.Match("project/src/")); } - void twomasklongerpath3() - { + void twomasklongerpath3() { std::vector masks; masks.push_back("src/"); masks.push_back("module/"); @@ -199,8 +179,7 @@ private: ASSERT(match.Match("project/module/")); } - void twomasklongerpath4() - { + void twomasklongerpath4() { std::vector masks; masks.push_back("src/"); masks.push_back("module/"); @@ -208,64 +187,56 @@ private: ASSERT(match.Match("project/src/module/")); } - void filemask1() - { + void filemask1() { std::vector masks; masks.push_back("foo.cpp"); PathMatch match(masks); ASSERT(match.Match("foo.cpp")); } - void filemaskdifferentcase() - { + void filemaskdifferentcase() { std::vector masks; masks.push_back("foo.cPp"); PathMatch match(masks); ASSERT(match.Match("fOo.cpp", false)); } - void filemask2() - { + void filemask2() { std::vector masks; masks.push_back("foo.cpp"); PathMatch match(masks); ASSERT(match.Match("../foo.cpp")); } - void filemask3() - { + void filemask3() { std::vector masks; masks.push_back("foo.cpp"); PathMatch match(masks); ASSERT(match.Match("src/foo.cpp")); } - void filemaskpath1() - { + void filemaskpath1() { std::vector masks; masks.push_back("src/foo.cpp"); PathMatch match(masks); ASSERT(match.Match("src/foo.cpp")); } - void filemaskpath2() - { + void filemaskpath2() { std::vector masks; masks.push_back("src/foo.cpp"); PathMatch match(masks); ASSERT(match.Match("proj/src/foo.cpp")); } - void filemaskpath3() - { + void filemaskpath3() { std::vector masks; masks.push_back("src/foo.cpp"); PathMatch match(masks); ASSERT(!match.Match("foo.cpp")); } - void filemaskpath4() - { + void filemaskpath4() { std::vector masks; masks.push_back("src/foo.cpp"); PathMatch match(masks); diff --git a/test/testpostfixoperator.cpp b/test/testpostfixoperator.cpp index 8b36fcac2..9059955b5 100644 --- a/test/testpostfixoperator.cpp +++ b/test/testpostfixoperator.cpp @@ -25,8 +25,7 @@ extern std::ostringstream errout; -class TestPostfixOperator : public TestFixture -{ +class TestPostfixOperator : public TestFixture { public: TestPostfixOperator() : TestFixture("TestPostfixOperator") { } @@ -35,8 +34,7 @@ private: - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -61,8 +59,7 @@ private: checkPostfixOperator.postfixOperator(); } - void run() - { + void run() { TEST_CASE(testsimple); TEST_CASE(testfor); TEST_CASE(teststream); @@ -73,14 +70,12 @@ private: TEST_CASE(testHangWithInvalidCode); // #2847 - cppcheck hangs with 100% cpu load } - void testHangWithInvalidCode() - { + void testHangWithInvalidCode() { check("a,b--\n"); ASSERT_EQUALS("", errout.str()); } - void testsimple() - { + void testsimple() { check("\n" "#include \n" "int main(int argc, char *argv[])\n" @@ -203,8 +198,7 @@ private: } - void testfor() - { + void testfor() { check("\n" "#include \n" "int main(int argc, char *argv[])\n" @@ -267,8 +261,7 @@ private: } - void teststream() - { + void teststream() { check("\n" "#include \n" "int main(int argc, char *argv[])\n" @@ -307,8 +300,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testvolatile() - { + void testvolatile() { check("\n" "#include \n" "class K {};\n" @@ -324,8 +316,7 @@ private: "[test.cpp:8]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout.str()); } - void testiterator() - { + void testiterator() { check("\n" "#include \n" "class Base {};\n" @@ -393,15 +384,13 @@ private: } - void test2168() - { + void test2168() { check("--> declare allocator lock here\n" "int main(){}\n"); ASSERT_EQUALS("", errout.str()); } - void pointer() - { + void pointer() { check("static struct class * ab;\n" "int * p;\n" "p++;\n"); diff --git a/test/testpreprocessor.cpp b/test/testpreprocessor.cpp index 72af1a9fc..1bf7f5501 100644 --- a/test/testpreprocessor.cpp +++ b/test/testpreprocessor.cpp @@ -35,35 +35,29 @@ extern std::ostringstream errout; extern std::ostringstream output; -class TestPreprocessor : public TestFixture -{ +class TestPreprocessor : public TestFixture { public: TestPreprocessor() : TestFixture("TestPreprocessor") { } - class OurPreprocessor : public Preprocessor - { + class OurPreprocessor : public Preprocessor { public: - static std::string replaceIfDefined(const std::string &str) - { + static std::string replaceIfDefined(const std::string &str) { return Preprocessor::replaceIfDefined(str); } - static std::string expandMacros(std::string code, ErrorLogger *errorLogger = 0) - { + static std::string expandMacros(std::string code, ErrorLogger *errorLogger = 0) { return Preprocessor::expandMacros(code, "file.cpp", errorLogger); } - static int getHeaderFileName(std::string &str) - { + static int getHeaderFileName(std::string &str) { return Preprocessor::getHeaderFileName(str); } }; private: - void run() - { + void run() { // Just read the code into a string. Perform simple cleanup of the code TEST_CASE(readCode1); TEST_CASE(readCode2); @@ -235,8 +229,7 @@ private: } - void readCode1() - { + void readCode1() { const char code[] = " \t a //\n" " #aa\t /* remove this */\tb \r\n"; Settings settings; @@ -246,8 +239,7 @@ private: ASSERT_EQUALS("a\n#aa b\n", codestr); } - void readCode2() - { + void readCode2() { const char code[] = "R\"( \" /* abc */ \n)\""; Settings settings; Preprocessor preprocessor(&settings, this); @@ -257,8 +249,7 @@ private: } - void Bug2190219() - { + void Bug2190219() { const char filedata[] = "int main()\n" "{\n" "#ifdef __cplusplus\n" @@ -320,8 +311,7 @@ private: } - void test1() - { + void test1() { const char filedata[] = "#ifdef WIN32 \n" " abcdef\n" "#else \n" @@ -341,8 +331,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test2() - { + void test2() { const char filedata[] = "# ifndef WIN32\n" " \" # ifdef WIN32\" // a comment\n" " # else \n" @@ -362,8 +351,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test3() - { + void test3() { const char filedata[] = "#ifdef ABC\n" "a\n" "#ifdef DEF\n" @@ -386,8 +374,7 @@ private: ASSERT_EQUALS(3, static_cast(actual.size())); } - void test4() - { + void test4() { const char filedata[] = "#ifdef ABC\n" "A\n" "#endif\t\n" @@ -408,8 +395,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test5() - { + void test5() { const char filedata[] = "#ifdef ABC\n" "A\n" "#else\n" @@ -433,8 +419,7 @@ private: ASSERT_EQUALS(3, static_cast(actual.size())); } - void test6() - { + void test6() { const char filedata[] = "#if(A)\n" "#if ( A ) \n" "#if A\n" @@ -450,8 +435,7 @@ private: ASSERT_EQUALS("#if A\n#if A\n#if A\n#if defined(A)\n#elif defined(A)\n", actual); } - void test7() - { + void test7() { const char filedata[] = "#ifdef ABC\n" "A\n" "#ifdef ABC\n" @@ -483,8 +467,7 @@ private: test7d(); } - void test7a() - { + void test7a() { const char filedata[] = "#ifndef ABC\n" "A\n" "#ifndef ABC\n" @@ -508,8 +491,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test7b() - { + void test7b() { const char filedata[] = "#ifndef ABC\n" "A\n" "#ifdef ABC\n" @@ -533,8 +515,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test7c() - { + void test7c() { const char filedata[] = "#ifdef ABC\n" "A\n" "#ifndef ABC\n" @@ -559,8 +540,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test7d() - { + void test7d() { const char filedata[] = "#if defined(ABC)\n" "A\n" "#if defined(ABC)\n" @@ -585,8 +565,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void test7e() - { + void test7e() { const char filedata[] = "#ifdef ABC\n" "#file \"test.h\"\n" "#ifndef test_h\n" @@ -614,8 +593,7 @@ private: } - void error1() - { + void error1() { const char filedata[] = "#ifdef A\n" ";\n" "#else\n" @@ -638,8 +616,7 @@ private: } - void error2() - { + void error2() { errout.str(""); const char filedata[] = "#error ê\n" @@ -654,8 +631,7 @@ private: } - void error3() - { + void error3() { errout.str(""); Settings settings; settings.userDefines = "__cplusplus"; @@ -665,8 +641,7 @@ private: } // Ticket #2919 - wrong filename reported for #error - void error4() - { + void error4() { // In included file { errout.str(""); @@ -688,8 +663,7 @@ private: } } - void if0_exclude() - { + void if0_exclude() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -706,8 +680,7 @@ private: ASSERT_EQUALS("#if 0\n\n#endif\nB\n", preprocessor.read(code2,"",NULL)); } - void if0_whitespace() - { + void if0_whitespace() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -718,8 +691,7 @@ private: ASSERT_EQUALS("#if 0\n\n#endif\nB\n", preprocessor.read(code,"",NULL)); } - void if0_else() - { + void if0_else() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -741,8 +713,7 @@ private: "#if 1\nA\n#else\nB\n#endif\nC\n", preprocessor.read(code2,"",NULL)); } - void if0_elif() - { + void if0_elif() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -755,8 +726,7 @@ private: ASSERT_EQUALS("#if 0\n\n#elif 1\nB\n#endif\nC\n", preprocessor.read(code,"",NULL)); } - void if0_include_1() - { + void if0_include_1() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -767,8 +737,7 @@ private: ASSERT_EQUALS("#if 0\n\n#endif\nAB\n", preprocessor.read(code,"",NULL)); } - void if0_include_2() - { + void if0_include_2() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -782,8 +751,7 @@ private: ASSERT_EQUALS("#if 0\n\n#ifdef WIN32\n#else\n#endif\n#endif\nAB\n", preprocessor.read(code,"",NULL)); } - void includeguard1() - { + void includeguard1() { // Handling include guards.. const char filedata[] = "#file \"abc.h\"\n" "#ifndef abcH\n" @@ -804,8 +772,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void includeguard2() - { + void includeguard2() { // Handling include guards.. const char filedata[] = "#file \"abc.h\"\n" "foo\n" @@ -828,8 +795,7 @@ private: } - void ifdefwithfile() - { + void ifdefwithfile() { // Handling include guards.. const char filedata[] = "#ifdef ABC\n" "#file \"abc.h\"\n" @@ -857,8 +823,7 @@ private: ASSERT_EQUALS("\n#file \"abc.h\"\nclass A{};\n\n\n\n\n\n\n\n#endfile\n\nint main() {}\n", actual["ABC"]); } - void newlines() - { + void newlines() { const char filedata[] = "\r\r\n\n"; // Preprocess @@ -870,8 +835,7 @@ private: - void comments1() - { + void comments1() { { const char filedata[] = "/*\n" "#ifdef WIN32\n" @@ -929,8 +893,7 @@ private: - void if0() - { + void if0() { const char filedata[] = " # if /* comment */ 0 // comment\n" "#ifdef WIN32\n" "#endif\n" @@ -948,8 +911,7 @@ private: ASSERT_EQUALS(1, static_cast(actual.size())); } - void if1() - { + void if1() { const char filedata[] = " # if /* comment */ 1 // comment\n" "ABC\n" " # endif \n"; @@ -967,8 +929,7 @@ private: } - void elif() - { + void elif() { { const char filedata[] = "#if DEF1\n" "ABC\n" @@ -1016,8 +977,7 @@ private: - void match_cfg_def() - { + void match_cfg_def() { { std::map cfg; ASSERT_EQUALS(false, Preprocessor::match_cfg_def(cfg, "A>1||defined(B)")); @@ -1056,8 +1016,7 @@ private: } - void if_cond1() - { + void if_cond1() { const char filedata[] = "#if LIBVER>100\n" " A\n" "#else\n" @@ -1078,8 +1037,7 @@ private: "", actual["LIBVER=101"]); } - void if_cond2() - { + void if_cond2() { const char filedata[] = "#ifdef A\n" "a\n" "#endif\n" @@ -1105,8 +1063,7 @@ private: if_cond2e(); } - void if_cond2b() - { + void if_cond2b() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" @@ -1130,8 +1087,7 @@ private: ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n", actual["B"]); } - void if_cond2c() - { + void if_cond2c() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" @@ -1157,8 +1113,7 @@ private: ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n\n\n", actual["B"]); } - void if_cond2d() - { + void if_cond2d() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" @@ -1190,8 +1145,7 @@ private: ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n\n\n\n\n\n\n\n", actual["B"]); } - void if_cond2e() - { + void if_cond2e() { const char filedata[] = "#if !defined(A)\n" "!a\n" "#elif !defined(B)\n" @@ -1215,8 +1169,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if_cond3() - { + void if_cond3() { const char filedata[] = "#ifdef A\n" "a\n" "#if defined(B) && defined(C)\n" @@ -1238,8 +1191,7 @@ private: ASSERT_EQUALS("\na\n\nabc\n\n\n", actual["A;B;C"]); } - void if_cond4() - { + void if_cond4() { { const char filedata[] = "#define A\n" "#define B\n" @@ -1337,8 +1289,7 @@ private: } } - void if_cond5() - { + void if_cond5() { const char filedata[] = "#if defined(A) && defined(B)\n" "ab\n" "#endif\n" @@ -1360,8 +1311,7 @@ private: ASSERT_EQUALS("\nab\n\ncd\n\nef\n\n", actual["A;B"]); } - void if_cond6() - { + void if_cond6() { const char filedata[] = "\n" "#if defined(A) && defined(B))\n" "#endif\n"; @@ -1379,8 +1329,7 @@ private: ASSERT_EQUALS("[file.c:2]: (error) mismatching number of '(' and ')' in this line: defined(A)&&defined(B))\n", errout.str()); } - void if_cond8() - { + void if_cond8() { const char filedata[] = "#if defined(A) + defined(B) + defined(C) != 1\n" "#endif\n"; @@ -1397,8 +1346,7 @@ private: } - void if_cond9() - { + void if_cond9() { const char filedata[] = "#if !defined _A\n" "abc\n" "#endif\n"; @@ -1415,8 +1363,7 @@ private: ASSERT_EQUALS("\nabc\n\n", actual[""]); } - void if_cond10() - { + void if_cond10() { const char filedata[] = "#if !defined(a) && !defined(b)\n" "#if defined(and)\n" "#endif\n" @@ -1430,8 +1377,7 @@ private: preprocessor.preprocess(istr, actual, "file.c"); } - void if_cond11() - { + void if_cond11() { errout.str(""); const char filedata[] = "#if defined(L_fixunssfdi) && LIBGCC2_HAS_SF_MODE\n" "#if LIBGCC2_HAS_DF_MODE\n" @@ -1446,8 +1392,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if_cond12() - { + void if_cond12() { const char filedata[] = "#define A (1)\n" "#if A == 1\n" ";\n" @@ -1457,8 +1402,7 @@ private: - void if_or_1() - { + void if_or_1() { const char filedata[] = "#if defined(DEF_10) || defined(DEF_11)\n" "a1;\n" "#endif\n"; @@ -1487,8 +1431,7 @@ private: } - void if_or_2() - { + void if_or_2() { const std::string code("#if X || Y\n" "a1;\n" "#endif\n"); @@ -1497,8 +1440,7 @@ private: } - void multiline1() - { + void multiline1() { const char filedata[] = "#define str \"abc\" \\\n" " \"def\" \n" "abcdef = str;\n"; @@ -1510,8 +1452,7 @@ private: ASSERT_EQUALS("#define str \"abc\" \"def\"\n\nabcdef = str;\n", preprocessor.read(istr, "test.c", 0)); } - void multiline2() - { + void multiline2() { const char filedata[] = "#define sqr(aa) aa * \\\n" " aa\n" "sqr(5);\n"; @@ -1523,8 +1464,7 @@ private: ASSERT_EQUALS("#define sqr(aa) aa * aa\n\nsqr(5);\n", preprocessor.read(istr, "test.c", 0)); } - void multiline3() - { + void multiline3() { const char filedata[] = "const char *str = \"abc\\\n" "def\\\n" "ghi\"\n"; @@ -1536,8 +1476,7 @@ private: ASSERT_EQUALS("const char *str = \"abcdefghi\"\n\n\n", preprocessor.read(istr, "test.c", 0)); } - void multiline4() - { + void multiline4() { errout.str(""); const char filedata[] = "#define A int a = 4;\\ \n" " int b = 5;\n" @@ -1560,8 +1499,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void multiline5() - { + void multiline5() { errout.str(""); const char filedata[] = "#define ABC int a /*\n" "*/= 4;\n" @@ -1582,8 +1520,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void remove_asm() - { + void remove_asm() { std::string str1("\nasm(\n\n\n);"); Preprocessor::removeAsm(str1); ASSERT_EQUALS("\nasm()\n\n\n;", str1); @@ -1601,8 +1538,7 @@ private: ASSERT_EQUALS("\n;asm();\n\n\n", str4); } - void if_defined() - { + void if_defined() { { const char filedata[] = "#if defined(AAA)\n" "#endif\n"; @@ -1614,16 +1550,14 @@ private: } } - void if_not_defined() - { + void if_not_defined() { const char filedata[] = "#if !defined(AAA)\n" "#endif\n"; ASSERT_EQUALS("#ifndef AAA\n#endif\n", OurPreprocessor::replaceIfDefined(filedata)); } - void macro_simple1() - { + void macro_simple1() { { const char filedata[] = "#define AAA(aa) f(aa)\n" "AAA(5);\n"; @@ -1637,29 +1571,25 @@ private: } } - void macro_simple2() - { + void macro_simple2() { const char filedata[] = "#define min(x,y) x 0 ) return 1;\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple5() - { + void macro_simple5() { const char filedata[] = "#define ABC if( temp > 0 ) return 1;\n" "\n" "void foo()\n" @@ -1670,80 +1600,69 @@ private: ASSERT_EQUALS("\n\nvoid foo()\n{\n int temp = 0;\n if( temp > 0 ) return 1;\n}\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple6() - { + void macro_simple6() { const char filedata[] = "#define ABC (a+b+c)\n" "ABC\n"; ASSERT_EQUALS("\n(a+b+c)\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple7() - { + void macro_simple7() { const char filedata[] = "#define ABC(str) str\n" "ABC(\"(\")\n"; ASSERT_EQUALS("\n\"(\"\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple8() - { + void macro_simple8() { const char filedata[] = "#define ABC 123\n" "#define ABCD 1234\n" "ABC ABCD\n"; ASSERT_EQUALS("\n\n123 1234\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple9() - { + void macro_simple9() { const char filedata[] = "#define ABC(a) f(a)\n" "ABC( \"\\\"\" );\n" "ABC( \"g\" );\n"; ASSERT_EQUALS("\nf(\"\\\"\");\nf(\"g\");\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple10() - { + void macro_simple10() { const char filedata[] = "#define ABC(t) t x\n" "ABC(unsigned long);\n"; ASSERT_EQUALS("\nunsigned long x;\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple11() - { + void macro_simple11() { const char filedata[] = "#define ABC(x) delete x\n" "ABC(a);\n"; ASSERT_EQUALS("\ndelete a;\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple12() - { + void macro_simple12() { const char filedata[] = "#define AB ab.AB\n" "AB.CD\n"; ASSERT_EQUALS("\nab.AB.CD\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple13() - { + void macro_simple13() { const char filedata[] = "#define TRACE(x)\n" "TRACE(;if(a))\n"; ASSERT_EQUALS("\n\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple14() - { + void macro_simple14() { const char filedata[] = "#define A \" a \"\n" "printf(A);\n"; ASSERT_EQUALS("\nprintf(\" a \");\n", OurPreprocessor::expandMacros(filedata)); } - void macro_simple15() - { + void macro_simple15() { const char filedata[] = "#define FOO\"foo\"\n" "FOO\n"; ASSERT_EQUALS("\n\"foo\"\n", OurPreprocessor::expandMacros(filedata)); } - void macroInMacro1() - { + void macroInMacro1() { { const char filedata[] = "#define A(m) long n = m; n++;\n" "#define B(n) A(n)\n" @@ -1843,23 +1762,20 @@ private: } } - void macroInMacro2() - { + void macroInMacro2() { const char filedata[] = "#define A(x) a##x\n" "#define B 0\n" "A(B)\n"; ASSERT_EQUALS("\n\naB\n", OurPreprocessor::expandMacros(filedata)); } - void macro_mismatch() - { + void macro_mismatch() { const char filedata[] = "#define AAA(aa,bb) f(aa)\n" "AAA(5);\n"; ASSERT_EQUALS("\nAAA(5);\n", OurPreprocessor::expandMacros(filedata)); } - void macro_linenumbers() - { + void macro_linenumbers() { const char filedata[] = "#define AAA(a)\n" "AAA(5\n" "\n" @@ -1873,15 +1789,13 @@ private: OurPreprocessor::expandMacros(filedata)); } - void macro_nopar() - { + void macro_nopar() { const char filedata[] = "#define AAA( ) { NULL }\n" "AAA()\n"; ASSERT_EQUALS("\n{ NULL }\n", OurPreprocessor::expandMacros(filedata)); } - void macro_switchCase() - { + void macro_switchCase() { { // Make sure "case 2" doesn't become "case2" const char filedata[] = "#define A( b ) " @@ -1927,8 +1841,7 @@ private: } } - void string1() - { + void string1() { const char filedata[] = "int main()" "{" " const char *a = \"#define A\n\";" @@ -1946,8 +1859,7 @@ private: ASSERT_EQUALS("int main(){ const char *a = \"#define A\n\";}\n", actual[""]); } - void string2() - { + void string2() { const char filedata[] = "#define AAA 123\n" "str = \"AAA\"\n"; @@ -1955,8 +1867,7 @@ private: ASSERT_EQUALS("\nstr = \"AAA\"\n", OurPreprocessor::expandMacros(filedata)); } - void string3() - { + void string3() { const char filedata[] = "str(\";\");\n"; // Compare results.. @@ -1964,8 +1875,7 @@ private: } - void preprocessor_undef() - { + void preprocessor_undef() { { const char filedata[] = "#define AAA int a;\n" "#undef AAA\n" @@ -1987,8 +1897,7 @@ private: } } - void defdef() - { + void defdef() { const char filedata[] = "#define AAA 123\n" "#define AAA 456\n" "#define AAA 789\n" @@ -1998,8 +1907,7 @@ private: ASSERT_EQUALS("\n\n\n789\n", OurPreprocessor::expandMacros(filedata)); } - void preprocessor_doublesharp() - { + void preprocessor_doublesharp() { // simple testcase without ## const char filedata1[] = "#define TEST(var,val) var = val\n" "TEST(foo,20);\n"; @@ -2039,8 +1947,7 @@ private: - void preprocessor_include_in_str() - { + void preprocessor_include_in_str() { const char filedata[] = "int main()\n" "{\n" "const char *a = \"#include \n\";\n" @@ -2062,8 +1969,7 @@ private: - void va_args_1() - { + void va_args_1() { const char filedata[] = "#define DBG(fmt...) printf(fmt)\n" "DBG(\"[0x%lx-0x%lx)\", pstart, pend);\n"; @@ -2073,8 +1979,7 @@ private: ASSERT_EQUALS("\nprintf(\"[0x%lx-0x%lx)\",pstart,pend);\n", actual); } - void va_args_2() - { + void va_args_2() { const char filedata[] = "#define DBG(fmt, args...) printf(fmt, ## args)\n" "DBG(\"hello\");\n"; @@ -2084,15 +1989,13 @@ private: ASSERT_EQUALS("\nprintf(\"hello\");\n", actual); } - void va_args_3() - { + void va_args_3() { const char filedata[] = "#define FRED(...) { fred(__VA_ARGS__); }\n" "FRED(123)\n"; ASSERT_EQUALS("\n{ fred(123); }\n", OurPreprocessor::expandMacros(filedata)); } - void va_args_4() - { + void va_args_4() { const char filedata[] = "#define FRED(name, ...) name (__VA_ARGS__)\n" "FRED(abc, 123)\n"; ASSERT_EQUALS("\nabc(123)\n", OurPreprocessor::expandMacros(filedata)); @@ -2100,8 +2003,7 @@ private: - void multi_character_character() - { + void multi_character_character() { const char filedata[] = "#define FOO 'ABCD'\n" "int main()\n" "{\n" @@ -2122,8 +2024,7 @@ private: } - void stringify() - { + void stringify() { const char filedata[] = "#define STRINGIFY(x) #x\n" "STRINGIFY(abc)\n"; @@ -2133,8 +2034,7 @@ private: ASSERT_EQUALS("\n\"abc\"\n", actual); } - void stringify2() - { + void stringify2() { const char filedata[] = "#define A(x) g(#x)\n" "A(abc);\n"; @@ -2144,8 +2044,7 @@ private: ASSERT_EQUALS("\ng(\"abc\");\n", actual); } - void stringify3() - { + void stringify3() { const char filedata[] = "#define A(x) g(#x)\n" "A( abc);\n"; @@ -2155,8 +2054,7 @@ private: ASSERT_EQUALS("\ng(\"abc\");\n", actual); } - void stringify4() - { + void stringify4() { const char filedata[] = "#define A(x) #x\n" "1 A(\n" "abc\n" @@ -2168,15 +2066,13 @@ private: ASSERT_EQUALS("\n1 \n\n\"abc\" 2\n", actual); } - void stringify5() - { + void stringify5() { const char filedata[] = "#define A(x) a(#x,x)\n" "A(foo(\"\\\"\"))\n"; ASSERT_EQUALS("\na(\"foo(\\\"\\\\\\\"\\\")\",foo(\"\\\"\"))\n", OurPreprocessor::expandMacros(filedata)); } - void pragma() - { + void pragma() { const char filedata[] = "#pragma once\n" "void f()\n" "{\n" @@ -2194,8 +2090,7 @@ private: ASSERT_EQUALS("\nvoid f()\n{\n}\n", actual[""]); } - void pragma_asm_1() - { + void pragma_asm_1() { const char filedata[] = "#pragma asm\n" " mov r1, 11\n" "#pragma endasm\n" @@ -2217,8 +2112,7 @@ private: ASSERT_EQUALS("\n\n\naaa\n\n\n\nbbb\n", actual[""]); } - void pragma_asm_2() - { + void pragma_asm_2() { const char filedata[] = "#pragma asm\n" " mov @w1, 11\n" "#pragma endasm ( temp=@w1 )\n" @@ -2236,8 +2130,7 @@ private: ASSERT_EQUALS("\n\nasm(temp);\nbbb\n", actual[""]); } - void endifsemicolon() - { + void endifsemicolon() { const char filedata[] = "void f()\n" "{\n" "#ifdef A\n" @@ -2260,8 +2153,7 @@ private: "}\n", actual[""]); } - void handle_error() - { + void handle_error() { { const char filedata[] = "#define A \n" "#define B don't want to \\\n" @@ -2290,8 +2182,7 @@ private: } } - void missing_doublequote() - { + void missing_doublequote() { { const char filedata[] = "#define a\n" "#ifdef 1\n" @@ -2365,8 +2256,7 @@ private: } } - void unicodeInCode() - { + void unicodeInCode() { const std::string filedata("a\xC8"); std::istringstream istr(filedata); errout.str(""); @@ -2376,8 +2266,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (error) The code contains characters that are unhandled. Neither unicode nor extended ASCII are supported. (line=1, character code=c8)\n", errout.str()); } - void unicodeInComment() - { + void unicodeInComment() { const std::string filedata("//\xC8"); std::istringstream istr(filedata.c_str()); Settings settings; @@ -2385,8 +2274,7 @@ private: ASSERT_EQUALS("", preprocessor.read(istr, "test.cpp", 0)); } - void unicodeInString() - { + void unicodeInString() { const std::string filedata("\"\xC8\""); std::istringstream istr(filedata.c_str()); Settings settings; @@ -2395,8 +2283,7 @@ private: } - void define_part_of_func() - { + void define_part_of_func() { errout.str(""); const char filedata[] = "#define A g(\n" "void f() {\n" @@ -2416,8 +2303,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void conditionalDefine() - { + void conditionalDefine() { const char filedata[] = "#ifdef A\n" "#define N 10\n" "#else\n" @@ -2440,8 +2326,7 @@ private: } - void multiline_comment() - { + void multiline_comment() { errout.str(""); const char filedata[] = "#define ABC {// \\\n" "}\n" @@ -2460,8 +2345,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void macro_parameters() - { + void macro_parameters() { errout.str(""); const char filedata[] = "#define BC(a, b, c, arg...) \\\n" "AB(a, b, c, ## arg)\n" @@ -2484,8 +2368,7 @@ private: ASSERT_EQUALS("[file.c:6]: (error) Syntax error. Not enough parameters for macro 'BC'.\n", errout.str()); } - void newline_in_macro() - { + void newline_in_macro() { errout.str(""); const char filedata[] = "#define ABC(str) printf( str )\n" "void f()\n" @@ -2506,8 +2389,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void includes() - { + void includes() { { std::string src = "#include a.h"; ASSERT_EQUALS(OurPreprocessor::NoHeader, OurPreprocessor::getHeaderFileName(src)); @@ -2539,8 +2421,7 @@ private: } } - void ifdef_ifdefined() - { + void ifdef_ifdefined() { const char filedata[] = "#ifdef ABC\n" "A\n" "#endif\t\n" @@ -2561,8 +2442,7 @@ private: ASSERT_EQUALS(2, static_cast(actual.size())); } - void define_if1() - { + void define_if1() { { const char filedata[] = "#define A 0\n" "#if A\n" @@ -2579,8 +2459,7 @@ private: } } - void define_if2() - { + void define_if2() { const char filedata[] = "#define A 22\n" "#define B A\n" "#if (B==A) || (B==C)\n" @@ -2589,8 +2468,7 @@ private: ASSERT_EQUALS("\n\n\nFOO\n\n", Preprocessor::getcode(filedata,"","",NULL,NULL)); } - void define_ifdef() - { + void define_ifdef() { { const char filedata[] = "#define ABC\n" "#ifndef ABC\n" @@ -2685,8 +2563,7 @@ private: } } - void define_ifndef1() - { + void define_ifndef1() { const char filedata[] = "#define A(x) (x)\n" "#ifndef A\n" ";\n" @@ -2705,8 +2582,7 @@ private: 2, actual.size()); } - void define_ifndef2() - { + void define_ifndef2() { const char filedata[] = "#ifdef A\n" "#define B char\n" "#endif\n" @@ -2720,8 +2596,7 @@ private: ASSERT_EQUALS("\n\n\n\n\n\nchar me;\n", Preprocessor::getcode(filedata, "A", "a.cpp", NULL, NULL)); } - void redundant_config() - { + void redundant_config() { const char filedata[] = "int main() {\n" "#ifdef FOO\n" "#ifdef BAR\n" @@ -2753,8 +2628,7 @@ private: } - void endfile() - { + void endfile() { const char filedata[] = "char a[] = \"#endfile\";\n" "char b[] = \"#endfile\";\n" "#include \"notfound.h\"\n"; @@ -2771,8 +2645,7 @@ private: ASSERT_EQUALS(1, (int)actual.size()); } - void dup_defines() - { + void dup_defines() { const char filedata[] = "#ifdef A\n" "#define B\n" "#if defined(B) && defined(A)\n" @@ -2794,27 +2667,20 @@ private: TODO_ASSERT_EQUALS(2, 3, static_cast(actual.size())); - if (actual.find("A") == actual.end()) - { + if (actual.find("A") == actual.end()) { ASSERT_EQUALS("A is checked", "failed"); - } - else - { + } else { ASSERT_EQUALS("A is checked", "A is checked"); } - if (actual.find("A;A;B") != actual.end()) - { + if (actual.find("A;A;B") != actual.end()) { ASSERT_EQUALS("A;A;B is NOT checked", "failed"); - } - else - { + } else { ASSERT_EQUALS("A;A;B is NOT checked", "A;A;B is NOT checked"); } } - void testPreprocessorRead1() - { + void testPreprocessorRead1() { const std::string filedata("/*\n*/ # /*\n*/ defi\\\nne FO\\\nO 10\\\n20"); std::istringstream istr(filedata.c_str()); Settings settings; @@ -2822,8 +2688,7 @@ private: ASSERT_EQUALS("#define FOO 1020", preprocessor.read(istr, "test.cpp", 0)); } - void testPreprocessorRead2() - { + void testPreprocessorRead2() { const std::string filedata("\"foo\\\\\nbar\""); std::istringstream istr(filedata.c_str()); Settings settings; @@ -2831,8 +2696,7 @@ private: ASSERT_EQUALS("\"foo\\bar\"", preprocessor.read(istr, "test.cpp", 0)); } - void testPreprocessorRead3() - { + void testPreprocessorRead3() { const std::string filedata("#define A \" a \"\n\" b\""); std::istringstream istr(filedata.c_str()); Settings settings; @@ -2840,8 +2704,7 @@ private: ASSERT_EQUALS(filedata, preprocessor.read(istr, "test.cpp", 0)); } - void testPreprocessorRead4() - { + void testPreprocessorRead4() { { // test < \\> < > (unescaped) const std::string filedata("#define A \" \\\\\"/*space*/ \" \""); @@ -2870,8 +2733,7 @@ private: } } - void invalid_define() - { + void invalid_define() { Settings settings; Preprocessor preprocessor(&settings, this); @@ -2882,8 +2744,7 @@ private: preprocessor.preprocess(src, processedFile, cfg, "", paths); // don't hang } - void inline_suppression_for_missing_include() - { + void inline_suppression_for_missing_include() { Settings settings; settings._inlineSuppressions = true; settings.addEnabled("all"); @@ -2902,8 +2763,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void predefine1() - { + void predefine1() { Settings settings; const std::string src("#ifdef X || Y\n" @@ -2915,8 +2775,7 @@ private: ASSERT_EQUALS("\nFred & Wilma\n\n", actual); } - void predefine2() - { + void predefine2() { Settings settings; const std::string src("#ifdef X && Y\n" @@ -2933,8 +2792,7 @@ private: } } - void predefine3() - { + void predefine3() { // #2871 - define in source is not used if -D is used const char code[] = "#define X 1\n" "#define Y X\n" @@ -2946,8 +2804,7 @@ private: ASSERT_EQUALS("\n\n\nFred & Wilma\n\n", actual); } - void simplifyCondition() - { + void simplifyCondition() { // Ticket #2794 std::map cfg; cfg["C"] = ""; @@ -2956,8 +2813,7 @@ private: ASSERT_EQUALS("1", condition); } - void invalidElIf() - { + void invalidElIf() { // #2942 - segfault const char code[] = "#elif (){\n"; const Settings settings; diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 34ce0ed80..1795c827c 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -28,8 +28,7 @@ extern std::ostringstream errout; -class TestSimplifyTokens : public TestFixture -{ +class TestSimplifyTokens : public TestFixture { public: TestSimplifyTokens() : TestFixture("TestSimplifyTokens") { } @@ -37,8 +36,7 @@ public: private: - void run() - { + void run() { // Make sure the Tokenizer::simplifyTokenList works. // The order of the simplifications is important. So this test // case shall make sure the simplifications are done in the @@ -394,8 +392,7 @@ private: TEST_CASE(removeRedundantFor); } - std::string tok(const char code[], bool simplify = true, Settings::PlatformType type = Settings::Unspecified) - { + std::string tok(const char code[], bool simplify = true, Settings::PlatformType type = Settings::Unspecified) { errout.str(""); Settings settings; @@ -411,12 +408,10 @@ private: tokenizer.validate(); std::string ret; - for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) { if (tok1 != tokenizer.tokens()) ret += " "; - if (!simplify) - { + if (!simplify) { if (tok1->isUnsigned()) ret += "unsigned "; else if (tok1->isSigned()) @@ -431,16 +426,14 @@ private: } - void simplifyTokenList1() - { + void simplifyTokenList1() { // #1717 : The simplifyErrNoInWhile needs to be used before simplifyIfAssign.. ASSERT_EQUALS("; x = f ( ) ; while ( x == -1 ) { x = f ( ) ; }", tok(";while((x=f())==-1 && errno==EINTR){}",true)); } - void cast() - { + void cast() { ASSERT_EQUALS("if ( ! p )", tok("if (p == (char *)0)")); ASSERT_EQUALS("return str ;", tok("return (char *)str;")); @@ -470,8 +463,7 @@ private: } - void iftruefalse() - { + void iftruefalse() { { const char code1[] = " void f() { int a; bool use = false; if( use ) { a=0; } else {a=1;} }"; const char code2[] = " void f() { int a; bool use = false; {a=1;} }"; @@ -539,8 +531,7 @@ private: } } - void combine_strings() - { + void combine_strings() { const char code1[] = "void foo()\n" "{\n" "const char *a =\n" @@ -560,8 +551,7 @@ private: ASSERT_EQUALS(tok(code2), tok(code1)); } - void combine_wstrings() - { + void combine_wstrings() { const char code1[] = "void foo()\n" "{\n" "const wchar_t *a =\n" @@ -581,8 +571,7 @@ private: ASSERT_EQUALS(tok(code2), tok(code1)); } - void double_plus() - { + void double_plus() { { const char code1[] = "void foo( int a )\n" "{\n" @@ -644,8 +633,7 @@ private: } } - void redundant_plus() - { + void redundant_plus() { { const char code1[] = "void foo( int a, int b )\n" "{\n" @@ -698,14 +686,12 @@ private: } - void parentheses1() - { + void parentheses1() { ASSERT_EQUALS("<= 110 ;", tok("<= (10+100);")); ASSERT_EQUALS("while ( x ( ) == -1 ) { }", tok("while((x()) == -1){ }")); } - void parenthesesVar() - { + void parenthesesVar() { // remove parentheses.. ASSERT_EQUALS("= p ;", tok("= (p);")); ASSERT_EQUALS("if ( a < p ) { }", tok("if(a<(p)){}")); @@ -730,21 +716,18 @@ private: ASSERT_EQUALS("void foo ( int p ) { if ( 0 <= p ) { ; } }", tok("void foo(int p){if((p)>=0);}")); } - void declareVar() - { + void declareVar() { const char code[] = "void f ( ) { char str [ 100 ] = \"100\" ; }"; ASSERT_EQUALS(code, tok(code)); } - void declareArray() - { + void declareArray() { const char code[] = "void f ( ) { char str [ ] = \"100\" ; }"; const char expected[] = "void f ( ) { char str [ 4 ] = \"100\" ; }"; ASSERT_EQUALS(expected, tok(code)); } - void dontRemoveIncrement() - { + void dontRemoveIncrement() { { const char code[] = "void f(int a)\n" "{\n" @@ -770,8 +753,7 @@ private: } } - void removePostIncrement() - { + void removePostIncrement() { const char code[] = "void f(int &c)\n" "{\n" " c = 0;\n" @@ -784,8 +766,7 @@ private: } - void removePreIncrement() - { + void removePreIncrement() { { const char code[] = "void f(int &c)\n" "{\n" @@ -809,8 +790,7 @@ private: } - std::string elseif(const char code[]) - { + std::string elseif(const char code[]) { errout.str(""); Settings settings; @@ -822,8 +802,7 @@ private: return tokenizer.tokens()->stringifyList(false); } - void elseif1() - { + void elseif1() { const char code[] = "else if(ab) { cd } else { ef }gh"; ASSERT_EQUALS("\n\n##file 0\n1: else { if ( ab ) { cd } else { ef } } gh\n", elseif(code)); @@ -862,8 +841,7 @@ private: } - void ifa_ifa() - { + void ifa_ifa() { ASSERT_EQUALS("int a ; if ( a ) { { ab } cd }", tok("int a ; if (a) { if (a) { ab } cd }", true)); ASSERT_EQUALS("int a ; if ( a ) { { ab } cd }", tok("int a ; if (unlikely(a)) { if (a) { ab } cd }", true)); } @@ -873,8 +851,7 @@ private: // Simplify 'sizeof'.. - std::string sizeof_(const char code[], bool simplify = true, Settings::PlatformType type = Settings::Unspecified) - { + std::string sizeof_(const char code[], bool simplify = true, Settings::PlatformType type = Settings::Unspecified) { errout.str(""); Settings settings; @@ -890,10 +867,8 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) - { - if (tok1->previous()) - { + for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) { + if (tok1->previous()) { ostr << " "; } ostr << tok1->str(); @@ -902,8 +877,7 @@ private: return ostr.str(); } - unsigned int sizeofFromTokenizer(const char type[]) - { + unsigned int sizeofFromTokenizer(const char type[]) { errout.str(""); Settings settings; @@ -917,15 +891,13 @@ private: return tokenizer.sizeOfType(&tok1); } - void sizeof1() - { + void sizeof1() { ASSERT_EQUALS("struct ABC * abc ; abc = malloc ( 100 ) ;", tok("struct ABC *abc = malloc(sizeof(*abc));")); ASSERT_EQUALS("struct ABC * abc ; abc = malloc ( 100 ) ;", tok("struct ABC *abc = malloc(sizeof *abc );")); } - void sizeof2() - { + void sizeof2() { const char code[] = "void foo()\n" "{\n" " int i[4];\n" @@ -935,8 +907,7 @@ private: ASSERT_EQUALS("void foo ( ) { int i [ 4 ] ; 16 ; 4 ; }", sizeof_(code)); } - void sizeof3() - { + void sizeof3() { const char code[] = "static int i[4];\n" "void f()\n" "{\n" @@ -946,8 +917,7 @@ private: ASSERT_EQUALS("static int i [ 4 ] ; void f ( ) { int i [ 10 ] ; 40 ; }", sizeof_(code)); } - void sizeof4() - { + void sizeof4() { { const char code[] = "int i[10];\n" "sizeof(i[0]);\n"; @@ -961,8 +931,7 @@ private: } } - void sizeof5() - { + void sizeof5() { const char code[] = "const char * names[2];" "for (int i = 0; i != sizeof(names[0]); i++)" @@ -972,8 +941,7 @@ private: ASSERT_EQUALS(expected.str(), sizeof_(code)); } - void sizeof6() - { + void sizeof6() { const char code[] = ";int i;\n" "sizeof(i);\n"; @@ -983,16 +951,14 @@ private: ASSERT_EQUALS(expected.str(), sizeof_(code)); } - void sizeof7() - { + void sizeof7() { const char code[] = ";INT32 i[10];\n" "sizeof(i[0]);\n"; ASSERT_EQUALS("; INT32 i [ 10 ] ; sizeof ( i [ 0 ] ) ;", sizeof_(code, true, Settings::Unspecified)); ASSERT_EQUALS("; int i [ 10 ] ; 4 ;", sizeof_(code, true, Settings::Win32A)); } - void sizeof8() - { + void sizeof8() { { const char code[] = "void f()\n" "{\n" @@ -1028,8 +994,7 @@ private: } } - void sizeof9() - { + void sizeof9() { // ticket #487 { const char code[] = "; const char *str = \"1\"; sizeof(str);"; @@ -1150,8 +1115,7 @@ private: } } - void sizeof10() - { + void sizeof10() { // ticket #809 const char code[] = "int m ; " "compat_ulong_t um ; " @@ -1160,8 +1124,7 @@ private: ASSERT_EQUALS(code, tok(code, true, Settings::Win32A)); } - void sizeof11() - { + void sizeof11() { // ticket #827 const char code[] = "void f()\n" "{\n" @@ -1192,8 +1155,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void sizeof12() - { + void sizeof12() { // ticket #827 const char code[] = "void f()\n" "{\n" @@ -1210,8 +1172,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void sizeof13() - { + void sizeof13() { // ticket #851 const char code[] = "int main()\n" "{\n" @@ -1235,8 +1196,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void sizeof14() - { + void sizeof14() { // ticket #954 const char code[] = "void f()\n" "{\n" @@ -1251,8 +1211,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void sizeof15() - { + void sizeof15() { // ticket #1020 tok("void f()\n" "{\n" @@ -1262,8 +1221,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sizeof16() - { + void sizeof16() { // ticket #1027 const char code[] = "void f()\n" "{\n" @@ -1274,8 +1232,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sizeof17() - { + void sizeof17() { // ticket #1050 const char code[] = "void f()\n" "{\n" @@ -1286,8 +1243,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sizeof18() - { + void sizeof18() { { std::ostringstream expected; expected << sizeof(short int); @@ -1429,8 +1385,7 @@ private: } } - void sizeof19() - { + void sizeof19() { // ticket #1891 - sizeof 'x' { const char code[] = "void f()\n" @@ -1455,8 +1410,7 @@ private: } } - void sizeof20() - { + void sizeof20() { // ticket #2024 - sizeof a) const char code[] = "struct struct_a {\n" " char a[20];\n" @@ -1473,8 +1427,7 @@ private: "}", tok(code)); } - void sizeof21() - { + void sizeof21() { // ticket #2232 - sizeof...(Args) const char code[] = "struct Internal {\n" " int operator()(const Args&... args) const {\n" @@ -1493,8 +1446,7 @@ private: tok(code); } - void sizeof22() - { + void sizeof22() { // ticket #2599 segmentation fault const char code[] = "sizeof\n"; @@ -1502,8 +1454,7 @@ private: tok(code); } - void sizeof23() - { + void sizeof23() { // ticket #2604 segmentation fault const char code[] = "sizeof <= A\n"; @@ -1511,15 +1462,13 @@ private: tok(code); } - void sizeof24() - { + void sizeof24() { const char code[] = "; struct AB ab; sizeof(ab)"; ASSERT_EQUALS("; struct AB ab ; 100", tok(code)); } - void sizeofsizeof() - { + void sizeofsizeof() { // ticket #1682 const char code[] = "void f()\n" "{\n" @@ -1529,8 +1478,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void casting() - { + void casting() { { const char code[] = "void f()\n" "{\n" @@ -1566,8 +1514,7 @@ private: } - void strlen1() - { + void strlen1() { ASSERT_EQUALS("4", tok("strlen(\"abcd\")")); { @@ -1605,8 +1552,7 @@ private: - void template1() - { + void template1() { const char code[] = "template void f(T val) { T a; }\n" "f(10);"; @@ -1616,8 +1562,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template2() - { + void template2() { const char code[] = "template class Fred { T a; };\n" "Fred fred;"; @@ -1628,8 +1573,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template3() - { + void template3() { const char code[] = "template class Fred { T data[sz]; };\n" "Fred fred;"; @@ -1640,8 +1584,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template4() - { + void template4() { const char code[] = "template class Fred { Fred(); };\n" "Fred fred;"; @@ -1652,8 +1595,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template5() - { + void template5() { const char code[] = "template class Fred { };\n" "template Fred::Fred() { }\n" "Fred fred;"; @@ -1666,8 +1608,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template6() - { + void template6() { const char code[] = "template class Fred { };\n" "Fred fred1;\n" "Fred fred2;"; @@ -1680,8 +1621,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template7() - { + void template7() { // A template class that is not used => no simplification { const char code[] = "template \n" @@ -1744,8 +1684,7 @@ private: } // Template definitions but no usage => no expansion - void template8() - { + void template8() { const char code[] = "template class A;\n" "template class B;\n" "\n" @@ -1768,8 +1707,7 @@ private: ASSERT_EQUALS("class A { ; } ;", sizeof_("class A{ template int foo(T d);};")); } - void template9() - { + void template9() { const char code[] = "template < typename T > class A { } ;\n" "\n" "void f ( ) {\n" @@ -1789,8 +1727,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template10() - { + void template10() { const char code[] = "template T * foo()\n" "{ return new T[ui]; }\n" "\n" @@ -1809,8 +1746,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template11() - { + void template11() { const char code[] = "template T * foo()\n" "{ return new T[ui]; }\n" "\n" @@ -1829,8 +1765,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template12() - { + void template12() { const char code[] = "template \n" "class A : public B\n" "{ };\n" @@ -1851,8 +1786,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template13() - { + void template13() { const char code[] = "class BB {};\n" "\n" "template \n" @@ -1878,8 +1812,7 @@ private: sizeof_(code); } - void template14() - { + void template14() { const char code[] = "template <> void foo()\n" "{ x(); }\n" "\n" @@ -1897,8 +1830,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template15() - { + void template15() { const char code[] = "template void a()\n" "{\n" " a();\n" @@ -1924,8 +1856,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template16() - { + void template16() { const char code[] = "template void a()\n" "{ }\n" "\n" @@ -1947,8 +1878,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template17() - { + void template17() { const char code[] = "template\n" "class Fred\n" "{\n" @@ -1964,8 +1894,7 @@ private: sizeof_(code); } - void template18() - { + void template18() { const char code[] = "template class foo { T a; };\n" "foo *f;"; @@ -1976,8 +1905,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template19() - { + void template19() { const char code[] = "template T & foo()\n" "{ static T temp; return temp; }\n" "\n" @@ -1996,8 +1924,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template20() - { + void template20() { // Ticket #1788 - the destructor implementation is lost const char code[] = "template class A\n" "{\n" @@ -2018,8 +1945,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template21() - { + void template21() { { const char code[] = "template struct Fred { T a; };\n" "Fred fred;"; @@ -2080,8 +2006,7 @@ private: } } - void template22() - { + void template22() { const char code[] = "template struct Fred { T a; };\n" "Fred fred;"; @@ -2092,8 +2017,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template23() - { + void template23() { const char code[] = "template void foo() { }\n" "void bar() {\n" " std::cout << (foo());\n" @@ -2108,8 +2032,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template24() - { + void template24() { // #2648 const char code[] = "template struct B\n" "{\n" @@ -2127,8 +2050,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void template25() - { + void template25() { const char code[] = "template struct B\n" "{\n" " int a[n];\n" @@ -2151,8 +2073,7 @@ private: } - void template26() - { + void template26() { // #2721 const char code[] = "template\n" "class A { public: T x; };\n" @@ -2165,14 +2086,12 @@ private: ASSERT_EQUALS("; C<2> a ; class C<2> : public A < char [ 2 ] > { }", sizeof_(code)); } - void template_unhandled() - { + void template_unhandled() { // An unhandled template usage should be simplified.. ASSERT_EQUALS("; x ( ) ;", sizeof_(";x();")); } - void template_default_parameter() - { + void template_default_parameter() { { const char code[] = "template \n" "class A\n" @@ -2256,8 +2175,7 @@ private: } } - void template_default_type() - { + void template_default_type() { const char code[] = "template \n" "class A\n" "{\n" @@ -2291,8 +2209,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void template_typename() - { + void template_typename() { { const char code[] = "template \n" "void foo(typename T::t *)\n" @@ -2314,8 +2231,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "test.c", "", false); std::ostringstream ostr; - for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) { ostr << tok1->str(); if (Token::Match(tok1, "%var% %var%")) ostr << " "; @@ -2324,8 +2240,7 @@ private: } } - void namespaces() - { + void namespaces() { { const char code[] = "using namespace std; namespace a{ namespace b{ void f(){} } }"; @@ -2360,8 +2275,7 @@ private: } - std::string simplifyIfAssign(const char code[]) - { + std::string simplifyIfAssign(const char code[]) { errout.str(""); Settings settings; // tokenize.. @@ -2378,8 +2292,7 @@ private: return ostr.str(); } - void ifassign1() - { + void ifassign1() { ASSERT_EQUALS("; a = b ; if ( a ) { ; }", simplifyIfAssign(";if(a=b);")); ASSERT_EQUALS("; a = b ( ) ; if ( a ) { ; }", simplifyIfAssign(";if((a=b()));")); ASSERT_EQUALS("; a = b ( ) ; if ( ! ( a ) ) { ; }", simplifyIfAssign(";if(!(a=b()));")); @@ -2391,8 +2304,7 @@ private: tok("void foo(A a) {if((a.c=b())>=0);}")); } - void ifAssignWithCast() - { + void ifAssignWithCast() { const char *code = "void foo()\n" "{\n" "FILE *f;\n" @@ -2413,8 +2325,7 @@ private: ASSERT_EQUALS(exptected, tok(code)); } - void whileAssign1() - { + void whileAssign1() { ASSERT_EQUALS("; a = b ; while ( a ) { b = 0 ; a = b ; }", simplifyIfAssign(";while(a=b) { b = 0; }")); ASSERT_EQUALS("; a . b = c ; while ( a . b ) { c = 0 ; a . b = c ; }", simplifyIfAssign(";while(a.b=c) { c=0; }")); ASSERT_EQUALS("struct hfs_bnode * node ; " @@ -2428,8 +2339,7 @@ private: tok("char *s; while (0 == (s=new char[10])) { }")); } - void whileAssign2() - { + void whileAssign2() { // #1909 - Internal error errout.str(""); tok("void f()\n" @@ -2443,8 +2353,7 @@ private: ASSERT_EQUALS("", errout.str()); } - std::string simplifyIfNot(const char code[]) - { + std::string simplifyIfNot(const char code[]) { errout.str(""); Settings settings; // tokenize.. @@ -2461,8 +2370,7 @@ private: return ostr.str(); } - void ifnot() - { + void ifnot() { ASSERT_EQUALS("if ( ! x )", simplifyIfNot("if(0==x)")); ASSERT_EQUALS("if ( ! x )", simplifyIfNot("if(x==0)")); ASSERT_EQUALS("if ( ! ( a = b ) )", simplifyIfNot("if(0==(a=b))")); @@ -2478,8 +2386,7 @@ private: - std::string simplifyLogicalOperators(const char code[]) - { + std::string simplifyLogicalOperators(const char code[]) { errout.str(""); Settings settings; // tokenize.. @@ -2494,15 +2401,13 @@ private: return ostr.str(); } - void not1() - { + void not1() { ASSERT_EQUALS("if ( ! p )", simplifyLogicalOperators("if (not p)")); ASSERT_EQUALS("if ( p && ! q )", simplifyLogicalOperators("if (p && not q)")); ASSERT_EQUALS("void foo ( not i )", simplifyLogicalOperators("void foo ( not i )")); } - void and1() - { + void and1() { ASSERT_EQUALS("if ( p && q ) { ; }", simplifyLogicalOperators("if (p and q) ;")); @@ -2519,8 +2424,7 @@ private: simplifyLogicalOperators("if (p and not q)")); } - void or1() - { + void or1() { ASSERT_EQUALS("if ( p || q ) { ; }", simplifyLogicalOperators("if (p or q) ;")); @@ -2537,8 +2441,7 @@ private: simplifyLogicalOperators("if (p or not q)")); } - void comma_keyword() - { + void comma_keyword() { { const char code[] = "void foo()\n" "{\n" @@ -2636,8 +2539,7 @@ private: } } - void remove_comma() - { + void remove_comma() { { const char code[] = "void f()\n" "{\n" @@ -2683,8 +2585,7 @@ private: } } - void conditionOperator() - { + void conditionOperator() { { const char code[] = "; x = a ? b : c;"; ASSERT_EQUALS("; if ( a ) { x = b ; } else { x = c ; }", tok(code)); @@ -2779,8 +2680,7 @@ private: } } - void calculations() - { + void calculations() { { const char code[] = "a[i+8+2]"; ASSERT_EQUALS("a [ i + 10 ]", tok(code)); @@ -2841,8 +2741,7 @@ private: } - void goto1() - { + void goto1() { { const char code[] = "void foo()\n" "{\n" @@ -2984,15 +2883,13 @@ private: } } - void goto2() - { + void goto2() { // Don't simplify goto inside function call (macro) const char code[] = "void f ( ) { slist_iter ( if ( a ) { goto dont_write ; } dont_write : ; x ( ) ; ) ; }"; ASSERT_EQUALS(code, tok(code)); } - void return1() - { + void return1() { ASSERT_EQUALS("void f ( ) { return ; }", tok("void f() { return; foo();}")); ASSERT_EQUALS("void f ( int n ) { if ( n ) { return ; } foo ( ) ; }",tok("void f(int n) { if (n) return; foo();}")); @@ -3007,8 +2904,7 @@ private: ASSERT_EQUALS("void f ( ) { MACRO ( return ; bar2 , foo ) }",tok("void f() { MACRO(return; bar2, foo) }")); } - void return2() - { + void return2() { const char code[] = "void f(){ " "if (k>0) goto label; " "return; " @@ -3025,8 +2921,7 @@ private: ASSERT_EQUALS("void f ( ) { if ( 0 < k ) { goto label ; } return ; { label : ; bar ( ) ; } }",tok(code)); } - void return3() - { + void return3() { const char code[] = "int f() { " "switch (x) { case 1: return 1; bar(); tack; { ticak(); return; } return; " "case 2: return 2; { random(); } tack(); " @@ -3035,8 +2930,7 @@ private: ASSERT_EQUALS("int f ( ) { switch ( x ) { case 1 : ; return 1 ; case 2 : ; return 2 ; } return 3 ; }",tok(code)); } - void return4() - { + void return4() { const char code[] = "int f() {" "switch (x) { case 1: return 1; bar(); tack; { ticak(); return; } return;" "case 2: switch(y) { case 1: return 0; bar2(); foo(); case 2: return 7; }" @@ -3048,8 +2942,7 @@ private: ASSERT_EQUALS(expected,tok(code)); } - void return5() - { + void return5() { const char code[] = "void foo () {" " switch (i) { case 0: switch (j) { case 0: return -1; }" " case 1: switch (j) { case -1: return -1; }" @@ -3063,8 +2956,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void strcat1() - { + void strcat1() { const char code[] = "; strcat(strcat(strcat(strcat(strcat(strcat(dst, \"this \"), \"\"), \"is \"), \"a \"), \"test\"), \".\");"; const char expect[] = "; " "strcat ( dst , \"this \" ) ; " @@ -3076,8 +2968,7 @@ private: ASSERT_EQUALS(expect, tok(code)); } - void strcat2() - { + void strcat2() { const char code[] = "; strcat(strcat(dst, foo[0]), \" \");"; const char expect[] = "; " "strcat ( dst , foo [ 0 ] ) ; " @@ -3086,8 +2977,7 @@ private: ASSERT_EQUALS(expect, tok(code)); } - void argumentsWithSameName() - { + void argumentsWithSameName() { // This code has syntax error, two variables can not have the same name { const char code[] = "void foo(x, x)\n" @@ -3106,16 +2996,14 @@ private: } } - void simplifyAtol() - { + void simplifyAtol() { ASSERT_EQUALS("a = std :: atol ( x ) ;", tok("a = std::atol(x);")); ASSERT_EQUALS("a = atol ( \"text\" ) ;", tok("a = atol(\"text\");")); ASSERT_EQUALS("a = 0 ;", tok("a = std::atol(\"0\");")); ASSERT_EQUALS("a = 10 ;", tok("a = atol(\"0xa\");")); } - void simplifyHexInString() - { + void simplifyHexInString() { ASSERT_EQUALS("\"a\"", tok("\"\\x61\"")); ASSERT_EQUALS("\"a\"", tok("\"\\141\"")); @@ -3137,8 +3025,7 @@ private: } - std::string simplifyTypedef(const char code[]) - { + std::string simplifyTypedef(const char code[]) { errout.str(""); Settings settings; @@ -3150,8 +3037,7 @@ private: tokenizer.simplifyTypedef(); std::string ret; - for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) - { + for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) { if (tok1 != tokenizer.tokens()) ret += " "; ret += tok1->str(); @@ -3162,8 +3048,7 @@ private: - void simplifyTypedef1() - { + void simplifyTypedef1() { const char code[] = "class A\n" "{\n" "public:\n" @@ -3194,8 +3079,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void simplifyTypedef2() - { + void simplifyTypedef2() { const char code[] = "class A;\n" "typedef A duplicate;\n" "class A\n" @@ -3216,8 +3100,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void simplifyTypedef3() - { + void simplifyTypedef3() { const char code[] = "class A {};\n" "typedef A duplicate;\n" "wchar_t foo()\n" @@ -3246,8 +3129,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void simplifyTypedef4() - { + void simplifyTypedef4() { const char code[] = "typedef int s32;\n" "typedef unsigned int u32;\n" "void f()\n" @@ -3268,8 +3150,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef5() - { + void simplifyTypedef5() { // ticket #780 const char code[] = "typedef struct yy_buffer_state *YY_BUFFER_STATE;\n" @@ -3288,8 +3169,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef6() - { + void simplifyTypedef6() { // ticket #983 const char code[] = "namespace VL {\n" @@ -3306,8 +3186,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef7() - { + void simplifyTypedef7() { const char code[] = "typedef int abc ; " "Fred :: abc f ;"; const char expected[] = @@ -3316,8 +3195,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef8() - { + void simplifyTypedef8() { const char code[] = "typedef int INT;\n" "typedef unsigned int UINT;\n" "typedef int * PINT;\n" @@ -3349,8 +3227,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef9() - { + void simplifyTypedef9() { const char code[] = "typedef struct s S, * PS;\n" "typedef struct t { int a; } T, *TP;\n" "typedef struct { int a; } U;\n" @@ -3377,8 +3254,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef10() - { + void simplifyTypedef10() { const char code[] = "typedef union s S, * PS;\n" "typedef union t { int a; float b ; } T, *TP;\n" "typedef union { int a; float b; } U;\n" @@ -3405,8 +3281,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef11() - { + void simplifyTypedef11() { const char code[] = "typedef enum { a = 0 , b = 1 , c = 2 } abc;\n" "typedef enum xyz { x = 0 , y = 1 , z = 2 } XYZ;\n" "abc e1;\n" @@ -3420,8 +3295,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef12() - { + void simplifyTypedef12() { const char code[] = "typedef vector V1;\n" "typedef std::vector V2;\n" "typedef std::vector > V3;\n" @@ -3441,8 +3315,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef13() - { + void simplifyTypedef13() { // ticket # 1167 const char code[] = "typedef std::pair Func;" "typedef std::vector CallQueue;" @@ -3461,8 +3334,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef14() - { + void simplifyTypedef14() { // ticket # 1232 const char code[] = "template struct E" "{" @@ -3489,8 +3361,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef15() - { + void simplifyTypedef15() { { const char code[] = "typedef char frame[10];\n" "frame f;"; @@ -3514,8 +3385,7 @@ private: } } - void simplifyTypedef16() - { + void simplifyTypedef16() { // ticket # 1252 const char code[] = "typedef char MOT8;\n" "typedef MOT8 CHFOO[4096];\n" @@ -3536,8 +3406,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef17() - { + void simplifyTypedef17() { const char code[] = "typedef char * PCHAR, CHAR;\n" "PCHAR pc;\n" "CHAR c;"; @@ -3550,8 +3419,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef18() - { + void simplifyTypedef18() { const char code[] = "typedef vector a;\n" "a b;\n"; @@ -3568,8 +3436,7 @@ private: ASSERT_EQUALS(true, tokenizer.validate()); } - void simplifyTypedef19() - { + void simplifyTypedef19() { { // ticket #1275 const char code[] = "typedef struct {} A, *B, **C;\n" @@ -3615,8 +3482,7 @@ private: } } - void simplifyTypedef20() - { + void simplifyTypedef20() { // ticket #1284 const char code[] = "typedef jobject invoke_t (jobject, Proxy *, Method *, JArray< jobject > *);"; @@ -3633,8 +3499,7 @@ private: ASSERT_EQUALS(true, tokenizer.validate()); } - void simplifyTypedef21() - { + void simplifyTypedef21() { const char code[] = "typedef void (* PF)();\n" "typedef void * (* PFV)(void *);\n" "PF pf;\n" @@ -3649,8 +3514,7 @@ private: ASSERT_EQUALS(expected, simplifyTypedef(code)); } - void simplifyTypedef22() - { + void simplifyTypedef22() { { const char code[] = "class Fred {\n" " typedef void (*testfp)();\n" @@ -3738,8 +3602,7 @@ private: } } - void simplifyTypedef23() - { + void simplifyTypedef23() { const char code[] = "typedef bool (*Callback) (int i);\n" "void addCallback(Callback callback) { }\n" "void addCallback1(Callback callback, int j) { }"; @@ -3752,8 +3615,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef24() - { + void simplifyTypedef24() { { const char code[] = "typedef int (*fp)();\n" "void g( fp f )\n" @@ -3789,8 +3651,7 @@ private: } } - void simplifyTypedef25() - { + void simplifyTypedef25() { { // ticket #1298 const char code[] = "typedef void (*fill_names_f) (const char *);\n" @@ -3823,8 +3684,7 @@ private: } } - void simplifyTypedef26() - { + void simplifyTypedef26() { { const char code[] = "typedef void (*Callback) ();\n" "void addCallback(Callback (*callback)());"; @@ -3851,8 +3711,7 @@ private: } } - void simplifyTypedef27() - { + void simplifyTypedef27() { // ticket #1316 const char code[] = "int main()\n" "{\n" @@ -3870,8 +3729,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef28() - { + void simplifyTypedef28() { const char code[] = "typedef std::pair (*F)(double);\n" "F f;"; @@ -3882,8 +3740,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef29() - { + void simplifyTypedef29() { const char code[] = "typedef int array [ice_or::value, is_int::value>::value ? 1 : -1];\n" "typedef int array1 [N];\n" "typedef int array2 [N][M];\n" @@ -3905,8 +3762,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef30() - { + void simplifyTypedef30() { const char code[] = "typedef ::std::list int_list;\n" "typedef ::std::list::iterator int_list_iterator;\n" "typedef ::std::list int_list_array[10];\n" @@ -3923,8 +3779,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef31() - { + void simplifyTypedef31() { { const char code[] = "class A {\n" "public:\n" @@ -3972,8 +3827,7 @@ private: } } - void simplifyTypedef32() - { + void simplifyTypedef32() { const char code[] = "typedef char CHAR;\n" "typedef CHAR * LPSTR;\n" "typedef const CHAR * LPCSTR;\n" @@ -3990,8 +3844,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef33() - { + void simplifyTypedef33() { const char code[] = "class A {\n" "public:\n" " typedef char CHAR_A;\n" @@ -4052,8 +3905,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef34() - { + void simplifyTypedef34() { // ticket #1411 const char code[] = "class X { };\n" "typedef X (*foofunc)(const X&);\n" @@ -4072,8 +3924,7 @@ private: } // Check simplifyTypedef - void checkSimplifyTypedef(const char code[]) - { + void checkSimplifyTypedef(const char code[]) { errout.str(""); // Tokenize.. Settings settings; @@ -4085,8 +3936,7 @@ private: tokenizer.tokenize(istr, "test.cpp"); } - void simplifyTypedef35() - { + void simplifyTypedef35() { const char code[] = "typedef int A;\n" "class S\n" "{\n" @@ -4164,8 +4014,7 @@ private: "[test.cpp:24] -> [test.cpp:1]: (style) Typedef 'A' hides typedef with same name\n", errout.str()); } - void simplifyTypedef36() - { + void simplifyTypedef36() { // ticket #1434 const char code[] = "typedef void (*TIFFFaxFillFunc)();\n" "void f(va_list ap)\n" @@ -4180,8 +4029,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyTypedef37() - { + void simplifyTypedef37() { { // ticket #1449 const char code[] = "template class V {};\n" @@ -4210,8 +4058,7 @@ private: } } - void simplifyTypedef38() - { + void simplifyTypedef38() { const char code[] = "typedef C A;\n" "struct AB : public A, public B { };"; const char expected[] = "; struct AB : public C , public B { } ;"; @@ -4221,8 +4068,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef39() - { + void simplifyTypedef39() { const char code[] = "typedef int A;\n" "template ::value;"; const char expected[] = ";"; @@ -4232,8 +4078,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef40() - { + void simplifyTypedef40() { const char code[] = "typedef int A;\n" "typedef int B;\n" "template class C { };"; @@ -4288,8 +4133,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef41() - { + void simplifyTypedef41() { // ticket #1488 checkSimplifyTypedef("class Y;\n" "class X\n" @@ -4300,8 +4144,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef42() - { + void simplifyTypedef42() { // ticket #1506 checkSimplifyTypedef("typedef struct A { } A;\n" "struct A;"); @@ -4316,8 +4159,7 @@ private: ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:1]: (style) Class 'A' forward declaration unnecessary, already declared\n", errout.str()); } - void simplifyTypedef43() - { + void simplifyTypedef43() { // ticket #1588 { const char code[] = "typedef struct foo A;\n" @@ -4377,8 +4219,7 @@ private: } } - void simplifyTypedef44() - { + void simplifyTypedef44() { { const char code[] = "typedef std::map Map;\n" "class MyMap : public Map\n" @@ -4465,8 +4306,7 @@ private: } } - void simplifyTypedef45() - { + void simplifyTypedef45() { // ticket # 1613 const char code[] = "void fn() {\n" " typedef foo<> bar;\n" @@ -4477,8 +4317,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef46() - { + void simplifyTypedef46() { const char code[] = "typedef const struct A { int a; } * AP;\n" "AP ap;\n"; @@ -4488,8 +4327,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef47() - { + void simplifyTypedef47() { { const char code[] = "typedef std::pair const I;\n" "I i;"; @@ -4511,8 +4349,7 @@ private: } } - void simplifyTypedef48() // ticket #1673 - { + void simplifyTypedef48() { // ticket #1673 const char code[] = "typedef struct string { } string;\n" "void foo (LIST *module_name)\n" "{\n" @@ -4528,8 +4365,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef49() // ticket #1691 - { + void simplifyTypedef49() { // ticket #1691 const char code[] = "class Class2 {\n" "typedef const Class & Const_Reference;\n" "void some_method (Const_Reference x) const {}\n" @@ -4545,8 +4381,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef50() - { + void simplifyTypedef50() { const char code[] = "typedef char (* type1)[10];\n" "typedef char (& type2)[10];\n" "typedef char (& type3)[x];\n" @@ -4567,8 +4402,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef51() - { + void simplifyTypedef51() { const char code[] = "class A { public: int i; };\n" "typedef const char (A :: * type1);\n" "type1 t1 = &A::i;"; @@ -4579,8 +4413,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef52() // ticket #1782 - { + void simplifyTypedef52() { // ticket #1782 { const char code[] = "typedef char (* type1)[10];\n" "type1 foo() { }"; @@ -4604,8 +4437,7 @@ private: } } - void simplifyTypedef53() // ticket #1801 - { + void simplifyTypedef53() { // ticket #1801 { const char code[] = "typedef int ( * int ( * ) ( ) ) ( ) ;"; @@ -4630,8 +4462,7 @@ private: } } - void simplifyTypedef54() // ticket #1814 - { + void simplifyTypedef54() { // ticket #1814 const char code[] = "void foo()\n" "{\n" " typedef std::basic_string string_type;\n" @@ -4649,8 +4480,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef55() - { + void simplifyTypedef55() { const char code[] = "typedef volatile unsigned long * const hwreg_t ;\n" "typedef void *const t1[2];\n" "typedef int*const *_Iterator;\n" @@ -4670,8 +4500,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef56() // ticket #1829 - { + void simplifyTypedef56() { // ticket #1829 const char code[] = "struct C {\n" " typedef void (*fptr)();\n" " const fptr pr;\n" @@ -4691,8 +4520,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef57() // ticket #1846 - { + void simplifyTypedef57() { // ticket #1846 const char code[] = "void foo {\n" " typedef int A;\n" " A a = A(1) * A(2);\n" @@ -4710,8 +4538,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef58() // ticket #1963 - { + void simplifyTypedef58() { // ticket #1963 { const char code[] = "typedef int vec2_t[2];\n" "vec2_t coords[4] = {1,2,3,4,5,6,7,8};\n"; @@ -4741,8 +4568,7 @@ private: } } - void simplifyTypedef59() // ticket #2011 - { + void simplifyTypedef59() { // ticket #2011 const char code[] = "template class SomeTemplateClass {\n" " typedef void (SomeTemplateClass::*MessageDispatcherFunc)(SerialInputMessage&);\n" "};\n"; @@ -4755,8 +4581,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef60() // ticket #2035 - { + void simplifyTypedef60() { // ticket #2035 const char code[] = "typedef enum {qfalse, qtrue} qboolean;\n" "typedef qboolean (*localEntitiyAddFunc_t) (struct le_s * le, entity_t * ent);\n" "void f()\n" @@ -4773,8 +4598,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef61() // ticket #2074 and 2075 - { + void simplifyTypedef61() { // ticket #2074 and 2075 const char code1[] = "typedef unsigned char (*Mf_GetIndexByte_Func) (void);\n" "typedef const unsigned char * (*Mf_GetPointerToCurrentPos_Func)(void);\n"; @@ -4790,8 +4614,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef62() // ticket #2082 - { + void simplifyTypedef62() { // ticket #2082 const char code1[] = "typedef char TString[256];\n" "void f()\n" "{\n" @@ -4849,8 +4672,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef63() // ticket #2175 'typedef float x[3];' - { + void simplifyTypedef63() { // ticket #2175 'typedef float x[3];' const char code[] = "typedef float x[3];\n" "x a,b,c;\n"; const std::string actual(sizeof_(code)); @@ -4858,8 +4680,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef64() - { + void simplifyTypedef64() { const char code[] = "typedef __typeof__(__type1() + __type2()) __type;" "__type t;\n"; const std::string actual(sizeof_(code)); @@ -4867,8 +4688,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef65() // ticket #2314 - { + void simplifyTypedef65() { // ticket #2314 const char code[] = "typedef BAR Foo; \n" "int main() { \n" " Foo b(0); \n" @@ -4879,16 +4699,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef66() // ticket #2341 - { + void simplifyTypedef66() { // ticket #2341 const char code[] = "typedef long* GEN;\n" "extern GEN (*foo)(long);"; const std::string actual(sizeof_(code)); ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef67() // ticket #2354 - { + void simplifyTypedef67() { // ticket #2354 const char code[] = "typedef int ( * Function ) ( ) ;\n" "void f ( ) {\n" " ((Function * (*) (char *, char *, int, int)) global[6]) ( \"assoc\", \"eggdrop\", 106, 0);\n" @@ -4901,8 +4719,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef68() // ticket #2355 - { + void simplifyTypedef68() { // ticket #2355 const char code[] = "typedef FMAC1 void (* a) ();\n" "void *(*b) ();\n"; const std::string actual(sizeof_(code)); @@ -4910,8 +4727,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef69() // ticket #2348 - { + void simplifyTypedef69() { // ticket #2348 const char code[] = "typedef int (*CompilerHook)();\n" "typedef struct VirtualMachine \n" "{\n" @@ -4926,8 +4742,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef70() // ticket #2348 - { + void simplifyTypedef70() { // ticket #2348 const char code[] = "typedef int pread_f ( int ) ;\n" "pread_f *(*test_func)(char *filename);\n"; const std::string expected = "; " @@ -4936,8 +4751,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef71() // ticket #2348 - { + void simplifyTypedef71() { // ticket #2348 { const char code[] = "typedef int RexxFunctionHandler();\n" "RexxFunctionHandler *(efuncs[1]);\n"; @@ -4956,8 +4770,7 @@ private: } } - void simplifyTypedef72() // ticket #2374 - { + void simplifyTypedef72() { // ticket #2374 // inline operator { const char code[] = "class Fred {\n" @@ -5016,8 +4829,7 @@ private: } } - void simplifyTypedef73() // ticket #2412 - { + void simplifyTypedef73() { // ticket #2412 const char code[] = "struct B {};\n" "typedef struct A : public B {\n" " void f();\n" @@ -5030,8 +4842,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef74() // ticket #2414 - { + void simplifyTypedef74() { // ticket #2414 const char code[] = "typedef long (*state_func_t)(void);\n" "typedef state_func_t (*state_t)(void);\n" "state_t current_state = death;\n" @@ -5043,31 +4854,27 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef75() // ticket #2426 - { + void simplifyTypedef75() { // ticket #2426 const char code[] = "typedef _Packed struct S { long l; }; \n"; const std::string expected = ";"; ASSERT_EQUALS(expected, sizeof_(code)); ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef76() // ticket #2453 segmentation fault - { + void simplifyTypedef76() { // ticket #2453 segmentation fault const char code[] = "void f1(typedef int x) {}\n"; const std::string expected = "void f1 ( typedef int x ) { }"; ASSERT_EQUALS(expected, sizeof_(code)); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void simplifyTypedef77() // ticket #2554 - { + void simplifyTypedef77() { // ticket #2554 const char code[] = "typedef char Str[10]; int x = sizeof(Str);\n"; const std::string expected = "; int x ; x = 10 ;"; ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef78() // ticket #2568 - { + void simplifyTypedef78() { // ticket #2568 const char code[] = "typedef struct A A_t;\n" "A_t a;\n" "typedef struct A { } A_t;\n" @@ -5076,8 +4883,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef79() // ticket #2348 - { + void simplifyTypedef79() { // ticket #2348 const char code[] = "typedef int (Tcl_ObjCmdProc) (int x);\n" "typedef struct LangVtab\n" "{\n" @@ -5091,8 +4897,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef80() // ticket #2587 - { + void simplifyTypedef80() { // ticket #2587 const char code[] = "typedef struct s { };\n" "void f() {\n" " sizeof(struct s);\n" @@ -5108,8 +4913,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef81() // ticket #2603 segmentation fault - { + void simplifyTypedef81() { // ticket #2603 segmentation fault checkSimplifyTypedef("typedef\n"); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); @@ -5117,8 +4921,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void simplifyTypedef82() // ticket #2403 - { + void simplifyTypedef82() { // ticket #2403 checkSimplifyTypedef("class A {\n" "public:\n" " typedef int F(int idx);\n" @@ -5135,8 +4938,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef83() // ticket #2620 - { + void simplifyTypedef83() { // ticket #2620 const char code[] = "typedef char Str[10];\n" "void f(Str &cl) { }\n"; @@ -5147,8 +4949,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedef84() // ticket #2630 (segmentation fault) - { + void simplifyTypedef84() { // ticket #2630 (segmentation fault) const char code1[] = "typedef y x () x\n"; checkSimplifyTypedef(code1); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); @@ -5162,8 +4963,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void simplifyTypedef85() // ticket #2651 - { + void simplifyTypedef85() { // ticket #2651 const char code[] = "typedef FOO ((BAR)(void, int, const int, int*));\n"; const char expected[] = ";"; checkSimplifyTypedef(code); @@ -5171,8 +4971,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef86() // ticket #2581 - { + void simplifyTypedef86() { // ticket #2581 const char code[] = "class relational {\n" " typedef void (safe_bool_helper::*safe_bool)();\n" "public:\n" @@ -5190,8 +4989,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef87() // ticket #2651 - { + void simplifyTypedef87() { // ticket #2651 const char code[] = "typedef FOO (*(*BAR)(void, int, const int, int*));\n"; const char expected[] = ";"; checkSimplifyTypedef(code); @@ -5199,8 +4997,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef88() // ticket #2675 - { + void simplifyTypedef88() { // ticket #2675 const char code[] = "typedef short int (*x)(...);\n"; const char expected[] = ";"; checkSimplifyTypedef(code); @@ -5208,8 +5005,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef89() // ticket #2717 - { + void simplifyTypedef89() { // ticket #2717 const char code[] = "class Fred {\n" " typedef void f(int) const;\n" " f func;\n" @@ -5220,8 +5016,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef90() // ticket #2718 - { + void simplifyTypedef90() { // ticket #2718 const char code[] = "typedef int IA[2];\n" "void f(const IA&) {};\n"; const char expected[] = "; void f ( const int ( & ) [ 2 ] ) { } ;"; @@ -5230,8 +5025,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef91() // ticket #2716 - { + void simplifyTypedef91() { // ticket #2716 const char code1[] = "namespace NS {\n" " typedef int (*T)();\n" " class A {\n" @@ -5329,8 +5123,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef92() // ticket #2736 (segmentation fault) - { + void simplifyTypedef92() { // ticket #2736 (segmentation fault) const char code[] = "typedef long Long;\n" "namespace NS {\n" "}\n"; @@ -5343,8 +5136,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef93() // ticket #2738 (syntax error) - { + void simplifyTypedef93() { // ticket #2738 (syntax error) const char code[] = "struct s { double x; };\n" "typedef struct s (*binop) (struct s, struct s);\n"; const char expected[] = "struct s { double x ; } ;"; @@ -5354,8 +5146,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef94() // ticket #1982 - { + void simplifyTypedef94() { // ticket #1982 const char code1[] = "class A {\n" "public:\n" " typedef struct {\n" @@ -5414,8 +5205,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef95() // ticket #2844 - { + void simplifyTypedef95() { // ticket #2844 const char code[] = "class symbol_table {\n" "public:\n" " typedef expression_error::error_code (*valid_func)(void *cbparam, const char *name, expression_space space);\n" @@ -5432,23 +5222,20 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef96() // ticket #2886 (segmentation fault) - { + void simplifyTypedef96() { // ticket #2886 (segmentation fault) const char code[] = "typedef struct x { }\n"; sizeof_(code); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void simplifyTypedef97() // ticket #2983 (segmentation fault) - { + void simplifyTypedef97() { // ticket #2983 (segmentation fault) const char code[] = "typedef x y\n" "(A); y\n"; sizeof_(code); ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef98() // ticket #2963 - { + void simplifyTypedef98() { // ticket #2963 const char code[] = "#define X type ## __LINE__\n" "typedef int X;\n" "typedef int X;\n"; @@ -5456,8 +5243,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef99() // ticket #2999 - { + void simplifyTypedef99() { // ticket #2999 const char code[] = "typedef struct Fred Fred;\n" "struct Fred { };\n"; sizeof_(code); @@ -5469,8 +5255,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef100() // ticket #3000 - { + void simplifyTypedef100() { // ticket #3000 const char code[] = "typedef struct Fred { } Fred;\n" "Fred * foo() {\n" " Fred *fred;\n" @@ -5481,16 +5266,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef101() // ticket #3003 (segmentation fault) - { + void simplifyTypedef101() { // ticket #3003 (segmentation fault) const char code[] = "typedef a x[];\n" "y = x\n"; sizeof_(code); ASSERT_EQUALS("[test.cpp:2]: (error) syntax error\n", errout.str()); } - void simplifyTypedef102() // ticket #3004 - { + void simplifyTypedef102() { // ticket #3004 const char code[] = "typedef struct { } Fred;\n" "void foo()\n" "{\n" @@ -5500,8 +5283,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef103() // ticket #3007 - { + void simplifyTypedef103() { // ticket #3007 const char code[] = "typedef struct { } Fred;\n" "void foo()\n" "{\n" @@ -5511,15 +5293,13 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedef104() // ticket #3070 - { + void simplifyTypedef104() { // ticket #3070 const char code[] = "typedef int (*in_func) (void FAR *, unsigned char FAR * FAR *);\n"; ASSERT_EQUALS(";", sizeof_(code)); ASSERT_EQUALS("", errout.str()); } - void simplifyTypedefFunction1() - { + void simplifyTypedefFunction1() { { const char code[] = "typedef void (*my_func)();\n" "std::queue func_queue;"; @@ -5805,8 +5585,7 @@ private: } } - void simplifyTypedefFunction2() // ticket #1685 - { + void simplifyTypedefFunction2() { // ticket #1685 const char code[] = "typedef void voidfn (int);\n" "voidfn xxx;"; @@ -5816,8 +5595,7 @@ private: ASSERT_EQUALS(expected, sizeof_(code)); } - void simplifyTypedefFunction3() - { + void simplifyTypedefFunction3() { { const char code[] = "typedef C func1();\n" "typedef C (* func2)();\n" @@ -6007,8 +5785,7 @@ private: } } - void simplifyTypedefFunction4() - { + void simplifyTypedefFunction4() { const char code[] = "typedef int ( * ( * type1 ) ( bool ) ) ( int , int ) ;\n" "typedef int ( * ( type2 ) ( bool ) ) ( int , int ) ;\n" "typedef int ( * type3 ( bool ) ) ( int , int ) ;\n" @@ -6027,8 +5804,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedefFunction5() - { + void simplifyTypedefFunction5() { const char code[] = "typedef int ( * type1 ) ( float ) ;\n" "typedef int ( * const type2 ) ( float ) ;\n" "typedef int ( * volatile type3 ) ( float ) ;\n" @@ -6074,8 +5850,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedefFunction6() - { + void simplifyTypedefFunction6() { const char code[] = "typedef void (*testfp)();\n" "struct Fred\n" "{\n" @@ -6105,8 +5880,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedefFunction7() - { + void simplifyTypedefFunction7() { const char code[] = "typedef void ( __gnu_cxx :: _SGIAssignableConcept < _Tp > :: * _func_Tp_SGIAssignableConcept ) () ;" "_func_Tp_SGIAssignableConcept X;\n"; @@ -6120,8 +5894,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyTypedefFunction8() - { + void simplifyTypedefFunction8() { // #2376 - internal error const char code[] = "typedef int f_expand(const nrv_byte *);\n" "void f(f_expand *(*get_fexp(int))){}\n"; @@ -6129,13 +5902,11 @@ private: ASSERT_EQUALS("", errout.str()); // make sure that there is no internal error } - void reverseArraySyntax() - { + void reverseArraySyntax() { ASSERT_EQUALS("a [ 13 ]", tok("13[a]")); } - void simplify_numeric_condition() - { + void simplify_numeric_condition() { { const char code[] = "void f()\n" @@ -6225,8 +5996,7 @@ private: } } - void simplify_condition() - { + void simplify_condition() { { const char code[] = "void f(int a)\n" @@ -6265,8 +6035,7 @@ private: } - void pointeralias1() - { + void pointeralias1() { { const char code[] = "void f()\n" "{\n" @@ -6351,8 +6120,7 @@ private: } } - void pointeralias2() - { + void pointeralias2() { const char code[] = "void f()\n" "{\n" " int i;\n" @@ -6362,8 +6130,7 @@ private: ASSERT_EQUALS("void f ( ) { int i ; return i ; }", tok(code)); } - void pointeralias3() - { + void pointeralias3() { const char code[] = "void f()\n" "{\n" " int i, j, *p;\n" @@ -6381,8 +6148,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void pointeralias4() - { + void pointeralias4() { const char code[] = "void f()\n" "{\n" " int a[10];\n" @@ -6398,8 +6164,7 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void pointeralias5() - { + void pointeralias5() { const char code[] = "int f()\n" "{\n" " int i;\n" @@ -6414,21 +6179,18 @@ private: ASSERT_EQUALS(expected, tok(code)); } - void reduceConstness() - { + void reduceConstness() { ASSERT_EQUALS("char * p ;", tok("char * const p;")); } - void while0() - { + void while0() { ASSERT_EQUALS("; x = 1 ;", tok("; do { x = 1 ; } while (0);")); ASSERT_EQUALS("; do { continue ; } while ( false ) ;", tok("; do { continue ; } while (0);")); ASSERT_EQUALS("; do { break ; } while ( false ) ;", tok("; do { break; } while (0);")); ASSERT_EQUALS(";", tok("; while (false) { a; }")); } - void while0for() - { + void while0for() { // for (condition is always false) ASSERT_EQUALS("void f ( ) { ; }", tok("void f() { int i; for (i = 0; i < 0; i++) { a; } }")); //ticket #3140 @@ -6440,40 +6202,35 @@ private: ASSERT_EQUALS("void f ( ) { }", tok("void f() { for (signed long long i = 0; i < 0; i++) { a; } }")); } - void while1() - { + void while1() { // ticket #1197 const char code[] = "void do {} while (0) { }"; const char expected[] = "void { }"; ASSERT_EQUALS(expected, tok(code)); } - void enum1() - { + void enum1() { const char code[] = "enum A { a, b, c }; A c1 = c;"; const char expected[] = "; int c1 ; c1 = 2 ;"; ASSERT_EQUALS(expected, tok(code, false)); } - void enum2() - { + void enum2() { const char code[] = "enum A { a, }; int array[a];"; const char expected[] = "; int array [ 0 ] ;"; ASSERT_EQUALS(expected, tok(code, false)); } - void enum3() - { + void enum3() { const char code[] = "enum { a, }; int array[a];"; const char expected[] = "; int array [ 0 ] ;"; ASSERT_EQUALS(expected, tok(code, false)); } - void enum4() - { + void enum4() { { const char code[] = "class A {\n" "public:\n" @@ -6523,8 +6280,7 @@ private: } } - void enum5() - { + void enum5() { const char code[] = "enum ABC {\n" " a = sizeof(int),\n" " b = 1 + a,\n" @@ -6549,15 +6305,13 @@ private: ASSERT_EQUALS("; int sum ; sum = 508 ;", tok(code, true)); } - void enum6() - { + void enum6() { const char code[] = "enum { a = MAC(A, B, C) }; void f(a) { }"; const char expected[] = "; void f ( MAC ( A , B , C ) ) { }"; ASSERT_EQUALS(expected, tok(code, false)); } - void enum7() - { + void enum7() { { // ticket 1388 const char code[] = "enum FOO {A,B,C};\n" @@ -6585,8 +6339,7 @@ private: } // Check simplifyEnum - void checkSimplifyEnum(const char code[]) - { + void checkSimplifyEnum(const char code[]) { errout.str(""); // Tokenize.. Settings settings; @@ -6598,8 +6351,7 @@ private: tokenizer.simplifyTokenList(); } - void enum8() - { + void enum8() { // ticket 1388 checkSimplifyEnum("enum Direction {N=100,E,S,W,ALL};\n" "template class EF_Vector{\n" @@ -6640,8 +6392,7 @@ private: "[test.cpp:23] -> [test.cpp:1]: (style) Template parameter 'S' hides enumerator with same name\n", errout.str()); } - void enum9() - { + void enum9() { // ticket 1404 checkSimplifyEnum("class XX {\n" "public:\n" @@ -6656,8 +6407,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void enum10() - { + void enum10() { // ticket 1445 const char code[] = "enum {\n" "SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1, \n" @@ -6669,8 +6419,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void enum11() - { + void enum11() { const char code[] = "int main()\n" "{\n" " enum { u, v };\n" @@ -6688,8 +6437,7 @@ private: "[test.cpp:4] -> [test.cpp:3]: (style) Variable 'v' hides enumerator with same name\n", errout.str()); } - void enum12() - { + void enum12() { const char code[] = "enum fred { a, b };\n" "void foo()\n" "{\n" @@ -6699,8 +6447,7 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void enum13() - { + void enum13() { const char code[] = "enum ab { ENTRY(1, a = 0), ENTRY(2, b) };\n" "void foo()\n" "{\n" @@ -6710,16 +6457,14 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void enum14() - { + void enum14() { const char code[] = "enum ab { a };\n" "ab"; const char expected[] = "; ab"; ASSERT_EQUALS(expected, tok(code, false)); } - void enum15() // C++0x features - { + void enum15() { // C++0x features { const char code[] = "enum : char { a = 99 };\n" "char c1 = a;"; @@ -6763,15 +6508,13 @@ private: } } - void enum16() // ticket #1988 - { + void enum16() { // ticket #1988 const char code[] = "enum D : auto * { FF = 0 };"; checkSimplifyEnum(code); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void enum17() // ticket #2381 - { + void enum17() { // ticket #2381 // if header is included twice its enums will be duplicated const char code[] = "enum ab { a=0, b };" "enum ab { a=0, b };\n"; @@ -6779,35 +6522,30 @@ private: ASSERT_EQUALS("", errout.str()); } - void enum18() // ticket #2466 - array with same name as enum constant - { + void enum18() { // ticket #2466 - array with same name as enum constant const char code[] = "enum ab { a=0, b };\n" "void f() { a[0]; }\n"; ASSERT_EQUALS("; void f ( ) { a [ 0 ] ; }", tok(code, false)); } - void enum19() // ticket #2536 - { + void enum19() { // ticket #2536 const char code[] = "enum class E1;\n" "enum class E2 : int;\n"; ASSERT_EQUALS(";", tok(code, false)); } - void enum20() // ticket #2600 segmentation fault - { + void enum20() { // ticket #2600 segmentation fault const char code[] = "enum { const }\n"; ASSERT_EQUALS(";", tok(code, false)); } - void enum21() // ticket #2720 syntax error - { + void enum21() { // ticket #2720 syntax error const char code[] = "enum E2 : signed const short { };\n"; ASSERT_EQUALS(";", tok(code, false)); ASSERT_EQUALS("", errout.str()); } - void enum22() // ticket #2745 - { + void enum22() { // ticket #2745 const char code[] = "enum en { x = 0 };\n" "void f() {\n" " int x = 0;\n" @@ -6821,8 +6559,7 @@ private: "[test.cpp:6] -> [test.cpp:1]: (style) Function parameter 'x' hides enumerator with same name\n", errout.str()); } - void enum23() // ticket #2804 - { + void enum23() { // ticket #2804 const char code[] = "enum Enumerator : std::uint8_t { ITEM1, ITEM2, ITEM3 };\n" "Enumerator e = ITEM3;\n"; const char expected[] = "; std :: uint8_t e ; e = 2 ;"; @@ -6830,8 +6567,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void enum24() // ticket #2828 - { + void enum24() { // ticket #2828 const char code[] = "enum EnumName { STYLE = 0x0001 };\n" "void f(long style) {\n" " if (style & STYLE) { }\n" @@ -6841,29 +6577,25 @@ private: ASSERT_EQUALS("", errout.str()); } - void enum25() // ticket #2966 (segmentation fault) - { + void enum25() { // ticket #2966 (segmentation fault) const char code[] = "enum x :\n"; tok(code, false); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void enum26() // ticket #2975 (segmentation fault) - { + void enum26() { // ticket #2975 (segmentation fault) const char code[] = "enum E {} e enum\n"; tok(code, false); ASSERT_EQUALS("", errout.str()); } - void enum27() // ticket #3005 (segmentation fault) - { + void enum27() { // ticket #3005 (segmentation fault) const char code[] = "enum : x\n"; tok(code, false); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void removestd() - { + void removestd() { ASSERT_EQUALS("; strcpy ( a , b ) ;", tok("; std::strcpy(a,b);")); ASSERT_EQUALS("; strcat ( a , b ) ;", tok("; std::strcat(a,b);")); ASSERT_EQUALS("; strncpy ( a , b , 10 ) ;", tok("; std::strncpy(a,b,10);")); @@ -6872,8 +6604,7 @@ private: ASSERT_EQUALS("; malloc ( 10 ) ;", tok("; std::malloc(10);")); } - void simplifyInitVar() - { + void simplifyInitVar() { // ticket #1005 - int *p(0); => int *p = 0; { const char code[] = "void foo() { int *p(0); }"; @@ -6891,16 +6622,14 @@ private: } } - void simplifyReference() - { + void simplifyReference() { ASSERT_EQUALS("void f ( ) { int a ; a ++ ; }", tok("void f() { int a; int &b(a); b++; }")); ASSERT_EQUALS("void f ( ) { int a ; a ++ ; }", tok("void f() { int a; int &b = a; b++; }")); } - void simplifyRealloc() - { + void simplifyRealloc() { ASSERT_EQUALS("; free ( p ) ; p = 0 ;", tok("; p = realloc(p,0);")); ASSERT_EQUALS("; p = malloc ( 100 ) ;", @@ -6909,16 +6638,14 @@ private: tok("; p = realloc(0, sizeof(char)*0);")); } - void simplifyErrNoInWhile() - { + void simplifyErrNoInWhile() { ASSERT_EQUALS("; while ( f ( ) ) { }", tok("; while (f() && errno == EINTR) { }")); ASSERT_EQUALS("; while ( f ( ) ) { }", tok("; while (f() && (errno == EINTR)) { }")); } - void simplifyFuncInWhile() - { + void simplifyFuncInWhile() { ASSERT_EQUALS("int cppcheck:r = fclose ( f ) ; " "while ( cppcheck:r ) " "{ " @@ -6947,8 +6674,7 @@ private: tok("while(fclose(f)); while(fclose(g));")); } - void initstruct() - { + void initstruct() { ASSERT_EQUALS("; struct A a ; a . buf = 3 ;", tok("; struct A a = { .buf = 3 };")); ASSERT_EQUALS("; struct A a ; a . buf = x ;", tok("; struct A a = { .buf = x };")); ASSERT_EQUALS("; struct A a ; a . buf = & key ;", tok("; struct A a = { .buf = &key };")); @@ -6958,8 +6684,7 @@ private: tok("; struct A a = { .buf = {0} };")); } - void simplifyStructDecl1() - { + void simplifyStructDecl1() { { const char code[] = "struct ABC { } abc;"; const char expected[] = "struct ABC { } ; ABC abc ;"; @@ -7101,15 +6826,13 @@ private: } } - void simplifyStructDecl2() // ticket #2479 (segmentation fault) - { + void simplifyStructDecl2() { // ticket #2479 (segmentation fault) const char code[] = "struct { char c; }"; const char expected[] = "struct { char c ; }"; ASSERT_EQUALS(expected, tok(code, false)); } - void simplifyStructDecl3() - { + void simplifyStructDecl3() { { const char code[] = "class ABC { } abc;"; const char expected[] = "class ABC { } ; ABC abc ;"; @@ -7231,8 +6954,7 @@ private: } } - void simplifyStructDecl4() - { + void simplifyStructDecl4() { { const char code[] = "class ABC {\n" " void foo() {\n" @@ -7262,8 +6984,7 @@ private: } } - void removeUnwantedKeywords() - { + void removeUnwantedKeywords() { ASSERT_EQUALS("int var ;", tok("register int var ;", true)); ASSERT_EQUALS("short var ;", tok("register short int var ;", true)); ASSERT_EQUALS("int foo ( ) { }", tok("inline int foo ( ) { }", true)); @@ -7280,8 +7001,7 @@ private: ASSERT_EQUALS("; int * p ;", tok("typedef int * __restrict__ rint; rint p;", true)); } - void simplifyCallingConvention() - { + void simplifyCallingConvention() { ASSERT_EQUALS("int f ( ) ;", tok("int __cdecl f();", true)); ASSERT_EQUALS("int f ( ) ;", tok("int __stdcall f();", true)); ASSERT_EQUALS("int f ( ) ;", tok("int __fastcall f();", true)); @@ -7303,19 +7023,16 @@ private: ASSERT_EQUALS("int f ( ) ;", tok("int CALLBACK f();", true)); } - void simplifyFunctorCall() - { + void simplifyFunctorCall() { ASSERT_EQUALS("IncrementFunctor ( ) ( a ) ;", tok("IncrementFunctor()(a);", true)); } - void redundant_semicolon() - { + void redundant_semicolon() { ASSERT_EQUALS("void f ( ) { ; }", tok("void f() { ; }", false)); ASSERT_EQUALS("void f ( ) { ; }", tok("void f() { do { ; } while (0); }", true)); } - void simplifyFunctionReturn() - { + void simplifyFunctionReturn() { const char code[] = "typedef void (*testfp)();\n" "struct Fred\n" "{\n" @@ -7335,16 +7052,14 @@ private: ASSERT_EQUALS(expected, tok(code, false)); } - void removeUnnecessaryQualification1() - { + void removeUnnecessaryQualification1() { const char code[] = "class Fred { Fred::Fred() {} };"; const char expected[] = "class Fred { Fred ( ) { } } ;"; ASSERT_EQUALS(expected, tok(code, false)); ASSERT_EQUALS("[test.cpp:1]: (portability) Extra qualification 'Fred::' unnecessary and considered an error by many compilers.\n", errout.str()); } - void removeUnnecessaryQualification2() - { + void removeUnnecessaryQualification2() { const char code[] = "template\n" "struct grammar : qi::grammar {\n" " grammar() : grammar::base_type(start) { }\n" @@ -7353,8 +7068,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void removeUnnecessaryQualification3() - { + void removeUnnecessaryQualification3() { const char code[] = "namespace one {\n" " class c {\n" " public:\n" @@ -7373,8 +7087,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void removeUnnecessaryQualification4() - { + void removeUnnecessaryQualification4() { const char code[] = "namespace one {\n" " class c {\n" " public:\n" @@ -7391,8 +7104,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void removeUnnecessaryQualification5() - { + void removeUnnecessaryQualification5() { const char code[] = "namespace one {\n" " class c {\n" " public:\n" @@ -7411,8 +7123,7 @@ private: ASSERT_EQUALS("[test.cpp:11]: (portability) Extra qualification 'two::c::' unnecessary and considered an error by many compilers.\n", errout.str()); } - void removeUnnecessaryQualification6() - { + void removeUnnecessaryQualification6() { const char code[] = "namespace NS {\n" " int HRDF_bit() { return 1; }\n" " void HRDF_bit_set() { }\n" @@ -7427,8 +7138,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void removeUnnecessaryQualification7() // ticket #2970 - { + void removeUnnecessaryQualification7() { // ticket #2970 const char code[] = "class TProcedure {\n" "public:\n" " TProcedure::TProcedure(long endAddress) : m_lEndAddr(endAddress){}\n" @@ -7439,8 +7149,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (portability) Extra qualification 'TProcedure::' unnecessary and considered an error by many compilers.\n", errout.str()); } - void removeUnnecessaryQualification8() - { + void removeUnnecessaryQualification8() { const char code[] = "class Fred {\n" "public:\n" " Fred & Fred::operator = (const Fred &);\n" @@ -7453,8 +7162,7 @@ private: "[test.cpp:5]: (portability) Extra qualification 'Fred::' unnecessary and considered an error by many compilers.\n", errout.str()); } - void removeUnnecessaryQualification9() - { + void removeUnnecessaryQualification9() { const char code[] = "class Fred {\n" "public:\n" " Fred::~Fred();\n" @@ -7463,8 +7171,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (portability) Extra qualification 'Fred::' unnecessary and considered an error by many compilers.\n", errout.str()); } - void simplifyIfNotNull() - { + void simplifyIfNotNull() { { // ticket # 2601 segmentation fault const char code[] = "|| #if #define <="; @@ -7480,22 +7187,19 @@ private: } } - void simplifyVarDecl1() // ticket # 2682 segmentation fault - { + void simplifyVarDecl1() { // ticket # 2682 segmentation fault const char code[] = "x a[0] ="; tok(code, false); ASSERT_EQUALS("", errout.str()); } - void simplifyVarDecl2() // ticket # 2834 segmentation fault - { + void simplifyVarDecl2() { // ticket # 2834 segmentation fault const char code[] = "std::vector::iterator"; tok(code, false); ASSERT_EQUALS("", errout.str()); } - void return_strncat() - { + void return_strncat() { const char code[] = "char *f()\n" "{\n" " char *temp=malloc(2);\n" @@ -7511,8 +7215,7 @@ private: "}", tok(code, true)); } - void removeRedundantFor() // ticket #3069 - { + void removeRedundantFor() { // ticket #3069 { const char code[] = "void f() {" " for(x=0;x<1;x++) {" diff --git a/test/teststl.cpp b/test/teststl.cpp index d528e2420..e4fdcbfb7 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -25,15 +25,13 @@ extern std::ostringstream errout; -class TestStl : public TestFixture -{ +class TestStl : public TestFixture { public: TestStl() : TestFixture("TestStl") { } private: - void run() - { + void run() { TEST_CASE(iterator1); TEST_CASE(iterator2); TEST_CASE(iterator3); @@ -113,8 +111,7 @@ private: } - void check(const std::string &code) - { + void check(const std::string &code) { // Clear the error buffer.. errout.str(""); @@ -134,8 +131,7 @@ private: } - void iterator1() - { + void iterator1() { check("void f()\n" "{\n" " list l1;\n" @@ -146,8 +142,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Same iterator is used with both l1 and l2\n", errout.str()); } - void iterator2() - { + void iterator2() { check("void foo()\n" "{\n" " list l1;\n" @@ -161,8 +156,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Same iterator is used with both l1 and l2\n", errout.str()); } - void iterator3() - { + void iterator3() { check("void foo()\n" "{\n" " list l1;\n" @@ -173,8 +167,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Same iterator is used with both l1 and l2\n", errout.str()); } - void iterator4() - { + void iterator4() { check("void foo(std::vector &test)\n" "{\n" " std::set result;\n" @@ -188,8 +181,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void iterator5() - { + void iterator5() { check("void foo()\n" "{\n" " std::vector ints1;\n" @@ -199,8 +191,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) mismatching containers\n", errout.str()); } - void iterator6() - { + void iterator6() { // Ticket #1357 check("void foo(const std::set &ints1)\n" "{\n" @@ -212,8 +203,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void iterator7() - { + void iterator7() { // Ticket #1600 check("void foo(std::vector &r)\n" "{\n" @@ -266,8 +256,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:14] (error) After insert, the iterator 'aI' may be invalid", "", errout.str()); } - void iterator8() - { + void iterator8() { // Ticket #1679 check("void foo()\n" "{\n" @@ -283,8 +272,7 @@ private: } // Dereferencing invalid pointer - void dereference() - { + void dereference() { check("void f()\n" "{\n" " std::vector ints;\n" @@ -296,8 +284,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Dereferenced iterator 'iter' has been erased\n", errout.str()); } - void dereference_member() - { + void dereference_member() { check("void f()\n" "{\n" " std::map ints;\n" @@ -310,8 +297,7 @@ private: } - void STLSize() - { + void STLSize() { check("void foo()\n" "{\n" " std::vector foo;\n" @@ -335,8 +321,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void STLSizeNoErr() - { + void STLSizeNoErr() { { check("void foo()\n" "{\n" @@ -383,8 +368,7 @@ private: - void erase1() - { + void erase1() { check("void f()\n" "{\n" " for (it = foo.begin(); it != foo.end(); ++it)\n" @@ -425,8 +409,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void erase2() - { + void erase2() { check("static void f()\n" "{\n" " for (iterator it = foo.begin(); it != foo.end(); it = next)\n" @@ -439,8 +422,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void erase3() - { + void erase3() { check("static void f(std::list &foo)\n" "{\n" " std::list::iterator it = foo.begin();\n" @@ -450,8 +432,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void erase4() - { + void erase4() { check("void f()\n" "{\n" " std::list::iterator it, it2;\n" @@ -493,8 +474,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Dangerous iterator usage after erase()-method.\n", errout.str()); } - void erase5() - { + void erase5() { check("void f()\n" "{\n" " std::list foo;\n" @@ -508,8 +488,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) Dangerous iterator usage after erase()-method.\n", errout.str()); } - void erase6() - { + void erase6() { check("void f() {\n" " std::vector vec(3);\n" " std::vector::iterator it;\n" @@ -522,8 +501,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseBreak() - { + void eraseBreak() { check("void f()\n" "{\n" " for (iterator it = foo.begin(); it != foo.end(); ++it)\n" @@ -548,8 +526,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseContinue() - { + void eraseContinue() { check("void f(std::vector &ints)\n" "{\n" " std::vector::iterator it;\n" @@ -565,8 +542,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseReturn1() - { + void eraseReturn1() { check("void f()\n" "{\n" " std::vector foo;\n" @@ -580,8 +556,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseReturn2() - { + void eraseReturn2() { check("void f()\n" "{\n" " std::vector foo;\n" @@ -601,8 +576,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseReturn3() - { + void eraseReturn3() { check("void f()\n" "{\n" " std::vector foo;\n" @@ -637,8 +611,7 @@ private: TODO_ASSERT_EQUALS("[test.cpp:9]: (error) Dangerous iterator usage after erase()-method.\n", "", errout.str()); } - void eraseGoto() - { + void eraseGoto() { check("void f()\n" "{\n" " for (iterator it = foo.begin(); it != foo.end(); ++it)\n" @@ -651,8 +624,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseAssign1() - { + void eraseAssign1() { check("void f()\n" "{\n" " for (iterator it = foo.begin(); it != foo.end(); ++it)\n" @@ -664,8 +636,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseAssign2() - { + void eraseAssign2() { check("void f(list &ints)\n" "{\n" " for (list::iterator it = ints.begin(); it != ints.end();) {\n" @@ -683,8 +654,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void eraseErase() - { + void eraseErase() { check("void f(std::vector &ints)\n" "{\n" " std::vector::iterator iter;\n" @@ -695,8 +665,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) Invalid iterator: iter\n", errout.str()); } - void eraseByValue() - { + void eraseByValue() { check("void f()\n" "{\n" " std::set foo;\n" @@ -717,8 +686,7 @@ private: } - void pushback1() - { + void pushback1() { check("void f(const std::vector &foo)\n" "{\n" " std::vector::const_iterator it = foo.begin();\n" @@ -728,8 +696,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) After push_back, the iterator 'it' may be invalid\n", errout.str()); } - void pushback2() - { + void pushback2() { check("void f()\n" "{\n" " std::vector::const_iterator it = foo.begin();\n" @@ -742,8 +709,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void pushback3() - { + void pushback3() { check("void f()\n" "{\n" " std::vector foo;\n" @@ -757,8 +723,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) After push_back, the iterator 'it' may be invalid\n", errout.str()); } - void pushback4() - { + void pushback4() { check("void f()\n" "{\n" " std::vector ints;\n" @@ -770,8 +735,7 @@ private: ASSERT_EQUALS("[test.cpp:7]: (error) Invalid pointer 'first' after push_back / push_front\n", errout.str()); } - void pushback5() - { + void pushback5() { check("void f()\n" "{\n" " std::vector::const_iterator i;\n" @@ -788,8 +752,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void pushback6() - { + void pushback6() { // ticket #735 check("void f()\n" "{\n" @@ -818,8 +781,7 @@ private: ASSERT_EQUALS("[test.cpp:9]: (error) After push_back, the iterator 'it' may be invalid\n", errout.str()); } - void pushback7() - { + void pushback7() { check("void f()\n" "{\n" " std::vector foo;\n" @@ -833,8 +795,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) After push_back, the iterator 'it' may be invalid\n", errout.str()); } - void pushback8() - { + void pushback8() { check("void f()\n" "{\n" " std::vector ints;\n" @@ -850,8 +811,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) After push_back, the iterator 'end' may be invalid\n", errout.str()); } - void pushback9() - { + void pushback9() { check("struct A {\n" " std::vector ints;\n" "};\n" @@ -871,8 +831,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void pushback10() - { + void pushback10() { check("void f(std::vector &foo)\n" "{\n" " std::vector::const_iterator it = foo.begin();\n" @@ -895,8 +854,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (error) After reserve, the iterator 'it' may be invalid\n", errout.str()); } - void pushback11() - { + void pushback11() { // #2798 check("void f() {\n" " std::vector ints;\n" @@ -910,8 +868,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void insert1() - { + void insert1() { check("void f(std::vector &ints)\n" "{\n" " std::vector::iterator iter = ints.begin() + 5;\n" @@ -938,8 +895,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (error) After insert, the iterator 'iter' may be invalid\n", errout.str()); } - void insert2() - { + void insert2() { // Ticket: #2169 check("void f(std::vector &vec) {\n" " for(std::vector::iterator iter = vec.begin(); iter != vec.end(); ++iter)\n" @@ -962,8 +918,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void invalidcode() - { + void invalidcode() { errout.str(""); const std::string src = "void f()\n" "{\n" @@ -979,17 +934,14 @@ private: - void stlBoundries1() - { + void stlBoundries1() { const int STL_CONTAINER_LIST = 9; - const std::string stlCont[STL_CONTAINER_LIST] = - { + const std::string stlCont[STL_CONTAINER_LIST] = { "deque", "list", "set", "multiset", "map", "multimap", "hash_map", "hash_multimap", "hash_set" }; - for (int i = 0; i < STL_CONTAINER_LIST; ++i) - { + for (int i = 0; i < STL_CONTAINER_LIST; ++i) { check("void f()\n" "{\n" " std::" + stlCont[i] + "::iterator it;\n" @@ -1001,8 +953,7 @@ private: } } - void stlBoundries2() - { + void stlBoundries2() { check("void f()\n" "{\n" " std::vector files;\n" @@ -1014,8 +965,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void stlBoundries3() - { + void stlBoundries3() { check("void f()\n" "{\n" " set files;\n" @@ -1031,8 +981,7 @@ private: - void if_find() - { + void if_find() { // --------------------------- // set::find // --------------------------- @@ -1071,8 +1020,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void if_str_find() - { + void if_str_find() { // error check("void f(const std::string &s)\n" "{\n" @@ -1082,8 +1030,7 @@ private: } - void size1() - { + void size1() { check("struct Fred {\n" " void foo();\n" " std::list x;\n" @@ -1172,8 +1119,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void redundantCondition1() - { + void redundantCondition1() { check("void f()\n" "{\n" " if (haystack.find(needle) != haystack.end())\n" @@ -1182,8 +1128,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Redundant checking of STL container element.\n", errout.str()); } - void size2() - { + void size2() { check("struct Fred {\n" " std::list x;\n" "};\n" @@ -1198,8 +1143,7 @@ private: ASSERT_EQUALS("[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout.str()); } - void redundantCondition2() - { + void redundantCondition2() { check("void f()\n" "{\n" " if (haystack.find(needle) != haystack.end())\n" @@ -1210,8 +1154,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Redundant checking of STL container element.\n", errout.str()); } - void missingInnerComparison1() - { + void missingInnerComparison1() { check("void f(std::set &ints) {\n" " for (std::set::iterator it = ints.begin(); it != ints.end(); ++it) {\n" " if (a) {\n" @@ -1229,8 +1172,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void missingInnerComparison2() - { + void missingInnerComparison2() { check("void f(std::set &ints) {\n" " for (std::set::iterator it = ints.begin(); it != ints.end(); ++it) {\n" " if (a) {\n" @@ -1243,8 +1185,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void missingInnerComparison3() - { + void missingInnerComparison3() { check("void f(std::set &ints) {\n" " for (std::set::iterator it = ints.begin(); it != ints.end(); ++it) {\n" " for (std::set::iterator it = ints2.begin(); it != ints2.end(); ++it)\n" @@ -1254,8 +1195,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void missingInnerComparison4() - { + void missingInnerComparison4() { check("function f1(std::list &l1) {\n" " for(std::list::iterator i = l1.begin(); i != l1.end(); i++) {\n" " if (*i == 44) {\n" @@ -1277,8 +1217,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void missingInnerComparison5() - { + void missingInnerComparison5() { check("void f() {\n" " for(it = map1.begin(); it != map1.end(); it++) {\n" " str[i++] = (*it).first;\n" @@ -1287,8 +1226,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void missingInnerComparison6() - { + void missingInnerComparison6() { check("void f(std::string &s) {\n" " for(string::iterator it = s.begin(); it != s.end(); it++) {\n" " it = s.insert(++it, 0);\n" @@ -1297,8 +1235,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void cstr() - { + void cstr() { check("void f() {\n" " std::string errmsg;\n" " throw errmsg.c_str();\n" @@ -1319,8 +1256,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Dangerous usage of c_str()\n", errout.str()); } - void autoPointer() - { + void autoPointer() { // ticket 2846 check("void f()\n" diff --git a/test/testsuite.cpp b/test/testsuite.cpp index b4ea73800..9250e473c 100644 --- a/test/testsuite.cpp +++ b/test/testsuite.cpp @@ -29,25 +29,21 @@ std::ostringstream output; * TestRegistry **/ -class TestRegistry -{ +class TestRegistry { private: std::list _tests; public: - static TestRegistry &theInstance() - { + static TestRegistry &theInstance() { static TestRegistry testreg; return testreg; } - void addTest(TestFixture *t) - { + void addTest(TestFixture *t) { _tests.push_back(t); } - const std::list &tests() const - { + const std::list &tests() const { return _tests; } }; @@ -76,15 +72,11 @@ TestFixture::TestFixture(const std::string &_name) bool TestFixture::runTest(const char testname[]) { - if (testToRun.empty() || testToRun == testname) - { + if (testToRun.empty() || testToRun == testname) { ++countTests; - if (quiet_tests) - { + if (quiet_tests) { std::cout << '.'; - } - else - { + } else { std::cout << classname << "::" << testname << "\n"; } return true; @@ -96,8 +88,7 @@ static std::string writestr(const std::string &str) { std::ostringstream ostr; ostr << "\""; - for (unsigned int i = 0; i < str.length(); ++i) - { + for (unsigned int i = 0; i < str.length(); ++i) { char ch = str[i]; if (ch == '\n') ostr << "\\n"; @@ -114,15 +105,11 @@ static std::string writestr(const std::string &str) void TestFixture::assert_(const char *filename, int linenr, bool condition) { - if (!condition) - { + if (!condition) { ++fails_counter; - if (gcc_style_errors) - { + if (gcc_style_errors) { errmsg << filename << ':' << linenr << ": Assertion failed." << std::endl; - } - else - { + } else { errmsg << "Assertion failed in " << filename << " at line " << linenr << std::endl; } } @@ -130,11 +117,9 @@ void TestFixture::assert_(const char *filename, int linenr, bool condition) void TestFixture::assertEquals(const char *filename, int linenr, const std::string &expected, const std::string &actual, const std::string &msg) { - if (expected != actual) - { + if (expected != actual) { ++fails_counter; - if (gcc_style_errors) - { + if (gcc_style_errors) { errmsg << filename << ':' << linenr << ": Assertion failed. " << "Expected: " << writestr(expected) @@ -142,17 +127,14 @@ void TestFixture::assertEquals(const char *filename, int linenr, const std::stri << writestr(actual) << "." << std::endl; - } - else - { + } else { errmsg << "Assertion failed in " << filename << " at line " << linenr << std::endl << "Expected:" << std::endl << writestr(expected) << std::endl << "Actual:" << std::endl << writestr(actual) << std::endl; } - if (!msg.empty()) - { + if (!msg.empty()) { errmsg << msg << std::endl; } } @@ -182,12 +164,9 @@ void TestFixture::todoAssertEquals(const char *filename, int linenr, const std::string &actual) { assertEquals(filename, linenr, current, actual); - if (wanted == actual) - { + if (wanted == actual) { assertEquals(filename, linenr, "TODO assertion", "The assertion succeeded"); - } - else - { + } else { ++todos_counter; } } @@ -204,13 +183,10 @@ void TestFixture::todoAssertEquals(const char *filename, int linenr, unsigned in void TestFixture::assertThrowFail(const char *filename, int linenr) { ++fails_counter; - if (gcc_style_errors) - { + if (gcc_style_errors) { errmsg << filename << ':' << linenr << " Assertion failed. " << "The expected exception was not thrown" << std::endl; - } - else - { + } else { errmsg << "Assertion failed in " << filename << " at line " << linenr << std::endl << "The expected exception was not thrown" << std::endl; } @@ -220,8 +196,7 @@ void TestFixture::printTests() { const std::list &tests = TestRegistry::theInstance().tests(); - for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) - { + for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) { std::cout << (*it)->classname << std::endl; } } @@ -229,8 +204,7 @@ void TestFixture::printTests() void TestFixture::run(const std::string &str) { testToRun = str; - if (quiet_tests) - { + if (quiet_tests) { std::cout << '\n' << classname << ':'; } run(); @@ -246,8 +220,7 @@ size_t TestFixture::runTests(const options& args) { std::string classname(args.which_test()); std::string testname(""); - if (classname.find("::") != std::string::npos) - { + if (classname.find("::") != std::string::npos) { testname = classname.substr(classname.find("::") + 2); classname.erase(classname.find("::")); } @@ -257,10 +230,8 @@ size_t TestFixture::runTests(const options& args) const std::list &tests = TestRegistry::theInstance().tests(); - for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) - { - if (classname.empty() || (*it)->classname == classname) - { + for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) { + if (classname.empty() || (*it)->classname == classname) { (*it)->processOptions(args); (*it)->run(testname); } diff --git a/test/testsuite.h b/test/testsuite.h index 2a6fedfe9..36f66d707 100644 --- a/test/testsuite.h +++ b/test/testsuite.h @@ -28,8 +28,7 @@ class options; class Token; -class TestFixture : public ErrorLogger -{ +class TestFixture : public ErrorLogger { private: static std::ostringstream errmsg; static unsigned int countTests; diff --git a/test/testsuppressions.cpp b/test/testsuppressions.cpp index 30be4d16a..bc9ca3d19 100644 --- a/test/testsuppressions.cpp +++ b/test/testsuppressions.cpp @@ -26,16 +26,14 @@ extern std::ostringstream errout; -class TestSuppressions : public TestFixture -{ +class TestSuppressions : public TestFixture { public: TestSuppressions() : TestFixture("TestSuppressions") { } private: - void run() - { + void run() { TEST_CASE(suppressionsBadId1); TEST_CASE(suppressionsDosFormat); // Ticket #1836 TEST_CASE(suppressionsFileNameWithColon); // Ticket #1919 - filename includes colon @@ -45,15 +43,13 @@ private: TEST_CASE(suppressionsMultiFile); } - void suppressionsBadId1() - { + void suppressionsBadId1() { Suppressions suppressions; std::istringstream s("123"); ASSERT_EQUALS("Failed to add suppression. Invalid id \"123\"", suppressions.parseFile(s)); } - void suppressionsDosFormat() - { + void suppressionsDosFormat() { Suppressions suppressions; std::istringstream s("abc\r\ndef\r\n"); ASSERT_EQUALS("", suppressions.parseFile(s)); @@ -61,8 +57,7 @@ private: ASSERT_EQUALS(true, suppressions.isSuppressed("def", "test.cpp", 1)); } - void suppressionsFileNameWithColon() - { + void suppressionsFileNameWithColon() { Suppressions suppressions; std::istringstream s("errorid:c:\\foo.cpp\nerrorid:c:\\bar.cpp:12"); ASSERT_EQUALS("", suppressions.parseFile(s)); @@ -71,8 +66,7 @@ private: ASSERT_EQUALS(true, suppressions.isSuppressed("errorid", "c:\\bar.cpp", 12)); } - void suppressionsGlob() - { + void suppressionsGlob() { // Check for syntax errors in glob { Suppressions suppressions; @@ -106,8 +100,7 @@ private: } } - void suppressionsFileNameWithExtraPath() - { + void suppressionsFileNameWithExtraPath() { // Ticket #2797 Suppressions suppressions; suppressions.addSuppression("errorid", "./a.c", 123); @@ -115,15 +108,13 @@ private: } // Check the suppression - void checkSuppression(const char code[], const std::string &suppression = "") - { + void checkSuppression(const char code[], const std::string &suppression = "") { // Clear the error log errout.str(""); Settings settings; settings._inlineSuppressions = true; - if (!suppression.empty()) - { + if (!suppression.empty()) { std::string r = settings.nomsg.addSuppressionLine(suppression); ASSERT_EQUALS("", r); } @@ -135,8 +126,7 @@ private: reportUnmatchedSuppressions(cppCheck.settings().nomsg.getUnmatchedGlobalSuppressions()); } - void checkSuppressionThreads(const char code[], const std::string &suppression = "") - { + void checkSuppressionThreads(const char code[], const std::string &suppression = "") { errout.str(""); output.str(""); @@ -147,8 +137,7 @@ private: Settings settings; settings._jobs = 1; settings._inlineSuppressions = true; - if (!suppression.empty()) - { + if (!suppression.empty()) { std::string r = settings.nomsg.addSuppressionLine(suppression); ASSERT_EQUALS("", r); } @@ -162,8 +151,7 @@ private: } // Check the suppression for multiple files - void checkSuppression(const char *names[], const char *codes[], const std::string &suppression = "") - { + void checkSuppression(const char *names[], const char *codes[], const std::string &suppression = "") { // Clear the error log errout.str(""); @@ -180,8 +168,7 @@ private: reportUnmatchedSuppressions(cppCheck.settings().nomsg.getUnmatchedGlobalSuppressions()); } - void runChecks(void (TestSuppressions::*check)(const char[], const std::string &)) - { + void runChecks(void (TestSuppressions::*check)(const char[], const std::string &)) { // check to make sure the appropriate error is present (this->*check)("void f() {\n" " int a;\n" @@ -302,18 +289,15 @@ private: ASSERT_EQUALS("[test.cpp:4]: (information) Unmatched suppression: uninitvar\n", errout.str()); } - void suppressionsSettings() - { + void suppressionsSettings() { runChecks(&TestSuppressions::checkSuppression); if (ThreadExecutor::isEnabled()) runChecks(&TestSuppressions::checkSuppressionThreads); } - void suppressionsMultiFile() - { + void suppressionsMultiFile() { const char *names[] = {"abc.cpp", "xyz.cpp", NULL}; - const char *codes[] = - { + const char *codes[] = { "void f() {\n" "}\n", "void f() {\n" diff --git a/test/testsymboldatabase.cpp b/test/testsymboldatabase.cpp index e5f744615..eeb547dcd 100644 --- a/test/testsymboldatabase.cpp +++ b/test/testsymboldatabase.cpp @@ -28,8 +28,7 @@ tokenizer.tokenize(istr, "test.cpp"); \ const SymbolDatabase *db = tokenizer.getSymbolDatabase(); -class TestSymbolDatabase: public TestFixture -{ +class TestSymbolDatabase: public TestFixture { public: TestSymbolDatabase() :TestFixture("TestSymbolDatabase") @@ -41,8 +40,7 @@ public: ,isArray(false) {} - virtual void reportOut(const std::string &outmsg) - { + virtual void reportOut(const std::string &outmsg) { errout << outmsg << std::endl; } @@ -54,8 +52,7 @@ private: bool found; bool isArray; - void reset() - { + void reset() { vartok = NULL; typetok = NULL; t = NULL; @@ -63,8 +60,7 @@ private: isArray = false; } - void run() - { + void run() { TEST_CASE(test_isVariableDeclarationCanHandleNull); TEST_CASE(test_isVariableDeclarationIdentifiesSimpleDeclaration); TEST_CASE(test_isVariableDeclarationIdentifiesScopedDeclaration); @@ -132,8 +128,7 @@ private: TEST_CASE(symboldatabase21); } - void test_isVariableDeclarationCanHandleNull() - { + void test_isVariableDeclarationCanHandleNull() { reset(); bool result = si.isVariableDeclaration(NULL, vartok, typetok, isArray); ASSERT_EQUALS(false, result); @@ -142,8 +137,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesSimpleDeclaration() - { + void test_isVariableDeclarationIdentifiesSimpleDeclaration() { reset(); givenACodeSampleToTokenize simpleDeclaration("int x;"); bool result = si.isVariableDeclaration(simpleDeclaration.tokens(), vartok, typetok, isArray); @@ -153,8 +147,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesScopedDeclaration() - { + void test_isVariableDeclarationIdentifiesScopedDeclaration() { reset(); givenACodeSampleToTokenize ScopedDeclaration("::int x;"); bool result = si.isVariableDeclaration(ScopedDeclaration.tokens(), vartok, typetok, isArray); @@ -164,8 +157,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesStdDeclaration() - { + void test_isVariableDeclarationIdentifiesStdDeclaration() { reset(); givenACodeSampleToTokenize StdDeclaration("std::string x;"); bool result = si.isVariableDeclaration(StdDeclaration.tokens(), vartok, typetok, isArray); @@ -175,8 +167,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesScopedStdDeclaration() - { + void test_isVariableDeclarationIdentifiesScopedStdDeclaration() { reset(); givenACodeSampleToTokenize StdDeclaration("::std::string x;"); bool result = si.isVariableDeclaration(StdDeclaration.tokens(), vartok, typetok, isArray); @@ -186,8 +177,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesManyScopes() - { + void test_isVariableDeclarationIdentifiesManyScopes() { reset(); givenACodeSampleToTokenize manyScopes("AA::BB::CC::DD::EE x;"); bool result = si.isVariableDeclaration(manyScopes.tokens(), vartok, typetok, isArray); @@ -197,8 +187,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesPointers() - { + void test_isVariableDeclarationIdentifiesPointers() { reset(); givenACodeSampleToTokenize pointer("int* p;"); bool result = si.isVariableDeclaration(pointer.tokens(), vartok, typetok, isArray); @@ -208,8 +197,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationDoesNotIdentifyConstness() - { + void test_isVariableDeclarationDoesNotIdentifyConstness() { reset(); givenACodeSampleToTokenize constness("const int* cp;"); bool result = si.isVariableDeclaration(constness.tokens(), vartok, typetok, isArray); @@ -219,8 +207,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesFirstOfManyVariables() - { + void test_isVariableDeclarationIdentifiesFirstOfManyVariables() { reset(); givenACodeSampleToTokenize multipleDeclaration("int first, second;"); bool result = si.isVariableDeclaration(multipleDeclaration.tokens(), vartok, typetok, isArray); @@ -230,8 +217,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesScopedPointerDeclaration() - { + void test_isVariableDeclarationIdentifiesScopedPointerDeclaration() { reset(); givenACodeSampleToTokenize manyScopes("AA::BB::CC::DD::EE* p;"); bool result = si.isVariableDeclaration(manyScopes.tokens(), vartok, typetok, isArray); @@ -241,8 +227,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesDeclarationWithIndirection() - { + void test_isVariableDeclarationIdentifiesDeclarationWithIndirection() { reset(); givenACodeSampleToTokenize pointerToPointer("int** pp;"); bool result = si.isVariableDeclaration(pointerToPointer.tokens(), vartok, typetok, isArray); @@ -252,8 +237,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesDeclarationWithMultipleIndirection() - { + void test_isVariableDeclarationIdentifiesDeclarationWithMultipleIndirection() { reset(); givenACodeSampleToTokenize pointerToPointer("int***** p;"); bool result = si.isVariableDeclaration(pointerToPointer.tokens(), vartok, typetok, isArray); @@ -263,8 +247,7 @@ private: ASSERT(false == isArray); } - void test_isVariableDeclarationIdentifiesArray() - { + void test_isVariableDeclarationIdentifiesArray() { reset(); givenACodeSampleToTokenize array("::std::string v[3];"); bool result = si.isVariableDeclaration(array.tokens(), vartok, typetok, isArray); @@ -274,8 +257,7 @@ private: ASSERT(true == isArray); } - void test_isVariableDeclarationIdentifiesOfArrayPointers() - { + void test_isVariableDeclarationIdentifiesOfArrayPointers() { reset(); givenACodeSampleToTokenize array("A *a[5];"); bool result = si.isVariableDeclaration(array.tokens(), vartok, typetok, isArray); @@ -285,8 +267,7 @@ private: ASSERT(true == isArray); } - void isVariableDeclarationIdentifiesTemplatedPointerVariable() - { + void isVariableDeclarationIdentifiesTemplatedPointerVariable() { reset(); givenACodeSampleToTokenize var("std::set* chars;"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -296,8 +277,7 @@ private: ASSERT(false == isArray); } - void isVariableDeclarationIdentifiesTemplatedPointerToPointerVariable() - { + void isVariableDeclarationIdentifiesTemplatedPointerToPointerVariable() { reset(); givenACodeSampleToTokenize var("std::deque*** ints;"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -307,8 +287,7 @@ private: ASSERT(false == isArray); } - void isVariableDeclarationIdentifiesTemplatedArrayVariable() - { + void isVariableDeclarationIdentifiesTemplatedArrayVariable() { reset(); givenACodeSampleToTokenize var("std::deque ints[3];"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -318,8 +297,7 @@ private: ASSERT(true == isArray); } - void isVariableDeclarationIdentifiesTemplatedVariable() - { + void isVariableDeclarationIdentifiesTemplatedVariable() { reset(); givenACodeSampleToTokenize var("std::vector ints;"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -329,8 +307,7 @@ private: ASSERT(false == isArray); } - void isVariableDeclarationIdentifiesTemplatedVariableIterator() - { + void isVariableDeclarationIdentifiesTemplatedVariableIterator() { reset(); givenACodeSampleToTokenize var("std::list::const_iterator floats;"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -340,8 +317,7 @@ private: ASSERT(false == isArray); } - void isVariableDeclarationIdentifiesNestedTemplateVariable() - { + void isVariableDeclarationIdentifiesNestedTemplateVariable() { reset(); givenACodeSampleToTokenize var("std::deque > intsets;"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -351,8 +327,7 @@ private: ASSERT(false == isArray); } - void isVariableDeclarationDoesNotIdentifyTemplateClass() - { + void isVariableDeclarationDoesNotIdentifyTemplateClass() { reset(); givenACodeSampleToTokenize var("template class SomeClass{};"); bool result = si.isVariableDeclaration(var.tokens(), vartok, typetok, isArray); @@ -360,8 +335,7 @@ private: ASSERT(false == isArray); } - void canFindMatchingBracketsNeedsOpen() - { + void canFindMatchingBracketsNeedsOpen() { reset(); givenACodeSampleToTokenize var("std::deque > intsets;"); @@ -370,8 +344,7 @@ private: ASSERT(! t); } - void canFindMatchingBracketsInnerPair() - { + void canFindMatchingBracketsInnerPair() { reset(); givenACodeSampleToTokenize var("std::deque > intsets;"); @@ -381,8 +354,7 @@ private: ASSERT_EQUALS(var.tokens()->strAt(9), t->str()); } - void canFindMatchingBracketsOuterPair() - { + void canFindMatchingBracketsOuterPair() { reset(); givenACodeSampleToTokenize var("std::deque > intsets;"); @@ -393,8 +365,7 @@ private: } - void canFindMatchingBracketsWithTooManyClosing() - { + void canFindMatchingBracketsWithTooManyClosing() { reset(); givenACodeSampleToTokenize var("X< 1>2 > x1;\n"); @@ -404,8 +375,7 @@ private: ASSERT_EQUALS(var.tokens()->strAt(3), t->str()); } - void canFindMatchingBracketsWithTooManyOpening() - { + void canFindMatchingBracketsWithTooManyOpening() { reset(); givenACodeSampleToTokenize var("X < (2 < 1) > x1;\n"); @@ -413,15 +383,13 @@ private: ASSERT(!found); } - void hasRegularFunction() - { + void hasRegularFunction() { GET_SYMBOL_DB("void func() { }\n") // 2 scopes: Global and Function ASSERT(db && db->scopeList.size() == 2 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(1)); ASSERT(scope && scope->className == "func"); @@ -434,15 +402,13 @@ private: } } - void hasInlineClassFunction() - { + void hasInlineClassFunction() { GET_SYMBOL_DB("class Fred { void func() { } };\n") // 3 scopes: Global, Class, and Function ASSERT(db && db->scopeList.size() == 3 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(4)); ASSERT(scope && scope->className == "func"); @@ -455,15 +421,13 @@ private: } } - void hasMissingInlineClassFunction() - { + void hasMissingInlineClassFunction() { GET_SYMBOL_DB("class Fred { void func(); };\n") // 2 scopes: Global and Class (no Function scope because there is no function implementation) ASSERT(db && db->scopeList.size() == 2 && !tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(4)); ASSERT(scope == NULL); @@ -476,15 +440,13 @@ private: } } - void hasClassFunction() - { + void hasClassFunction() { GET_SYMBOL_DB("class Fred { void func(); }; Fred::func() { }\n") // 3 scopes: Global, Class, and Function ASSERT(db && db->scopeList.size() == 3 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(12)); ASSERT(scope && scope->className == "func"); @@ -497,15 +459,13 @@ private: } } - void hasRegularFunctionReturningFunctionPointer() - { + void hasRegularFunctionReturningFunctionPointer() { GET_SYMBOL_DB("void (*func(int f))(char) { }\n") // 2 scopes: Global and Function ASSERT(db && db->scopeList.size() == 2 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(3)); ASSERT(scope && scope->className == "func"); @@ -518,15 +478,13 @@ private: } } - void hasInlineClassFunctionReturningFunctionPointer() - { + void hasInlineClassFunctionReturningFunctionPointer() { GET_SYMBOL_DB("class Fred { void (*func(int f))(char) { } };\n") // 3 scopes: Global, Class, and Function ASSERT(db && db->scopeList.size() == 3 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(6)); ASSERT(scope && scope->className == "func"); @@ -539,15 +497,13 @@ private: } } - void hasMissingInlineClassFunctionReturningFunctionPointer() - { + void hasMissingInlineClassFunctionReturningFunctionPointer() { GET_SYMBOL_DB("class Fred { void (*func(int f))(char); };\n") // 2 scopes: Global and Class (no Function scope because there is no function implementation) ASSERT(db && db->scopeList.size() == 2 && !tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(6)); ASSERT(scope == NULL); @@ -560,15 +516,13 @@ private: } } - void hasClassFunctionReturningFunctionPointer() - { + void hasClassFunctionReturningFunctionPointer() { GET_SYMBOL_DB("class Fred { void (*func(int f))(char); }; void (*Fred::func(int f))(char) { }\n") // 3 scopes: Global, Class, and Function ASSERT(db && db->scopeList.size() == 3 && tokenizer.getFunctionTokenByName("func")); - if (db) - { + if (db) { const Scope *scope = db->findFunctionScopeByToken(tokenizer.tokens()->tokAt(23)); ASSERT(scope && scope->className == "func"); @@ -581,17 +535,14 @@ private: } } - void hasGlobalVariables1() - { + void hasGlobalVariables1() { GET_SYMBOL_DB("int i;\n") ASSERT(db && db->scopeList.size() == 1); - if (db && db->scopeList.size() == 1) - { + if (db && db->scopeList.size() == 1) { std::list::const_iterator it = db->scopeList.begin(); ASSERT(it->varlist.size() == 1); - if (it->varlist.size() == 1) - { + if (it->varlist.size() == 1) { std::list::const_iterator var = it->varlist.begin(); ASSERT(var->name() == "i"); ASSERT(var->typeStartToken()->str() == "int"); @@ -599,17 +550,14 @@ private: } } - void hasGlobalVariables2() - { + void hasGlobalVariables2() { GET_SYMBOL_DB("int array[2][2];\n") ASSERT(db && db->scopeList.size() == 1); - if (db && db->scopeList.size() == 1) - { + if (db && db->scopeList.size() == 1) { std::list::const_iterator it = db->scopeList.begin(); ASSERT(it->varlist.size() == 1); - if (it->varlist.size() == 1) - { + if (it->varlist.size() == 1) { std::list::const_iterator var = it->varlist.begin(); ASSERT(var->name() == "array"); ASSERT(var->typeStartToken()->str() == "int"); @@ -617,17 +565,14 @@ private: } } - void hasGlobalVariables3() - { + void hasGlobalVariables3() { GET_SYMBOL_DB("int array[2][2] = { { 0, 0 }, { 0, 0 } };\n") ASSERT(db && db->scopeList.size() == 1); - if (db && db->scopeList.size() == 1) - { + if (db && db->scopeList.size() == 1) { std::list::const_iterator it = db->scopeList.begin(); ASSERT(it->varlist.size() == 1); - if (it->varlist.size() == 1) - { + if (it->varlist.size() == 1) { std::list::const_iterator var = it->varlist.begin(); ASSERT(var->name() == "array"); ASSERT(var->typeStartToken()->str() == "int"); @@ -635,8 +580,7 @@ private: } } - void check(const char code[], bool debug = true) - { + void check(const char code[], bool debug = true) { // Clear the error log errout.str(""); @@ -654,8 +598,7 @@ private: tokenizer.getSymbolDatabase(); } - void functionArgs1() - { + void functionArgs1() { check("void f(std::vector, const std::vector & v) { }\n"); ASSERT_EQUALS("", errout.str()); @@ -665,8 +608,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void functionArgs2() - { + void functionArgs2() { GET_SYMBOL_DB("void f(int a[][4]) { }"); const Variable *a = db->getVariableFromVarId(1); ASSERT_EQUALS("a", a->nameToken()->str()); @@ -675,8 +617,7 @@ private: ASSERT_EQUALS(4UL, a->dimension(1)); } - void symboldatabase1() - { + void symboldatabase1() { check("namespace foo {\n" " class bar;\n" "};"); @@ -687,8 +628,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase2() - { + void symboldatabase2() { check("class foo {\n" "public slots :\n" "foo() { }\n" @@ -702,8 +642,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase3() - { + void symboldatabase3() { check("typedef void (func_type)();\n" "struct A {\n" " friend func_type f : 2;\n" @@ -711,8 +650,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase4() - { + void symboldatabase4() { check("static void function_declaration_before(void) __attribute__((__used__));\n" "static void function_declaration_before(void) {}\n" "static void function_declaration_after(void) {}\n" @@ -744,8 +682,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase5() - { + void symboldatabase5() { // ticket #2178 - segmentation fault check("int CL_INLINE_DECL(integer_decode_float) (int x) {\n" " return (sign ? cl_I() : 0);\n" @@ -753,8 +690,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase6() - { + void symboldatabase6() { // ticket #2221 - segmentation fault check("template class X { };\n" "X< 1>2 > x1;\n" @@ -766,8 +702,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase7() - { + void symboldatabase7() { // ticket #2230 - segmentation fault check("template class E,class D> class C : E\n" "{\n" @@ -782,8 +717,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase8() - { + void symboldatabase8() { // ticket #2252 - segmentation fault check("struct PaletteColorSpaceHolder: public rtl::StaticWithInit,\n" " PaletteColorSpaceHolder>\n" @@ -797,8 +731,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase9() - { + void symboldatabase9() { // ticket #2425 - segmentation fault check("class CHyperlink : public CString\n" "{\n" @@ -812,8 +745,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase10() - { + void symboldatabase10() { // ticket #2537 - segmentation fault check("class A {\n" "private:\n" @@ -826,8 +758,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase11() - { + void symboldatabase11() { // ticket #2539 - segmentation fault check("int g ();\n" "struct S {\n" @@ -837,8 +768,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase12() - { + void symboldatabase12() { // ticket #2547 - segmentation fault check("class foo {\n" " void bar2 () = __null;\n" @@ -847,8 +777,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase13() - { + void symboldatabase13() { // ticket #2577 - segmentation fault check("class foo {\n" " void bar2 () = A::f;\n" @@ -857,64 +786,56 @@ private: ASSERT_EQUALS("", errout.str()); } - void symboldatabase14() - { + void symboldatabase14() { // ticket #2589 - segmentation fault check("struct B : A\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase15() - { + void symboldatabase15() { // ticket #2591 - segmentation fault check("struct A :\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase16() - { + void symboldatabase16() { // ticket #2637 - segmentation fault check("{} const const\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase17() - { + void symboldatabase17() { // ticket #2657 - segmentation fault check("return f(){}\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase18() - { + void symboldatabase18() { // ticket #2865 - segmentation fault check("char a[1]\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase19() - { + void symboldatabase19() { // ticket #2991 - segmentation fault check("::y(){x}\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase20() - { + void symboldatabase20() { // ticket #3013 - segmentation fault check("struct x : virtual y\n"); ASSERT_EQUALS("", errout.str()); } - void symboldatabase21() - { + void symboldatabase21() { check("class Fred {\n" " class Foo { };\n" " void func() const;\n" diff --git a/test/testthreadexecutor.cpp b/test/testthreadexecutor.cpp index 9102793eb..b5f838973 100644 --- a/test/testthreadexecutor.cpp +++ b/test/testthreadexecutor.cpp @@ -34,8 +34,7 @@ extern std::ostringstream errout; extern std::ostringstream output; -class TestThreadExecutor : public TestFixture -{ +class TestThreadExecutor : public TestFixture { public: TestThreadExecutor() : TestFixture("TestThreadExecutor") { } @@ -46,20 +45,17 @@ private: * Execute check using n jobs for y files which are have * identical data, given within data. */ - void check(unsigned int jobs, int files, int result, const std::string &data) - { + void check(unsigned int jobs, int files, int result, const std::string &data) { errout.str(""); output.str(""); - if (!ThreadExecutor::isEnabled()) - { + if (!ThreadExecutor::isEnabled()) { // Skip this check on systems which don't use this feature return; } std::vector filenames; std::map filesizes; - for (int i = 1; i <= files; ++i) - { + for (int i = 1; i <= files; ++i) { std::ostringstream oss; oss << "file_" << i << ".cpp"; filenames.push_back(oss.str()); @@ -74,8 +70,7 @@ private: ASSERT_EQUALS(result, executor.check()); } - void run() - { + void run() { TEST_CASE(deadlock_with_many_errors); TEST_CASE(no_errors_more_files); TEST_CASE(no_errors_less_files); @@ -84,8 +79,7 @@ private: TEST_CASE(one_error_several_files); } - void deadlock_with_many_errors() - { + void deadlock_with_many_errors() { std::ostringstream oss; oss << "int main()\n" << "{\n"; @@ -97,8 +91,7 @@ private: check(2, 3, 3, oss.str()); } - void no_errors_more_files() - { + void no_errors_more_files() { std::ostringstream oss; oss << "int main()\n" << "{\n"; @@ -107,8 +100,7 @@ private: check(2, 3, 0, oss.str()); } - void no_errors_less_files() - { + void no_errors_less_files() { std::ostringstream oss; oss << "int main()\n" << "{\n"; @@ -117,8 +109,7 @@ private: check(2, 1, 0, oss.str()); } - void no_errors_equal_amount_files() - { + void no_errors_equal_amount_files() { std::ostringstream oss; oss << "int main()\n" << "{\n"; @@ -127,8 +118,7 @@ private: check(2, 2, 0, oss.str()); } - void one_error_less_files() - { + void one_error_less_files() { std::ostringstream oss; oss << "int main()\n" << "{\n"; @@ -138,8 +128,7 @@ private: check(2, 1, 1, oss.str()); } - void one_error_several_files() - { + void one_error_several_files() { std::ostringstream oss; oss << "int main()\n" << "{\n"; diff --git a/test/testtoken.cpp b/test/testtoken.cpp index 3dc3a0ca3..50434cec9 100644 --- a/test/testtoken.cpp +++ b/test/testtoken.cpp @@ -24,16 +24,14 @@ #include extern std::ostringstream errout; -class TestToken : public TestFixture -{ +class TestToken : public TestFixture { public: TestToken() : TestFixture("TestToken") { } private: - void run() - { + void run() { TEST_CASE(nextprevious); TEST_CASE(multiCompare); TEST_CASE(getStrLength); @@ -49,8 +47,7 @@ private: TEST_CASE(matchOr); } - void nextprevious() - { + void nextprevious() { Token *token = new Token(0); token->str("1"); token->insertToken("2"); @@ -71,8 +68,7 @@ private: Tokenizer::deleteTokens(token); } - void multiCompare() - { + void multiCompare() { // Test for found ASSERT_EQUALS(1, Token::multiCompare("one|two", "one")); ASSERT_EQUALS(1, Token::multiCompare("one|two", "two")); @@ -98,8 +94,7 @@ private: ASSERT_EQUALS(-1, Token::multiCompare("%op%|two", "x")); } - void getStrLength() - { + void getStrLength() { Token tok(0); tok.str("\"\""); @@ -115,8 +110,7 @@ private: ASSERT_EQUALS(1, (int)Token::getStrLength(&tok)); } - void strValue() - { + void strValue() { Token tok(0); tok.str("\"\""); ASSERT_EQUALS(std::string(""), tok.strValue()); @@ -126,8 +120,7 @@ private: } - void deleteLast() - { + void deleteLast() { Token *tokensBack = 0; Token tok(&tokensBack); tok.insertToken("aba"); @@ -137,8 +130,7 @@ private: } - void matchAny() - { + void matchAny() { givenACodeSampleToTokenize varBitOrVar("abc|def"); ASSERT_EQUALS(true, Token::Match(varBitOrVar.tokens(), "%var% | %var%")); @@ -146,8 +138,7 @@ private: ASSERT_EQUALS(true, Token::Match(varLogOrVar.tokens(), "%var% || %var%")); } - void matchSingleChar() - { + void matchSingleChar() { givenACodeSampleToTokenize singleChar("a"); ASSERT_EQUALS(true, Token::Match(singleChar.tokens(), "[a|bc]")); ASSERT_EQUALS(false, Token::Match(singleChar.tokens(), "[d|ef]")); @@ -157,8 +148,7 @@ private: ASSERT_EQUALS(false, Token::Match(&multiChar, "[ab|def]")); } - void matchNothingOrAnyNotElse() - { + void matchNothingOrAnyNotElse() { givenACodeSampleToTokenize emptyString(""); ASSERT_EQUALS(true, Token::Match(emptyString.tokens(), "!!else")); ASSERT_EQUALS(false, Token::Match(emptyString.tokens(), "!!else something")); @@ -178,8 +168,7 @@ private: } - void matchNumeric() - { + void matchNumeric() { givenACodeSampleToTokenize nonNumeric("abc"); ASSERT_EQUALS(false, Token::Match(nonNumeric.tokens(), "%num%")); @@ -218,8 +207,7 @@ private: } - void matchBoolean() - { + void matchBoolean() { givenACodeSampleToTokenize yes("YES"); ASSERT_EQUALS(false, Token::Match(yes.tokens(), "%bool%")); @@ -230,8 +218,7 @@ private: ASSERT_EQUALS(true, Token::Match(negative.tokens(), "%bool%")); } - void matchOr() - { + void matchOr() { givenACodeSampleToTokenize bitwiseOr("|"); ASSERT_EQUALS(true, Token::Match(bitwiseOr.tokens(), "%or%")); ASSERT_EQUALS(false, Token::Match(bitwiseOr.tokens(), "%op%")); @@ -250,8 +237,7 @@ private: ASSERT_EQUALS(true, Token::Match(logicalAnd.tokens(), "%oror%|&&")); } - void matchOp() - { + void matchOp() { givenACodeSampleToTokenize op("+"); ASSERT_EQUALS(true, Token::Match(op.tokens(), "%op%")); } diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 9a605c424..83b100d6b 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -24,16 +24,14 @@ #include extern std::ostringstream errout; -class TestTokenizer : public TestFixture -{ +class TestTokenizer : public TestFixture { public: TestTokenizer() : TestFixture("TestTokenizer") { } private: - void run() - { + void run() { TEST_CASE(tokenize1); TEST_CASE(tokenize2); TEST_CASE(tokenize3); @@ -367,11 +365,9 @@ private: } - bool cmptok(const char *expected[], const Token *actual) - { + bool cmptok(const char *expected[], const Token *actual) { unsigned int i = 0; - for (; expected[i] && actual; ++i, actual = actual->next()) - { + for (; expected[i] && actual; ++i, actual = actual->next()) { if (strcmp(expected[i], actual->str().c_str()) != 0) return false; } @@ -379,8 +375,7 @@ private: } - std::string tokenizeAndStringify(const char code[], bool simplify = false, bool expand = true, Settings::PlatformType platform = Settings::Unspecified) - { + std::string tokenizeAndStringify(const char code[], bool simplify = false, bool expand = true, Settings::PlatformType platform = Settings::Unspecified) { errout.str(""); Settings settings; @@ -395,10 +390,8 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { - if (expand) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { + if (expand) { if (tok->isUnsigned()) ostr << "unsigned "; else if (tok->isSigned()) @@ -411,15 +404,11 @@ private: ostr << tok->str(); // Append newlines - if (tok->next()) - { - if (tok->linenr() != tok->next()->linenr()) - { + if (tok->next()) { + if (tok->linenr() != tok->next()->linenr()) { for (unsigned int i = tok->linenr(); i < tok->next()->linenr(); ++i) ostr << "\n"; - } - else - { + } else { ostr << " "; } } @@ -429,21 +418,18 @@ private: } - void tokenize1() - { + void tokenize1() { const std::string code("void f ( )\n" "{ if ( p . y ( ) > yof ) { } }"); ASSERT_EQUALS(code, tokenizeAndStringify(code.c_str())); } - void tokenize2() - { + void tokenize2() { const std::string code("{ sizeof a, sizeof b }"); ASSERT_EQUALS("{ sizeof a , sizeof b }", tokenizeAndStringify(code.c_str())); } - void tokenize3() - { + void tokenize3() { errout.str(""); const std::string code("void foo()\n" "{\n" @@ -458,8 +444,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void tokenize4() - { + void tokenize4() { errout.str(""); const std::string code("class foo\n" "{\n" @@ -474,22 +459,19 @@ private: ASSERT_EQUALS("", errout.str()); } - void tokenize5() - { + void tokenize5() { // Tokenize values ASSERT_EQUALS("; + 1E3 ;", tokenizeAndStringify("; +1E3 ;")); ASSERT_EQUALS("; 1E-2 ;", tokenizeAndStringify("; 1E-2 ;")); } - void tokenize6() - { + void tokenize6() { // "*(p+1)" => "p[1]" ASSERT_EQUALS("; x = p [ 1 ] ;", tokenizeAndStringify("; x = * ( p + 1 ) ;", true)); ASSERT_EQUALS("; x = p [ n ] ;", tokenizeAndStringify("; x = * ( p + n ) ;", true)); } - void tokenize7() - { + void tokenize7() { const std::string code = "void f() {\n" " int x1 = 1;\n" " int x2(x1);\n" @@ -498,8 +480,7 @@ private: tokenizeAndStringify(code.c_str(), false)); } - void tokenize8() - { + void tokenize8() { const std::string code = "void f() {\n" " int x1(g());\n" " int x2(x1);\n" @@ -512,8 +493,7 @@ private: tokenizeDebugListing(code.c_str(), false)); } - void tokenize9() - { + void tokenize9() { errout.str(""); const char code[] = "typedef void (*fp)();\n" "typedef fp (*fpp)();\n" @@ -524,22 +504,19 @@ private: ASSERT_EQUALS("", errout.str()); } - void tokenize10() - { + void tokenize10() { ASSERT_EQUALS("private:", tokenizeAndStringify("private:", false)); ASSERT_EQUALS("protected:", tokenizeAndStringify("protected:", false)); ASSERT_EQUALS("public:", tokenizeAndStringify("public:", false)); ASSERT_EQUALS("__published:", tokenizeAndStringify("__published:", false)); } - void tokenize11() - { + void tokenize11() { ASSERT_EQUALS("X * sizeof ( Y ( ) ) ;", tokenizeAndStringify("X * sizeof(Y());", false)); } // ticket #2118 - invalid syntax error - void tokenize12() - { + void tokenize12() { tokenizeAndStringify("Q_GLOBAL_STATIC_WITH_INITIALIZER(Qt4NodeStaticData, qt4NodeStaticData, {\n" " for (unsigned i = 0 ; i < count; i++) {\n" " }\n" @@ -548,8 +525,7 @@ private: } // bailout if there is "@" - it is not handled well - void tokenize13() - { + void tokenize13() { const char code[] = "@implementation\n" "-(Foo *)foo: (Bar *)bar\n" "{ }\n" @@ -558,46 +534,38 @@ private: } // Ticket #2361: 0X10 => 16 - void tokenize14() - { + void tokenize14() { ASSERT_EQUALS("; 16 ;", tokenizeAndStringify(";0x10;")); ASSERT_EQUALS("; 16 ;", tokenizeAndStringify(";0X10;")); } // Ticket #2429: 0.125 - void tokenize15() - { + void tokenize15() { ASSERT_EQUALS("0.125", tokenizeAndStringify(".125")); } // #2612 - segfault for "<><<" - void tokenize16() - { + void tokenize16() { tokenizeAndStringify("<><<"); } - void tokenize17() // #2759 - { + void tokenize17() { // #2759 ASSERT_EQUALS("class B : private :: A { } ;", tokenizeAndStringify("class B : private ::A { };")); } - void tokenize18() // tokenize "(X&&Y)" into "( X && Y )" instead of "( X & & Y )" - { + void tokenize18() { // tokenize "(X&&Y)" into "( X && Y )" instead of "( X & & Y )" ASSERT_EQUALS("( X && Y )", tokenizeAndStringify("(X&&Y)")); } - void tokenize19() // #3006 (segmentation fault) - { + void tokenize19() { // #3006 (segmentation fault) tokenizeAndStringify("x < () <"); } - void tokenize20() // replace C99 _Bool => bool - { + void tokenize20() { // replace C99 _Bool => bool ASSERT_EQUALS("bool a ; a = true ;", tokenizeAndStringify("_Bool a = true;")); } - void wrong_syntax() - { + void wrong_syntax() { { errout.str(""); const std::string code("TR(kvmpio, PROTO(int rw), ARGS(rw), TP_(aa->rw;))"); @@ -620,8 +588,7 @@ private: } } - void wrong_syntax_if_macro() - { + void wrong_syntax_if_macro() { // #2518 errout.str(""); const std::string code("void f() { if MACRO(); }"); @@ -629,8 +596,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); } - void minus() - { + void minus() { ASSERT_EQUALS("i = -12", tokenizeAndStringify("i = -12")); ASSERT_EQUALS("1 - 2", tokenizeAndStringify("1-2")); ASSERT_EQUALS("foo ( -1 ) - 2", tokenizeAndStringify("foo(-1)-2")); @@ -639,8 +605,7 @@ private: - void longtok() - { + void longtok() { std::string filedata(10000, 'a'); errout.str(""); @@ -659,8 +624,7 @@ private: // Don’t remove "(int *)".. - void removeCast1() - { + void removeCast1() { const char code[] = "int *f(int *);"; errout.str(""); @@ -681,8 +645,7 @@ private: } // remove static_cast.. - void removeCast2() - { + void removeCast2() { const char code[] = "t = (static_cast *>(&p));\n"; errout.str(""); @@ -702,36 +665,31 @@ private: ASSERT_EQUALS(" t = & p ;", ostr.str()); } - void removeCast3() - { + void removeCast3() { // ticket #961 const char code[] = "assert (iplen >= (unsigned) ipv4->ip_hl * 4 + 20);"; const char expected[] = "assert ( iplen >= ipv4 . ip_hl * 4 + 20 ) ;"; ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void removeCast4() - { + void removeCast4() { // ticket #970 const char code[] = "if (a >= (unsigned)(b)) {}"; const char expected[] = "if ( a >= ( unsigned int ) b ) { }"; ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void removeCast5() - { + void removeCast5() { // ticket #1817 ASSERT_EQUALS("a . data = f ;", tokenizeAndStringify("a->data = reinterpret_cast(static_cast(f));", true)); } - void removeCast6() - { + void removeCast6() { // ticket #2103 ASSERT_EQUALS("if ( ! x )", tokenizeAndStringify("if (x == (char *) ((void *)0))", true)); } - void inlineasm() - { + void inlineasm() { ASSERT_EQUALS("; asm ( ) ;", tokenizeAndStringify(";asm { mov ax,bx };")); ASSERT_EQUALS("; asm ( ) ;", tokenizeAndStringify(";_asm { mov ax,bx };")); ASSERT_EQUALS("; asm ( ) ;", tokenizeAndStringify(";__asm { mov ax,bx };")); @@ -745,8 +703,7 @@ private: } - void pointers_condition() - { + void pointers_condition() { ASSERT_EQUALS("( p )", tokenizeAndStringify("( p != NULL )", true)); ASSERT_EQUALS("( p )", tokenizeAndStringify("( NULL != p )", true)); ASSERT_EQUALS("( this . p )", tokenizeAndStringify("( this->p != NULL )", true)); @@ -783,8 +740,7 @@ private: } - void ifAddBraces1() - { + void ifAddBraces1() { const char code[] = "void f()\n" "{\n" " if (a);\n" @@ -797,8 +753,7 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces2() - { + void ifAddBraces2() { const char code[] = "void f()\n" "{\n" " if (a) if (b) { }\n" @@ -809,8 +764,7 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces3() - { + void ifAddBraces3() { const char code[] = "void f()\n" "{\n" " if (a) for (;;) { }\n" @@ -821,8 +775,7 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces4() - { + void ifAddBraces4() { const char code[] = "char * foo ()\n" "{\n" " char *str = malloc(10);\n" @@ -841,8 +794,7 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces5() - { + void ifAddBraces5() { const char code[] = "void f()\n" "{\n" "for(int i = 0; i < 2; i++)\n" @@ -861,14 +813,12 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces6() - { + void ifAddBraces6() { const char code[] = "if()"; ASSERT_EQUALS("if ( )", tokenizeAndStringify(code, true)); } - void ifAddBraces7() - { + void ifAddBraces7() { const char code[] = "void f()\n" "{\n" "int a;\n" @@ -883,8 +833,7 @@ private: "}", tokenizeAndStringify(code, true)); } - void ifAddBraces9() - { + void ifAddBraces9() { // ticket #990 const char code[] = "void f() {" @@ -900,31 +849,27 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void ifAddBraces10() - { + void ifAddBraces10() { // ticket #1361 const char code[] = "{ DEBUG(if (x) y; else z); }"; const char expected[] = "{ DEBUG ( if ( x ) y ; else z ) ; }"; ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void ifAddBraces11() - { + void ifAddBraces11() { const char code[] = "{ if (x) if (y) ; else ; }"; const char expected[] = "{ if ( x ) { if ( y ) { ; } else { ; } } }"; ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void ifAddBraces12() - { + void ifAddBraces12() { // ticket #1424 const char code[] = "{ if (x) do { } while(x); }"; const char expected[] = "{ if ( x ) { do { } while ( x ) ; } }"; ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void ifAddBraces13() - { + void ifAddBraces13() { // ticket #1809 const char code[] = "{ if (x) if (y) { } else { } else { } }"; const char expected[] = "{ if ( x ) { if ( y ) { } else { } } else { } }"; @@ -936,27 +881,23 @@ private: ASSERT_EQUALS(expected2, tokenizeAndStringify(code2, true)); } - void ifAddBraces14() - { + void ifAddBraces14() { // ticket #2610 (segfault) tokenizeAndStringify("if()<{}", false); } - void ifAddBraces15() - { + void ifAddBraces15() { // ticket #2616 - unknown macro before if ASSERT_EQUALS("{ A if ( x ) { y ( ) ; } }", tokenizeAndStringify("{A if(x)y();}", false)); } - void whileAddBraces() - { + void whileAddBraces() { const char code[] = ";while(a);"; ASSERT_EQUALS("; while ( a ) { ; }", tokenizeAndStringify(code, true)); } - void doWhileAddBraces() - { + void doWhileAddBraces() { { const char code[] = "do ; while (0);"; const char result[] = "do { ; } while ( 0 ) ;"; @@ -1015,8 +956,7 @@ private: } } - void forAddBraces() - { + void forAddBraces() { { const char code[] = "void f() {\n" " for(;;)\n" @@ -1049,8 +989,7 @@ private: } - std::string simplifyKnownVariables(const char code[]) - { + std::string simplifyKnownVariables(const char code[]) { errout.str(""); Settings settings; @@ -1063,8 +1002,7 @@ private: tokenizer.simplifyKnownVariables(); std::ostringstream ostr; - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (tok->previous()) ostr << " "; ostr << tok->str(); @@ -1073,8 +1011,7 @@ private: return ostr.str(); } - void simplifyKnownVariables1() - { + void simplifyKnownVariables1() { { const char code[] = "void f()\n" "{\n" @@ -1100,8 +1037,7 @@ private: } } - void simplifyKnownVariables2() - { + void simplifyKnownVariables2() { const char code[] = "void f()\n" "{\n" " int a = 10;\n" @@ -1114,8 +1050,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables3() - { + void simplifyKnownVariables3() { const char code[] = "void f()\n" "{\n" " int a = 4;\n" @@ -1131,8 +1066,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables4() - { + void simplifyKnownVariables4() { const char code[] = "void f()\n" "{\n" " int a = 4;\n" @@ -1145,8 +1079,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables5() - { + void simplifyKnownVariables5() { const char code[] = "void f()\n" "{\n" " int a = 4;\n" @@ -1158,8 +1091,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables6() - { + void simplifyKnownVariables6() { const char code[] = "void f()\n" "{\n" " char str[2];" @@ -1172,8 +1104,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables7() - { + void simplifyKnownVariables7() { const char code[] = "void foo()\n" "{\n" " int i = 22;\n" @@ -1186,8 +1117,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables8() - { + void simplifyKnownVariables8() { const char code[] = "void foo()\n" "{\n" " int i = 22;\n" @@ -1200,8 +1130,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables9() - { + void simplifyKnownVariables9() { const char code[] = "void foo()\n" "{\n" " int a = 1, b = 2;\n" @@ -1214,8 +1143,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables10() - { + void simplifyKnownVariables10() { { const char code[] = "void f()\n" "{\n" @@ -1281,8 +1209,7 @@ private: } } - void simplifyKnownVariables11() - { + void simplifyKnownVariables11() { const char code[] = "const int foo = 0;\n" "int main()\n" "{\n" @@ -1294,8 +1221,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables12() - { + void simplifyKnownVariables12() { const char code[] = "ENTER_NAMESPACE(project_namespace)\n" "const double pi = 3.14;\n" "int main(){}\n"; @@ -1304,8 +1230,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables13() - { + void simplifyKnownVariables13() { const char code[] = "void f()\n" "{\n" " int i = 10;\n" @@ -1317,15 +1242,13 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables14() - { + void simplifyKnownVariables14() { // ticket #753 const char code[] = "void f ( ) { int n ; n = 1 ; do { ++ n ; } while ( n < 10 ) ; }"; ASSERT_EQUALS(code, simplifyKnownVariables(code)); } - void simplifyKnownVariables15() - { + void simplifyKnownVariables15() { { const char code[] = "int main()\n" "{\n" @@ -1351,15 +1274,13 @@ private: } } - void simplifyKnownVariables16() - { + void simplifyKnownVariables16() { // ticket #807 - segmentation fault when macro isn't found const char code[] = "void f ( ) { int n = 1; DISPATCH(while); }"; simplifyKnownVariables(code); } - void simplifyKnownVariables17() - { + void simplifyKnownVariables17() { // ticket #807 - segmentation fault when macro isn't found const char code[] = "void f ( ) { char *s = malloc(100);mp_ptr p = s; p++; }"; ASSERT_EQUALS( @@ -1367,24 +1288,21 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables18() - { + void simplifyKnownVariables18() { const char code[] = "void f ( ) { char *s = malloc(100);mp_ptr p = s; ++p; }"; ASSERT_EQUALS( "void f ( ) { char * s ; s = malloc ( 100 ) ; mp_ptr p ; p = s ; ++ p ; }", simplifyKnownVariables(code)); } - void simplifyKnownVariables19() - { + void simplifyKnownVariables19() { const char code[] = "void f ( ) { int i=0; do { if (i>0) { a(); } i=b(); } while (i != 12); }"; ASSERT_EQUALS( "void f ( ) { int i ; i = 0 ; do { if ( 0 < i ) { a ( ) ; } i = b ( ) ; } while ( i != 12 ) ; }", simplifyKnownVariables(code)); } - void simplifyKnownVariables20() - { + void simplifyKnownVariables20() { const char code[] = "void f()\n" "{\n" " int i = 0;\n" @@ -1398,8 +1316,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables21() - { + void simplifyKnownVariables21() { const char code[] = "void foo() { int n = 10; for (int i = 0; i < n; ++i) { } }"; ASSERT_EQUALS( @@ -1407,8 +1324,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables22() - { + void simplifyKnownVariables22() { // This testcase is related to ticket #1169 { const char code[] = "void foo()\n" @@ -1456,8 +1372,7 @@ private: } } - void simplifyKnownVariables23() - { + void simplifyKnownVariables23() { // This testcase is related to ticket #1596 const char code[] = "void foo(int x)\n" "{\n" @@ -1488,8 +1403,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables24() - { + void simplifyKnownVariables24() { { // This testcase is related to ticket #1596 const char code[] = "void foo()\n" @@ -1534,8 +1448,7 @@ private: } } - void simplifyKnownVariables25() - { + void simplifyKnownVariables25() { { // This testcase is related to ticket #1646 const char code[] = "void foo(char *str)\n" @@ -1587,8 +1500,7 @@ private: } } - void simplifyKnownVariables26() - { + void simplifyKnownVariables26() { // This testcase is related to ticket #887 const char code[] = "void foo()\n" "{\n" @@ -1606,8 +1518,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables27() - { + void simplifyKnownVariables27() { // This testcase is related to ticket #1633 const char code[] = "void foo()\n" "{\n" @@ -1625,8 +1536,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables28() - { + void simplifyKnownVariables28() { const char code[] = "void foo(int g)\n" "{\n" " int i = 2;\n" @@ -1645,8 +1555,7 @@ private: simplifyKnownVariables(code)); } - void simplifyKnownVariables29() // ticket #1811 - { + void simplifyKnownVariables29() { // ticket #1811 { const char code[] = "int foo(int u, int v)\n" "{\n" @@ -1956,8 +1865,7 @@ private: } } - void simplifyKnownVariables30() - { + void simplifyKnownVariables30() { const char code[] = "int foo() {\n" " iterator it1 = ints.begin();\n" " iterator it2 = it1;\n" @@ -1971,8 +1879,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables31() - { + void simplifyKnownVariables31() { const char code[] = "void foo(const char str[]) {\n" " const char *p = str;\n" " if (p[0] == 0) {\n" @@ -1986,8 +1893,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables32() - { + void simplifyKnownVariables32() { { const char code[] = "void foo() {\n" " const int x = 0;\n" @@ -2003,8 +1909,7 @@ private: } } - void simplifyKnownVariables33() - { + void simplifyKnownVariables33() { const char code[] = "static void foo(struct Foo *foo) {\n" " foo->a = 23;\n" " x[foo->a] = 0;\n" @@ -2016,8 +1921,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables34() - { + void simplifyKnownVariables34() { const char code[] = "void f() {\n" " int x = 10;\n" " do { cin >> x; } while (x > 5);\n" @@ -2031,8 +1935,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables35() - { + void simplifyKnownVariables35() { // Ticket #2353 const char code[] = "int f() {" " int x = 0;" @@ -2045,8 +1948,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables36() - { + void simplifyKnownVariables36() { // Ticket #2304 const char code[] = "void f() {" " const char *q = \"hello\";" @@ -2056,8 +1958,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables37() - { + void simplifyKnownVariables37() { // Ticket #2398 - no simplication in for loop const char code[] = "void f() {\n" " double x = 0;\n" @@ -2078,8 +1979,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables38() - { + void simplifyKnownVariables38() { // Ticket #2399 - simplify conditions const char code[] = "void f() {\n" " int x = 0;\n" @@ -2094,8 +1994,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariables39() - { + void simplifyKnownVariables39() { // Ticket #2296 - simplify pointer alias 'delete p;' { const char code[] = "void f() {\n" @@ -2116,8 +2015,7 @@ private: } - void simplifyKnownVariables40() - { + void simplifyKnownVariables40() { const char code[] = "void f() {\n" " char c1 = 'a';\n" " char c2 = { c1 };\n" @@ -2125,8 +2023,7 @@ private: ASSERT_EQUALS("void f ( ) {\n;\nchar c2 ; c2 = { 'a' } ;\n}", tokenizeAndStringify(code, true)); } - void simplifyKnownVariables41() - { + void simplifyKnownVariables41() { const char code[] = "void f() {\n" " int x = 0;\n" " const int *p; p = &x;\n" @@ -2135,8 +2032,7 @@ private: ASSERT_EQUALS("void f ( ) {\nint x ; x = 0 ;\nconst int * p ; p = & x ;\nif ( & x ) { return 0 ; }\n}", tokenizeAndStringify(code, true)); } - void simplifyKnownVariables42() - { + void simplifyKnownVariables42() { { const char code[] = "void f() {\n" " char str1[10], str2[10];\n" @@ -2178,8 +2074,7 @@ private: } } - void simplifyKnownVariables43() - { + void simplifyKnownVariables43() { { const char code[] = "void f() {\n" " int a, *p; p = &a;\n" @@ -2205,8 +2100,7 @@ private: } } - void simplifyKnownVariablesBailOutAssign1() - { + void simplifyKnownVariablesBailOutAssign1() { const char code[] = "int foo() {\n" " int i; i = 0;\n" " if (x) { i = 10; }\n" @@ -2220,8 +2114,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariablesBailOutAssign2() - { + void simplifyKnownVariablesBailOutAssign2() { // ticket #3032 - assignment in condition const char code[] = "void f(struct ABC *list) {\n" " struct ABC *last = NULL;\n" @@ -2234,8 +2127,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariablesBailOutFor1() - { + void simplifyKnownVariablesBailOutFor1() { const char code[] = "void foo() {\n" " for (int i = 0; i < 10; ++i) { }\n" "}\n"; @@ -2246,8 +2138,7 @@ private: ASSERT_EQUALS("", errout.str()); // debug warnings } - void simplifyKnownVariablesBailOutFor2() - { + void simplifyKnownVariablesBailOutFor2() { const char code[] = "void foo() {\n" " int i = 0;\n" " while (i < 10) { ++i; }\n" @@ -2260,8 +2151,7 @@ private: ASSERT_EQUALS("", errout.str()); // debug warnings } - void simplifyKnownVariablesBailOutFor3() - { + void simplifyKnownVariablesBailOutFor3() { const char code[] = "void foo() {\n" " for (std::string::size_type pos = 0; pos < 10; ++pos)\n" " { }\n" @@ -2274,8 +2164,7 @@ private: ASSERT_EQUALS("", errout.str()); // debug warnings } - void simplifyKnownVariablesBailOutMemberFunction() - { + void simplifyKnownVariablesBailOutMemberFunction() { const char code[] = "void foo(obj a) {\n" " obj b = a;\n" " b.f();\n" @@ -2287,8 +2176,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true)); } - void simplifyKnownVariablesBailOutConditionalIncrement() - { + void simplifyKnownVariablesBailOutConditionalIncrement() { const char code[] = "int f() {\n" " int a = 0;\n" " if (x) {\n" @@ -2300,8 +2188,7 @@ private: ASSERT_EQUALS("", errout.str()); // no debug warnings } - void simplifyKnownVariablesBailOutSwitchBreak() - { + void simplifyKnownVariablesBailOutSwitchBreak() { // Ticket #2324 const char code[] = "int f(char *x) {\n" " char *p;\n" @@ -2340,8 +2227,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code,true)); } - void simplifyKnownVariablesFloat() - { + void simplifyKnownVariablesFloat() { // Ticket #2454 const char code[] = "void f() {\n" " float a = 40;\n" @@ -2353,8 +2239,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code,true)); } - void simplifyKnownVariablesClassMember() - { + void simplifyKnownVariablesClassMember() { // Ticket #2815 { const char code[] = "char *a;\n" @@ -2383,8 +2268,7 @@ private: - std::string tokenizeDebugListing(const std::string &code, bool simplify = false) - { + std::string tokenizeDebugListing(const std::string &code, bool simplify = false) { errout.str(""); Settings settings; @@ -2400,8 +2284,7 @@ private: return tokenizer.tokens()->stringifyList(true); } - void varid1() - { + void varid1() { { const std::string actual = tokenizeDebugListing( "static int i = 1;\n" @@ -2455,8 +2338,7 @@ private: } } - void varid2() - { + void varid2() { const std::string actual = tokenizeDebugListing( "void f()\n" "{\n" @@ -2476,8 +2358,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid3() - { + void varid3() { const std::string actual = tokenizeDebugListing( "static char str[4];\n" "void f()\n" @@ -2497,8 +2378,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid4() - { + void varid4() { const std::string actual = tokenizeDebugListing( "void f(const unsigned int a[])\n" "{\n" @@ -2514,8 +2394,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid5() - { + void varid5() { const std::string actual = tokenizeDebugListing( "void f()\n" "{\n" @@ -2532,8 +2411,7 @@ private: } - void varid6() - { + void varid6() { const std::string actual = tokenizeDebugListing( "int f(int a, int b)\n" "{\n" @@ -2550,8 +2428,7 @@ private: } - void varid7() - { + void varid7() { const std::string actual = tokenizeDebugListing( "void func()\n" "{\n" @@ -2573,8 +2450,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varidReturn1() - { + void varidReturn1() { const std::string actual = tokenizeDebugListing( "int f()\n" "{\n" @@ -2592,8 +2468,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varidReturn2() - { + void varidReturn2() { const std::string actual = tokenizeDebugListing( "void foo()\n" "{\n" @@ -2611,8 +2486,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid8() - { + void varid8() { const std::string actual = tokenizeDebugListing( "void func()\n" "{\n" @@ -2630,8 +2504,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid9() - { + void varid9() { const std::string actual = tokenizeDebugListing( "typedef int INT32;\n"); @@ -2641,8 +2514,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid10() - { + void varid10() { const std::string actual = tokenizeDebugListing( "void foo()\n" "{\n" @@ -2660,8 +2532,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid11() - { + void varid11() { const std::string actual = tokenizeDebugListing( "class Foo;\n"); @@ -2671,8 +2542,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid12() - { + void varid12() { const std::string actual = tokenizeDebugListing( "static void a()\n" "{\n" @@ -2688,8 +2558,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid13() - { + void varid13() { const std::string actual = tokenizeDebugListing( "void f()\n" "{\n" @@ -2707,8 +2576,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid14() - { + void varid14() { // Overloaded operator* const std::string actual = tokenizeDebugListing( "void foo()\n" @@ -2729,8 +2597,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid15() - { + void varid15() { { const std::string actual = tokenizeDebugListing( "struct S {\n" @@ -2764,8 +2631,7 @@ private: } } - void varid16() - { + void varid16() { const std::string code("void foo()\n" "{\n" " int x = 1;\n" @@ -2782,8 +2648,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid17() // ticket #1810 - { + void varid17() { // ticket #1810 const std::string code("char foo()\n" "{\n" " char c('c');\n" @@ -2800,8 +2665,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid18() - { + void varid18() { const std::string code("char foo(char c)\n" "{\n" " bar::c = c;\n" @@ -2816,8 +2680,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid19() - { + void varid19() { const std::string code("void foo()\n" "{\n" " std::pair, int> x;\n" @@ -2832,8 +2695,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid20() - { + void varid20() { const std::string code("void foo()\n" "{\n" " pair, vector > x;\n" @@ -2848,8 +2710,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid21() - { + void varid21() { const std::string code("void foo()\n" "{\n" " vector x;\n" @@ -2864,8 +2725,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid22() - { + void varid22() { const std::string code("class foo()\n" "{\n" "public:\n" @@ -2882,8 +2742,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid23() - { + void varid23() { const std::string code("class foo()\n" "{\n" "public:\n" @@ -2900,8 +2759,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid24() - { + void varid24() { const std::string code("class foo()\n" "{\n" "public:\n" @@ -2922,8 +2780,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid25() - { + void varid25() { const std::string code("class foo()\n" "{\n" "public:\n" @@ -2944,16 +2801,14 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid26() - { + void varid26() { const std::string code("list functions;\n"); const std::string expected("\n\n##file 0\n" "1: list < int ( * ) ( ) > functions@1 ;\n"); ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid27() - { + void varid27() { const std::string code("int fooled_ya;\n" "fooled_ya::iterator iter;\n"); const std::string expected("\n\n##file 0\n" @@ -2962,14 +2817,12 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid28() // ticket #2630 (segmentation fault) - { + void varid28() { // ticket #2630 (segmentation fault) tokenizeDebugListing("template \n"); ASSERT_EQUALS("", errout.str()); } - void varid29() - { + void varid29() { const std::string code("class A {\n" " B,1> b;\n" "};\n"); @@ -2980,8 +2833,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varid30() // ticket #2614 - { + void varid30() { // ticket #2614 const std::string code1("void f(EventPtr *eventP, ActionPtr **actionsP)\n" "{\n" " EventPtr event = *eventP;\n" @@ -3026,26 +2878,22 @@ private: ASSERT_EQUALS(expected3, tokenizeDebugListing(code3)); } - void varid31() // ticket #2831 (segmentation fault) - { + void varid31() { // ticket #2831 (segmentation fault) const std::string code("z"); ASSERT_EQUALS("", errout.str()); } - void varid32() // ticket #2835 (segmentation fault) - { + void varid32() { // ticket #2835 (segmentation fault) const std::string code("><,f ints;\n" "list::iterator it;\n" @@ -3165,8 +3007,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid_delete() - { + void varid_delete() { const std::string actual = tokenizeDebugListing( "void f()\n" "{\n" @@ -3184,8 +3025,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid_functions() - { + void varid_functions() { { const std::string actual = tokenizeDebugListing( "void f();\n" @@ -3248,8 +3088,7 @@ private: } - void varid_reference_to_containers() - { + void varid_reference_to_containers() { const std::string actual = tokenizeDebugListing( "void f()\n" "{\n" @@ -3269,8 +3108,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid_in_class1() - { + void varid_in_class1() { { const std::string actual = tokenizeDebugListing( "class Foo\n" @@ -3326,8 +3164,7 @@ private: } } - void varid_in_class2() - { + void varid_in_class2() { const std::string actual = tokenizeDebugListing( "struct Foo {\n" " int x;\n" @@ -3361,8 +3198,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid_operator() - { + void varid_operator() { { const std::string actual = tokenizeDebugListing( "class Foo\n" @@ -3394,8 +3230,7 @@ private: } } - void varid_throw() // ticket #1723 - { + void varid_throw() { // ticket #1723 const std::string actual = tokenizeDebugListing( "UserDefinedException* pe = new UserDefinedException();\n" "throw pe;\n"); @@ -3407,8 +3242,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varid_unknown_macro() - { + void varid_unknown_macro() { // #2638 - unknown macro const char code[] = "void f() {\n" " int a[10];\n" @@ -3424,8 +3258,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass1() - { + void varidclass1() { const std::string actual = tokenizeDebugListing( "class Fred\n" "{\n" @@ -3466,8 +3299,7 @@ private: } - void varidclass2() - { + void varidclass2() { const std::string actual = tokenizeDebugListing( "class Fred\n" "{ void f(); };\n" @@ -3500,8 +3332,7 @@ private: } - void varidclass3() - { + void varidclass3() { const std::string actual = tokenizeDebugListing( "class Fred\n" "{ int i; void f(); };\n" @@ -3534,8 +3365,7 @@ private: } - void varidclass4() - { + void varidclass4() { const std::string actual = tokenizeDebugListing( "class Fred\n" "{ int i; void f(); };\n" @@ -3559,8 +3389,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varidclass5() - { + void varidclass5() { const std::string actual = tokenizeDebugListing( "class A { };\n" "class B\n" @@ -3582,8 +3411,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varidclass6() - { + void varidclass6() { const std::string actual = tokenizeDebugListing( "class A\n" "{\n" @@ -3614,8 +3442,7 @@ private: TODO_ASSERT_EQUALS(wanted, current, actual); } - void varidclass7() - { + void varidclass7() { const std::string actual = tokenizeDebugListing( "int main()\n" "{\n" @@ -3633,8 +3460,7 @@ private: ASSERT_EQUALS(expected, actual); } - void varidclass8() - { + void varidclass8() { const std::string code("class Fred {\n" "public:\n" " void foo(int d) {\n" @@ -3655,8 +3481,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass9() - { + void varidclass9() { const std::string code("typedef char Str[10];" "class A {\n" "public:\n" @@ -3681,8 +3506,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass10() - { + void varidclass10() { const std::string code("class A {\n" " void f() {\n" " a = 3;\n" @@ -3700,8 +3524,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass11() - { + void varidclass11() { const std::string code("class Fred {\n" " int a;\n" " void f();\n" @@ -3728,8 +3551,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass12() - { + void varidclass12() { const std::string code("class Fred {\n" " int a;\n" " void f() { Fred::a = 0; }\n" @@ -3744,8 +3566,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void varidclass13() - { + void varidclass13() { const std::string code("class Fred {\n" " int a;\n" " void f() { Foo::Fred::a = 0; }\n" @@ -3760,8 +3581,7 @@ private: ASSERT_EQUALS(expected, tokenizeDebugListing(code)); } - void file1() - { + void file1() { const char code[] = "a1\n" "#file \"b\"\n" "b1\n" @@ -3778,8 +3598,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "a"); - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { std::ostringstream ostr; ostr << char('a' + tok->fileIndex()) << tok->linenr(); ASSERT_EQUALS(tok->str(), ostr.str()); @@ -3787,8 +3606,7 @@ private: } - void file2() - { + void file2() { const char code[] = "a1\n" "#file \"b\"\n" "b1\n" @@ -3814,8 +3632,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "a"); - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { std::ostringstream ostr; ostr << char('a' + tok->fileIndex()) << tok->linenr(); ASSERT_EQUALS(tok->str(), ostr.str()); @@ -3824,8 +3641,7 @@ private: - void file3() - { + void file3() { const char code[] = "#file \"c:\\a.h\"\n" "123\n" "#endfile\n"; @@ -3845,8 +3661,7 @@ private: - void doublesharp() - { + void doublesharp() { const char code[] = "TEST(var,val) var##_##val = val\n"; errout.str(""); @@ -3866,8 +3681,7 @@ private: ASSERT_EQUALS("TEST ( var , val ) var_val = val ", ostr.str()); } - void macrodoublesharp() - { + void macrodoublesharp() { const char code[] = "DBG(fmt,args...) printf(fmt, ## args)\n"; errout.str(""); @@ -3887,8 +3701,7 @@ private: ASSERT_EQUALS("DBG ( fmt , args . . . ) printf ( fmt , ## args ) ", ostr.str()); } - void simplify_function_parameters() - { + void simplify_function_parameters() { { const char code[] = "char a [ ABC ( DEF ) ] ;"; ASSERT_EQUALS(code, tokenizeAndStringify(code, true)); @@ -3918,8 +3731,7 @@ private: } // Simplify "((..))" into "(..)" - void removeParentheses1() - { + void removeParentheses1() { const char code[] = "void foo()" "{" " free(((void*)p));" @@ -3928,8 +3740,7 @@ private: ASSERT_EQUALS("void foo ( ) { free ( p ) ; }", tokenizeAndStringify(code, true)); } - void removeParentheses2() - { + void removeParentheses2() { const char code[] = "void foo()" "{" " if (__builtin_expect((s == NULL), 0))" @@ -3939,8 +3750,7 @@ private: ASSERT_EQUALS("void foo ( ) { if ( ! s ) { return ; } }", tokenizeAndStringify(code)); } - void removeParentheses3() - { + void removeParentheses3() { { const char code[] = "void foo()" "{" @@ -3967,8 +3777,7 @@ private: } // Simplify "( function (..))" into "function (..)" - void removeParentheses4() - { + void removeParentheses4() { const char code[] = "void foo()" "{" " (free(p));" @@ -3976,8 +3785,7 @@ private: ASSERT_EQUALS("void foo ( ) { free ( p ) ; }", tokenizeAndStringify(code)); } - void removeParentheses5() - { + void removeParentheses5() { // Simplify "( delete x )" into "delete x" { const char code[] = "void foo()" @@ -3998,20 +3806,17 @@ private: } // "!(abc.a)" => "!abc.a" - void removeParentheses6() - { + void removeParentheses6() { const char code[] = "(!(abc.a))"; ASSERT_EQUALS("( ! abc . a )", tokenizeAndStringify(code)); } - void removeParentheses7() - { + void removeParentheses7() { const char code[] = ";char *p; (delete(p), (p)=0);"; ASSERT_EQUALS("; char * p ; delete p ; p = 0 ;", tokenizeAndStringify(code,true)); } - void removeParentheses8() - { + void removeParentheses8() { const char code[] = "struct foo {\n" " void operator delete(void *obj, size_t sz);\n" "}\n"; @@ -4024,30 +3829,25 @@ private: ASSERT_EQUALS(expected, actual); } - void removeParentheses9() - { + void removeParentheses9() { ASSERT_EQUALS("void delete ( double num ) ;", tokenizeAndStringify("void delete(double num);", false)); } - void removeParentheses10() - { + void removeParentheses10() { ASSERT_EQUALS("p = buf + 8 ;", tokenizeAndStringify("p = (buf + 8);", false)); } - void removeParentheses11() - { + void removeParentheses11() { // #2502 ASSERT_EQUALS("{ } x ( ) ;", tokenizeAndStringify("{}(x());", false)); } - void removeParentheses12() - { + void removeParentheses12() { // #2760 ASSERT_EQUALS(", x = 0 ;", tokenizeAndStringify(",(x)=0;", false)); } - void tokenize_double() - { + void tokenize_double() { const char code[] = "void f()\n" "{\n" " double a = 4.2;\n" @@ -4072,8 +3872,7 @@ private: ASSERT_EQUALS(" void f ( ) { double a ; a = 4.2 ; float b ; b = 4.2f ; double c ; c = 4.2e+10 ; double d ; d = 4.2e-10 ; int e ; e = 4 + 2 ; }", ostr.str()); } - void tokenize_strings() - { + void tokenize_strings() { const char code[] = "void f()\n" "{\n" "const char *a =\n" @@ -4100,8 +3899,7 @@ private: ASSERT_EQUALS(" void f ( ) { const char * a ; a = { \"hello more world\" } ; }", ostr.str()); } - void simplify_constants() - { + void simplify_constants() { const char code[] = "void f()\n" "{\n" @@ -4132,8 +3930,7 @@ private: ASSERT_EQUALS(" void f ( ) { ; { ; } } void g ( ) { ; }", ostr.str()); } - void simplify_constants2() - { + void simplify_constants2() { const char code[] = "void f( Foo &foo, Foo *foo2 )\n" "{\n" @@ -4163,8 +3960,7 @@ private: ASSERT_EQUALS(oss.str(), ostr.str()); } - void simplify_constants3() - { + void simplify_constants3() { const char code[] = "static const char str[] = \"abcd\";\n" "static const unsigned int SZ = sizeof(str);\n" @@ -4176,8 +3972,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code,true)); } - void simplify_null() - { + void simplify_null() { const char code[] = "int * p = NULL;\n" "int * q = __null;\n"; @@ -4186,8 +3981,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code,true)); } - void simplifyMulAnd() - { + void simplifyMulAnd() { // (error) Resource leak ASSERT_EQUALS( "void f ( ) { int f ; f = open ( ) ; }", @@ -4203,8 +3997,7 @@ private: ); } - void vardecl1() - { + void vardecl1() { const char code[] = "unsigned int a, b;"; const std::string actual(tokenizeAndStringify(code)); @@ -4212,8 +4005,7 @@ private: ASSERT_EQUALS("unsigned int a ; unsigned int b ;", actual); } - void vardecl2() - { + void vardecl2() { const char code[] = "void foo(a,b) unsigned int a, b; { }"; const std::string actual(tokenizeAndStringify(code)); @@ -4221,15 +4013,13 @@ private: ASSERT_EQUALS("void foo ( a , b ) unsigned int a ; unsigned int b ; { }", actual); } - void vardecl3() - { + void vardecl3() { const char code[] = "void f() { char * p = foo<10,char>(); }"; const std::string actual(tokenizeAndStringify(code)); ASSERT_EQUALS("void f ( ) { char * p ; p = foo < 10 , char > ( ) ; }", actual); } - void vardecl4() - { + void vardecl4() { // ticket #346 const char code1[] = "void *p = NULL;"; @@ -4249,8 +4039,7 @@ private: ASSERT_EQUALS(res4, tokenizeAndStringify(code4)); } - void vardecl_stl_1() - { + void vardecl_stl_1() { // ticket #520 const char code1[] = "std::vectora, b;"; @@ -4266,8 +4055,7 @@ private: ASSERT_EQUALS(res3, tokenizeAndStringify(code3)); } - void vardecl_stl_2() - { + void vardecl_stl_2() { const char code1[] = "{ std::string x = \"abc\"; }"; ASSERT_EQUALS("{ std :: string x ; x = \"abc\" ; }", tokenizeAndStringify(code1)); @@ -4275,16 +4063,14 @@ private: ASSERT_EQUALS("{ std :: vector < int > x ; x = y ; }", tokenizeAndStringify(code2)); } - void vardecl_template() - { + void vardecl_template() { // ticket #1046 const char code1[] = "b<(1<<24),10,24> u, v;"; const char res1[] = "b < ( 1 << 24 ) , 10 , 24 > u ; b < ( 1 << 24 ) , 10 , 24 > v ;"; ASSERT_EQUALS(res1, tokenizeAndStringify(code1)); } - void vardecl_union() - { + void vardecl_union() { // ticket #1976 const char code1[] = "class Fred { public: union { int a ; int b ; } ; } ;"; ASSERT_EQUALS(code1, tokenizeAndStringify(code1)); @@ -4299,8 +4085,7 @@ private: ASSERT_EQUALS("void f ( ) {\n\nint x ;\nlong & y = x ;\n\n}", tokenizeAndStringify(code2)); } - void vardecl_par() - { + void vardecl_par() { // ticket #2743 - set links if variable type contains parentheses const char code[] = "Fred fred1=a, fred2=b;"; @@ -4311,8 +4096,7 @@ private: ASSERT_EQUALS(true, tokenizer.validate()); } - void vardec_static() - { + void vardec_static() { { // don't simplify declarations of static variables // "static int i = 0;" is not the same as "static int i; i = 0;" @@ -4346,8 +4130,7 @@ private: } } - void vardecl6() - { + void vardecl6() { // ticket #565 const char code1[] = "int z = x >> 16;"; @@ -4355,8 +4138,7 @@ private: ASSERT_EQUALS(res1, tokenizeAndStringify(code1)); } - void vardecl7() - { + void vardecl7() { // ticket #603 const char code[] = "void f() {\n" " for (int c = 0; c < 0; ++c) {}\n" @@ -4372,8 +4154,7 @@ private: ASSERT_EQUALS(res, tokenizeAndStringify(code)); } - void vardecl8() - { + void vardecl8() { // ticket #696 const char code[] = "char a[10]={'\\0'}, b[10]={'\\0'};"; const char res[] = "char a [ 10 ] = { 0 } ; char b [ 10 ] = { 0 } ;"; @@ -4381,50 +4162,43 @@ private: ASSERT_EQUALS(res, tokenizeAndStringify(code)); } - void vardecl9() - { + void vardecl9() { const char code[] = "char a[2] = {'A', '\\0'}, b[2] = {'B', '\\0'};"; const char res[] = "char a [ 2 ] = { 'A' , 0 } ; char b [ 2 ] = { 'B' , 0 } ;"; ASSERT_EQUALS(res, tokenizeAndStringify(code)); } - void vardecl10() - { + void vardecl10() { // ticket #732 const char code[] = "char a [ 2 ] = { '-' } ; memset ( a , '-' , sizeof ( a ) ) ;"; ASSERT_EQUALS(code, tokenizeAndStringify(code)); } - void vardecl11() - { + void vardecl11() { // ticket #1684 const char code[] = "char a[5][8], b[5][8];"; ASSERT_EQUALS("char a [ 5 ] [ 8 ] ; char b [ 5 ] [ 8 ] ;", tokenizeAndStringify(code)); } - void vardecl12() - { + void vardecl12() { const char code[] = "struct A { public: B a, b, c, d; };"; ASSERT_EQUALS("struct A { public: B a ; B b ; B c ; B d ; } ;", tokenizeAndStringify(code)); } - void vardecl13() - { + void vardecl13() { const char code[] = "void f() {\n" " int a = (x < y) ? 1 : 0;\n" "}"; ASSERT_EQUALS("void f ( ) {\nint a ; a = ( x < y ) ? 1 : 0 ;\n}", tokenizeAndStringify(code)); } - void vardecl14() - { + void vardecl14() { const char code[] = "::std::tr1::shared_ptr pNum1, pNum2;\n"; ASSERT_EQUALS(":: std :: tr1 :: shared_ptr < int > pNum1 ; :: std :: tr1 :: shared_ptr < int > pNum2 ;", tokenizeAndStringify(code)); } - void volatile_variables() - { + void volatile_variables() { const char code[] = "volatile int a=0;\n" "volatile int b=0;\n" "volatile int c=0;\n"; @@ -4434,8 +4208,7 @@ private: ASSERT_EQUALS("int a ; a = 0 ;\nint b ; b = 0 ;\nint c ; c = 0 ;", actual); } - void syntax_error() - { + void syntax_error() { { errout.str(""); const char code[] = "void f() {}"; @@ -4533,8 +4306,7 @@ private: } - void syntax_error_templates_1() - { + void syntax_error_templates_1() { // ok code.. using ">" for a comparison { errout.str(""); @@ -4613,16 +4385,14 @@ private: } } - void syntax_error_templates_2() - { + void syntax_error_templates_2() { std::istringstream istr("template<>\n"); Settings settings; Tokenizer tokenizer(&settings, this); tokenizer.tokenize(istr, "test.cpp"); // shouldn't segfault } - void removeKeywords() - { + void removeKeywords() { const char code[] = "if (__builtin_expect(!!(x), 1));"; const std::string actual(tokenizeAndStringify(code, true)); @@ -4634,8 +4404,7 @@ private: /** * tokenize "signed i" => "signed int i" */ - void signed1() - { + void signed1() { { const char code1[] = "void foo ( signed int , float ) ;"; ASSERT_EQUALS(code1, tokenizeAndStringify(code1)); @@ -4669,8 +4438,7 @@ private: * tokenize "unsigned i" => "unsigned int i" * tokenize "unsigned" => "unsigned int" */ - void unsigned1() - { + void unsigned1() { // No changes.. { const char code[] = "void foo ( unsigned int , float ) ;"; @@ -4705,16 +4473,14 @@ private: } } - void unsigned2() - { + void unsigned2() { const char code[] = "i = (unsigned)j;"; const char expected[] = "i = ( unsigned int ) j ;"; ASSERT_EQUALS(expected, tokenizeAndStringify(code)); } // simplify "unsigned" when using templates.. - void unsigned3() - { + void unsigned3() { { const char code[] = "; foo();"; const char expected[] = "; foo ( ) ;"; @@ -4728,8 +4494,7 @@ private: } } - void createLinks() - { + void createLinks() { { const char code[] = "class A{\n" " void f() {}\n" @@ -4797,8 +4562,7 @@ private: } } - void removeExceptionSpecification1() - { + void removeExceptionSpecification1() { const char code[] = "class A\n" "{\n" "private:\n" @@ -4818,8 +4582,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code)); } - void removeExceptionSpecification2() - { + void removeExceptionSpecification2() { const char code[] = "class A\n" "{\n" "private:\n" @@ -4843,8 +4606,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code)); } - void removeExceptionSpecification3() - { + void removeExceptionSpecification3() { const char code[] = "namespace A {\n" " struct B {\n" " B() throw ()\n" @@ -4863,8 +4625,7 @@ private: } - void gt() - { + void gt() { ASSERT_EQUALS("( i < 10 )", tokenizeAndStringify("(10>i)")); ASSERT_EQUALS("; i < 10 ;", tokenizeAndStringify(";10>i;")); ASSERT_EQUALS("void > ( ) ; void > ( )", @@ -4872,8 +4633,7 @@ private: } - void simplifyString() - { + void simplifyString() { errout.str(""); Settings settings; Tokenizer tokenizer(&settings, this); @@ -4883,8 +4643,7 @@ private: ASSERT_EQUALS("\"a3\"", tokenizer.simplifyString("\"\\x333\"")); } - void simplifyConst() - { + void simplifyConst() { ASSERT_EQUALS("void foo ( ) { const int x ; }", tokenizeAndStringify("void foo(){ int const x;}")); @@ -4905,14 +4664,12 @@ private: } - void switchCase() - { + void switchCase() { ASSERT_EQUALS("void foo ( int i ) { switch ( i ) { case -1 : break ; } }", tokenizeAndStringify("void foo (int i) { switch(i) { case -1: break; } }")); } - std::string simplifyFunctionPointers(const char code[]) - { + std::string simplifyFunctionPointers(const char code[]) { errout.str(""); Settings settings; Tokenizer tokenizer(&settings, this); @@ -4920,8 +4677,7 @@ private: tokenizer.tokenize(istr, "test.cpp"); tokenizer.simplifyFunctionPointers(); std::ostringstream ostr; - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (tok->isUnsigned()) ostr << " unsigned"; else if (tok->isSigned()) @@ -4933,16 +4689,14 @@ private: return ostr.str(); } - void functionpointer1() - { + void functionpointer1() { ASSERT_EQUALS(" void* f;", simplifyFunctionPointers("void (*f)();")); ASSERT_EQUALS(" void** f;", simplifyFunctionPointers("void *(*f)();")); ASSERT_EQUALS(" unsigned int* f;", simplifyFunctionPointers("unsigned int (*f)();")); ASSERT_EQUALS(" unsigned int** f;", simplifyFunctionPointers("unsigned int * (*f)();")); } - void functionpointer2() - { + void functionpointer2() { const char code[] = "typedef void (* PF)();" "void f1 ( ) { }" "PF pf = &f1;" @@ -4954,8 +4708,7 @@ private: ASSERT_EQUALS(expected, simplifyFunctionPointers(code)); } - void functionpointer3() - { + void functionpointer3() { // Related with ticket #2873 const char code[] = "void f() {\n" "(void)(xy(*p)(0);)" @@ -4966,15 +4719,13 @@ private: ASSERT_EQUALS(expected, simplifyFunctionPointers(code)); } - void removeRedundantAssignment() - { + void removeRedundantAssignment() { ASSERT_EQUALS("void f ( ) { ; int * q ; }", tokenizeAndStringify("void f() { int *p, *q; p = q; }", true)); ASSERT_EQUALS("void f ( ) { ; int * q ; }", tokenizeAndStringify("void f() { int *p = 0, *q; p = q; }", true)); ASSERT_EQUALS("int f ( int * x ) { return * x ; }", tokenizeAndStringify("int f(int *x) { return *x; }", true)); } - void removedeclspec() - { + void removedeclspec() { ASSERT_EQUALS("a b", tokenizeAndStringify("a __declspec ( dllexport ) b")); ASSERT_EQUALS("int a ;", tokenizeAndStringify("__declspec(thread) __declspec(align(32)) int a;")); ASSERT_EQUALS("int i ;", tokenizeAndStringify("__declspec(allocate(\"mycode\")) int i;")); @@ -4982,15 +4733,13 @@ private: ASSERT_EQUALS("int x [ ] ;", tokenizeAndStringify("__declspec(property(get=GetX, put=PutX)) int x[];")); } - void removeattribute() - { + void removeattribute() { ASSERT_EQUALS("short array [ 3 ] ;", tokenizeAndStringify("short array[3] __attribute__ ((aligned));")); ASSERT_EQUALS("int x [ 2 ] ;", tokenizeAndStringify("int x[2] __attribute__ ((packed));")); ASSERT_EQUALS("int vecint ;", tokenizeAndStringify("int __attribute__((mode(SI))) __attribute__((vector_size (16))) vecint;")); } - void cpp0xtemplate1() - { + void cpp0xtemplate1() { const char *code = "template \n" "void fn2 (T t = []{return 1;}())\n" "{}\n" @@ -5001,16 +4750,14 @@ private: ASSERT_EQUALS(";\n\n\nint main ( )\n{\nfn2 ( ) ;\n}void fn2 ( int t = [ ] { return 1 ; } ( ) )\n{ }", tokenizeAndStringify(code)); } - void cpp0xtemplate2() - { + void cpp0xtemplate2() { // tokenize ">>" into "> >" const char *code = "list> ints;\n"; TODO_ASSERT_EQUALS("list < list < int > > ints ;", "list < list < int >> ints ;", tokenizeAndStringify(code)); } - void cpp0xtemplate3() - { + void cpp0xtemplate3() { // #2549 const char *code = "template\n" "struct S\n" @@ -5021,8 +4768,7 @@ private: tokenizeAndStringify(code)); } - void cpp0xdefault() - { + void cpp0xdefault() { { const char *code = "struct foo {" " foo() = default;" @@ -5055,8 +4801,7 @@ private: } } - std::string arraySize_(const std::string &code) - { + std::string arraySize_(const std::string &code) { errout.str(""); Settings settings; // tokenize.. @@ -5065,8 +4810,7 @@ private: tokenizer.tokenize(istr, "test.cpp"); std::ostringstream ostr; - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (tok->isName()) ostr << " "; ostr << tok->str(); @@ -5075,20 +4819,17 @@ private: return ostr.str(); } - void arraySize() - { + void arraySize() { ASSERT_EQUALS("; int a[3]={1,2,3};", arraySize_(";int a[]={1,2,3};")); ASSERT_EQUALS("; int a[]={ ABC,2,3};", arraySize_(";int a[]={ABC,2,3};")); } - std::string labels_(const std::string &code) - { + std::string labels_(const std::string &code) { // the arraySize_ does what we want currently.. return arraySize_(code); } - void labels() - { + void labels() { ASSERT_EQUALS(" void f(){ ab:; a=0;}", labels_("void f() { ab: a=0; }")); //ticket #3176 ASSERT_EQUALS(" void f(){ ab:;(* func)();}", labels_("void f() { ab: (*func)(); }")); @@ -5113,8 +4854,7 @@ private: } // Check simplifyInitVar - void checkSimplifyInitVar(const char code[], bool simplify = false) - { + void checkSimplifyInitVar(const char code[], bool simplify = false) { // Tokenize.. Settings settings; settings.inconclusive = true; @@ -5130,8 +4870,7 @@ private: tokenizer.validate(); } - void simplifyInitVar() - { + void simplifyInitVar() { { const char code[] = "int i ; int p(0);"; ASSERT_EQUALS("int i ; int p ; p = 0 ;", tokenizeAndStringify(code)); @@ -5338,8 +5077,7 @@ private: } } - void bitfields1() - { + void bitfields1() { const char code1[] = "struct A { bool x : 1; };"; ASSERT_EQUALS("struct A { bool x ; } ;", tokenizeAndStringify(code1,false)); @@ -5416,8 +5154,7 @@ private: ASSERT_EQUALS("struct A { signed long long x ; } ;", tokenizeAndStringify(code25,false)); } - void bitfields2() - { + void bitfields2() { const char code1[] = "struct A { public: int x : 3; };"; ASSERT_EQUALS("struct A { public: int x ; } ;", tokenizeAndStringify(code1,false)); @@ -5437,8 +5174,7 @@ private: ASSERT_EQUALS("struct A { private: unsigned long x ; } ;", tokenizeAndStringify(code6,false)); } - void bitfields3() - { + void bitfields3() { const char code1[] = "struct A { const int x : 3; };"; ASSERT_EQUALS("struct A { const int x ; } ;", tokenizeAndStringify(code1,false)); @@ -5452,8 +5188,7 @@ private: ASSERT_EQUALS("struct A { public: const unsigned long x ; } ;", tokenizeAndStringify(code4,false)); } - void bitfields4() // ticket #1956 - { + void bitfields4() { // ticket #1956 const char code1[] = "struct A { CHAR x : 3; };"; ASSERT_EQUALS("struct A { CHAR x ; } ;", tokenizeAndStringify(code1,false)); @@ -5485,8 +5220,7 @@ private: ASSERT_EQUALS("struct A { UINT64 x ; } ;", tokenizeAndStringify(code10,false)); } - void bitfields5() // ticket #1956 - { + void bitfields5() { // ticket #1956 const char code1[] = "struct RGB { unsigned int r : 3, g : 3, b : 2; };"; ASSERT_EQUALS("struct RGB { unsigned int r ; unsigned int g ; unsigned int b ; } ;", tokenizeAndStringify(code1,false)); @@ -5497,8 +5231,7 @@ private: ASSERT_EQUALS("struct A { virtual void f ( ) { } int f1 ; } ;", tokenizeAndStringify(code3,false)); } - void bitfields6() // ticket #2595 - { + void bitfields6() { // ticket #2595 const char code1[] = "struct A { bool b : true; };"; ASSERT_EQUALS("struct A { bool b ; } ;", tokenizeAndStringify(code1,false)); @@ -5515,8 +5248,7 @@ private: ASSERT_EQUALS("void f ( int a ) { switch ( a ) { default : ; break ; } }", tokenizeAndStringify(code5,true)); } - void bitfields7() // ticket #1987 - { + void bitfields7() { // ticket #1987 const char code[] = "typedef struct Descriptor {" " unsigned element_size: 8* sizeof( unsigned );" "} Descriptor;"; @@ -5527,8 +5259,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void bitfields8() - { + void bitfields8() { const char code[] = "struct A;" "class B : virtual public C" "{" @@ -5543,8 +5274,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void bitfields9() // ticket #2706 - { + void bitfields9() { // ticket #2706 const char code[] = "void f() {\n" " goto half;\n" "half:\n" @@ -5556,8 +5286,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void bitfields10() // ticket #2737 - { + void bitfields10() { // ticket #2737 const char code[] = "{}" "MACRO " "default: { }" @@ -5565,16 +5294,14 @@ private: ASSERT_EQUALS("{ } MACRO default : { } ;", tokenizeAndStringify(code,false)); } - void bitfields11() // ticket #2845 (segmentation fault) - { + void bitfields11() { // ticket #2845 (segmentation fault) const char code[] = "#if b&&a\n" "#ifdef y z:\n"; tokenizeAndStringify(code,false); ASSERT_EQUALS("", errout.str()); } - void microsoftMFC() - { + void microsoftMFC() { const char code1[] = "class MyDialog : public CDialog { DECLARE_MESSAGE_MAP() private: CString text; };"; ASSERT_EQUALS("class MyDialog : public CDialog { private: CString text ; } ;", tokenizeAndStringify(code1,false,true,Settings::Win32A)); @@ -5588,8 +5315,7 @@ private: ASSERT_EQUALS("class MyDialog : public CDialog { private: CString text ; } ;", tokenizeAndStringify(code4,false,true,Settings::Win32A)); } - void microsoftMemory() - { + void microsoftMemory() { const char code1[] = "void foo() { int a[10], b[10]; CopyMemory(a, b, sizeof(a)); }"; ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memcpy ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code1,false,true,Settings::Win32A)); @@ -5609,8 +5335,7 @@ private: ASSERT_EQUALS("void foo ( ) { memset ( f ( 1 , g ( a , b ) ) , 255 , h ( i , j ( 0 , 1 ) ) ) ; }", tokenizeAndStringify(code6,false,true,Settings::Win32A)); } - void borland() - { + void borland() { // __closure ASSERT_EQUALS("int * a ;", tokenizeAndStringify("int (__closure *a)();", false)); @@ -5620,8 +5345,7 @@ private: tokenizeAndStringify("class Fred { __property int x = { } };", false)); } - void Qt() - { + void Qt() { const char code1[] = "class Counter : public QObject " "{ " " Q_OBJECT " @@ -5727,8 +5451,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void sql() - { + void sql() { // Oracle PRO*C extensions for inline SQL. Just replace the SQL with "asm()" to fix wrong error messages // ticket: #1959 const char code1[] = "; EXEC SQL SELECT A FROM B;"; @@ -5736,8 +5459,7 @@ private: } - void simplifyLogicalOperators() - { + void simplifyLogicalOperators() { ASSERT_EQUALS("if ( a && b )", tokenizeAndStringify("if (a and b)")); ASSERT_EQUALS("if ( a || b )", tokenizeAndStringify("if (a or b)")); ASSERT_EQUALS("if ( a & b )", tokenizeAndStringify("if (a bitand b)")); @@ -5748,8 +5470,7 @@ private: ASSERT_EQUALS("if ( a != b )", tokenizeAndStringify("if (a not_eq b)")); } - void simplifyCalculations() - { + void simplifyCalculations() { ASSERT_EQUALS("void foo ( char str [ ] ) { char x ; x = * str ; }", tokenizeAndStringify("void foo ( char str [ ] ) { char x = 0 | ( * str ) ; }", true)); ASSERT_EQUALS("void foo ( ) { if ( b ) { } }", @@ -5772,8 +5493,7 @@ private: tokenizeAndStringify("bool f(int i) { switch (i) { case 10 + 5: return true; } }", true)); } - void simplifyCompoundAssignment() - { + void simplifyCompoundAssignment() { ASSERT_EQUALS("; x = x + y ;", tokenizeAndStringify("; x += y;")); ASSERT_EQUALS("; x = x - y ;", tokenizeAndStringify("; x -= y;")); ASSERT_EQUALS("; x = x * y ;", tokenizeAndStringify("; x *= y;")); @@ -5825,18 +5545,15 @@ private: ASSERT_EQUALS("; a = a * ( b + 1 ) ;", tokenizeAndStringify("; a*=b+1;")); } - void simplifyAssignmentInFunctionCall() - { + void simplifyAssignmentInFunctionCall() { ASSERT_EQUALS("; x = g ( ) ; f ( x ) ;", tokenizeAndStringify(";f(x=g());")); } - void cs() - { + void cs() { ASSERT_EQUALS("; int * i ;", tokenizeAndStringify("; int [] i;")); } - std::string javatest(const char javacode[]) - { + std::string javatest(const char javacode[]) { errout.str(""); Settings settings; // tokenize.. @@ -5845,8 +5562,7 @@ private: tokenizer.tokenize(istr, "test.java"); std::ostringstream ostr; - for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) - { + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { ostr << tok->str(); if (tok->next()) ostr << " "; @@ -5856,13 +5572,11 @@ private: } - void java() - { + void java() { ASSERT_EQUALS("void f ( ) { }", javatest("void f() throws Exception { }")); } - void simplifyOperatorName1() - { + void simplifyOperatorName1() { // make sure C code doesn't get changed const char code[] = "void operator () {}" "int main()" @@ -5879,8 +5593,7 @@ private: ASSERT_EQUALS(result, tokenizeAndStringify(code,false)); } - void simplifyOperatorName2() - { + void simplifyOperatorName2() { const char code[] = "class Fred" "{" " Fred(const Fred & f) { operator = (f); }" @@ -5896,8 +5609,7 @@ private: ASSERT_EQUALS(result, tokenizeAndStringify(code,false)); } - void simplifyOperatorName3() - { + void simplifyOperatorName3() { // #2615 const char code[] = "void f() {" "static_cast(xResult.operator->())->GetMatrix();" @@ -5906,15 +5618,13 @@ private: ASSERT_EQUALS(result, tokenizeAndStringify(code,false)); } - void simplifyOperatorName4() - { + void simplifyOperatorName4() { const char code[] = "void operator==() { }"; const char result[] = "void operator== ( ) { }"; ASSERT_EQUALS(result, tokenizeAndStringify(code,false)); } - void simplifyOperatorName5() - { + void simplifyOperatorName5() { const char code1[] = "std::istream & operator >> (std::istream & s, Fred &f);"; const char result1[] = "std :: istream & operator>> ( std :: istream & s , Fred & f ) ;"; ASSERT_EQUALS(result1, tokenizeAndStringify(code1,false)); @@ -5924,8 +5634,7 @@ private: ASSERT_EQUALS(result2, tokenizeAndStringify(code2,false)); } - void simplifyOperatorName6() // ticket #3195 - { + void simplifyOperatorName6() { // ticket #3195 const char code1[] = "value_type * operator ++ (int);"; const char result1[] = "value_type * operator++ ( int ) ;"; ASSERT_EQUALS(result1, tokenizeAndStringify(code1,false)); @@ -5935,21 +5644,18 @@ private: ASSERT_EQUALS(result2, tokenizeAndStringify(code2,false)); } - void removeMacrosInGlobalScope() - { + void removeMacrosInGlobalScope() { // remove some unhandled macros in the global scope. ASSERT_EQUALS("void f ( ) { }", tokenizeAndStringify("void f() NOTHROW { }")); ASSERT_EQUALS("struct Foo { } ;", tokenizeAndStringify("struct __declspec(dllexport) Foo {};")); ASSERT_EQUALS("ABA ( ) namespace { }", tokenizeAndStringify("ABA() namespace { }")); } - void multipleAssignment() - { + void multipleAssignment() { ASSERT_EQUALS("a = b = 0 ;", tokenizeAndStringify("a=b=0;")); } - void simplifyIfAddBraces() // ticket # 2739 (segmentation fault) - { + void simplifyIfAddBraces() { // ticket # 2739 (segmentation fault) tokenizeAndStringify("if()x"); ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); @@ -5963,8 +5669,7 @@ private: } } - void platformWin32() - { + void platformWin32() { const char code[] = "unsigned int sizeof_short = sizeof(short);" "unsigned int sizeof_unsigned_short = sizeof(unsigned short);" "unsigned int sizeof_int = sizeof(int);" @@ -6090,8 +5795,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, true, Settings::Win32A)); } - void platformWin32A() - { + void platformWin32A() { const char code[] = "wchar_t wc;" "TCHAR c;" "PTSTR ptstr;" @@ -6135,8 +5839,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, false, true, Settings::Win32A)); } - void platformWin32W() - { + void platformWin32W() { const char code[] = "wchar_t wc;" "TCHAR c;" "PTSTR ptstr;" @@ -6180,8 +5883,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, false, true, Settings::Win32W)); } - void platformWin64() - { + void platformWin64() { const char code[] = "unsigned int sizeof_short = sizeof(short);" "unsigned int sizeof_unsigned_short = sizeof(unsigned short);" "unsigned int sizeof_int = sizeof(int);" @@ -6237,8 +5939,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, true, Settings::Win64)); } - void platformUnix32() - { + void platformUnix32() { const char code[] = "unsigned int sizeof_short = sizeof(short);" "unsigned int sizeof_unsigned_short = sizeof(unsigned short);" "unsigned int sizeof_int = sizeof(int);" @@ -6282,8 +5983,7 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, true, Settings::Unix32)); } - void platformUnix64() - { + void platformUnix64() { const char code[] = "unsigned int sizeof_short = sizeof(short);" "unsigned int sizeof_unsigned_short = sizeof(unsigned short);" "unsigned int sizeof_int = sizeof(int);" diff --git a/test/testuninitvar.cpp b/test/testuninitvar.cpp index 2c930957d..5dd56347c 100644 --- a/test/testuninitvar.cpp +++ b/test/testuninitvar.cpp @@ -23,8 +23,7 @@ extern std::ostringstream errout; -class TestUninitVar : public TestFixture -{ +class TestUninitVar : public TestFixture { public: TestUninitVar() : TestFixture("TestUninitVar") { } @@ -32,8 +31,7 @@ public: private: - void run() - { + void run() { TEST_CASE(uninitvar1); TEST_CASE(uninitvar_bitop); // using uninitialized operand in bit operation TEST_CASE(uninitvar_alloc); // data is allocated but not initialized @@ -52,8 +50,7 @@ private: TEST_CASE(uninitvar_typeof); // typeof } - void checkUninitVar(const char code[]) - { + void checkUninitVar(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -70,8 +67,7 @@ private: check.executionPaths(); } - void uninitvar1() - { + void uninitvar1() { // Ticket #2207 - False negative checkUninitVar("void foo() {\n" " int a;\n" @@ -530,8 +526,7 @@ private: } - void uninitvar_bitop() - { + void uninitvar_bitop() { checkUninitVar("void foo() {\n" " int b;\n" " c = a | b;\n" @@ -546,8 +541,7 @@ private: } // if.. - void uninitvar_if() - { + void uninitvar_if() { checkUninitVar("static void foo()\n" "{\n" " Foo *p;\n" @@ -781,8 +775,7 @@ private: // handling for/while loops.. - void uninitvar_loops() - { + void uninitvar_loops() { // for.. checkUninitVar("void f()\n" "{\n" @@ -905,8 +898,7 @@ private: } // switch.. - void uninitvar_switch() - { + void uninitvar_switch() { checkUninitVar("void f(int x)\n" "{\n" " short c;\n" @@ -984,8 +976,7 @@ private: } // arrays.. - void uninitvar_arrays() - { + void uninitvar_arrays() { checkUninitVar("int f()\n" "{\n" " char a[10];\n" @@ -1110,8 +1101,7 @@ private: } // alloc.. - void uninitvar_alloc() - { + void uninitvar_alloc() { checkUninitVar("void f()\n" "{\n" " char *s = malloc(100);\n" @@ -1229,8 +1219,7 @@ private: } // class / struct.. - void uninitvar_class() - { + void uninitvar_class() { checkUninitVar("class Fred\n" "{\n" " int i;\n" @@ -1279,8 +1268,7 @@ private: } // enum.. - void uninitvar_enum() - { + void uninitvar_enum() { checkUninitVar("void f()\n" "{\n" " enum AB { a, b };\n" @@ -1291,8 +1279,7 @@ private: } // references.. - void uninitvar_references() - { + void uninitvar_references() { checkUninitVar("void f()\n" "{\n" " int a;\n" @@ -1319,8 +1306,7 @@ private: } // strncpy doesn't always 0-terminate.. - void uninitvar_strncpy() - { + void uninitvar_strncpy() { checkUninitVar("void f()\n" "{\n" " char a[100];\n" @@ -1347,8 +1333,7 @@ private: } // initialization with memset (not 0-terminating string).. - void uninitvar_memset() - { + void uninitvar_memset() { checkUninitVar("void f() {\n" " char a[20];\n" " memset(a, 'a', 20);\n" @@ -1357,8 +1342,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Dangerous usage of 'a' (not 0-terminated)\n", errout.str()); } - std::string analyseFunctions(const char code[]) - { + std::string analyseFunctions(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -1379,8 +1363,7 @@ private: return ret; } - void uninitvar_func() - { + void uninitvar_func() { // function analysis.. ASSERT_EQUALS("foo", analyseFunctions("void foo(int x) { }")); ASSERT_EQUALS("foo", analyseFunctions("void foo(int x);")); @@ -1584,8 +1567,7 @@ private: } // valid and invalid use of 'int a(int x) { return x + x; }' - void func_uninit_var() - { + void func_uninit_var() { const std::string funca("int a(int x) { return x + x; }\n"); checkUninitVar((funca + @@ -1605,8 +1587,7 @@ private: // valid and invalid use of 'void a(int *p) { *p = 0; }' - void func_uninit_pointer() - { + void func_uninit_pointer() { const std::string funca("void a(int *p) { *p = 0; }\n"); // ok - initialized pointer @@ -1626,8 +1607,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout.str()); } - void uninitvar_typeof() - { + void uninitvar_typeof() { checkUninitVar("void f() {\n" " struct Fred *fred;\n" " typeof(fred->x);\n" diff --git a/test/testunusedfunctions.cpp b/test/testunusedfunctions.cpp index 27c37b732..20b08b521 100644 --- a/test/testunusedfunctions.cpp +++ b/test/testunusedfunctions.cpp @@ -24,8 +24,7 @@ extern std::ostringstream errout; -class TestUnusedFunctions : public TestFixture -{ +class TestUnusedFunctions : public TestFixture { public: TestUnusedFunctions() : TestFixture("TestUnusedFunctions") { } @@ -33,8 +32,7 @@ public: private: - void run() - { + void run() { TEST_CASE(incondition); TEST_CASE(return1); TEST_CASE(return2); @@ -52,8 +50,7 @@ private: TEST_CASE(lineNumber); // Ticket 3059 } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -71,8 +68,7 @@ private: checkUnusedFunctions.check(this); } - void incondition() - { + void incondition() { check("int f1()\n" "{\n" " if (f1())\n" @@ -81,8 +77,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void return1() - { + void return1() { check("int f1()\n" "{\n" " return f1();\n" @@ -90,8 +85,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void return2() - { + void return2() { check("char * foo()\n" "{\n" " return *foo();\n" @@ -99,8 +93,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void callback1() - { + void callback1() { check("void f1()\n" "{\n" " void (*f)() = cond ? f1 : NULL;\n" @@ -108,8 +101,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void else1() - { + void else1() { check("void f1()\n" "{\n" " if (cond) ;\n" @@ -118,8 +110,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void functionpointer() - { + void functionpointer() { check("namespace abc {\n" "void foo() { }\n" "};\n" @@ -143,8 +134,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void template1() - { + void template1() { check("template void foo() { }\n" "\n" "int main()\n" @@ -155,14 +145,12 @@ private: ASSERT_EQUALS("", errout.str()); } - void throwIsNotAFunction() - { + void throwIsNotAFunction() { check("struct A {void f() const throw () {}}; int main() {A a; a.f();}\n"); ASSERT_EQUALS("", errout.str()); } - void unusedError() - { + void unusedError() { check("void foo() {}\n" "int main()\n"); ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used\n", errout.str()); @@ -180,8 +168,7 @@ private: ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used\n", errout.str()); } - void unusedMain() - { + void unusedMain() { check("int main() { }\n"); ASSERT_EQUALS("", errout.str()); @@ -192,16 +179,14 @@ private: ASSERT_EQUALS("", errout.str()); } - void initializationIsNotAFunction() - { + void initializationIsNotAFunction() { check("struct B: N::A {\n" " B(): N::A() {};\n" "};\n"); ASSERT_EQUALS("", errout.str()); } - void multipleFiles() - { + void multipleFiles() { CheckUnusedFunctions c; // Clear the error buffer.. @@ -209,8 +194,7 @@ private: const char code[] = "static void f() { }"; - for (int i = 1; i <= 2; ++i) - { + for (int i = 1; i <= 2; ++i) { std::ostringstream fname; fname << "test" << i << ".cpp"; @@ -232,8 +216,7 @@ private: ASSERT_EQUALS("[test1.cpp:1]: (style) The function 'f' is never used\n",errout.str()); } - void lineNumber() - { + void lineNumber() { check("void foo() {}\n" "void bar() {}\n" "int main()\n"); diff --git a/test/testunusedprivfunc.cpp b/test/testunusedprivfunc.cpp index 3ca5f2b94..5cb1b8d77 100644 --- a/test/testunusedprivfunc.cpp +++ b/test/testunusedprivfunc.cpp @@ -25,15 +25,13 @@ extern std::ostringstream errout; -class TestUnusedPrivateFunction : public TestFixture -{ +class TestUnusedPrivateFunction : public TestFixture { public: TestUnusedPrivateFunction() : TestFixture("TestUnusedPrivateFunction") { } private: - void run() - { + void run() { TEST_CASE(test1); TEST_CASE(test2); TEST_CASE(test3); @@ -73,8 +71,7 @@ private: } - void check(const char code[]) - { + void check(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -94,8 +91,7 @@ private: - void test1() - { + void test1() { check("class Fred\n" "{\n" "private:\n" @@ -165,8 +161,7 @@ private: } - void test2() - { + void test2() { check("class A {\n" "public:\n" " A();\n" @@ -184,8 +179,7 @@ private: } - void test3() - { + void test3() { check("class A {\n" "public:\n" " A() { }\n" @@ -200,8 +194,7 @@ private: } - void test4() - { + void test4() { check("class A {\n" "public:\n" " A();\n" @@ -216,8 +209,7 @@ private: } - void test5() - { + void test5() { check("class A {\n" "private:\n" " A() : lock(new Lock())\n" @@ -227,8 +219,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void test6() // ticket #2602 segmentation fault - { + void test6() { // ticket #2602 segmentation fault check("class A {\n" " A& operator=(const A&);\n" "};\n"); @@ -239,8 +230,7 @@ private: - void func_pointer1() - { + void func_pointer1() { check("class Fred\n" "{\n" "private:\n" @@ -266,8 +256,7 @@ private: - void func_pointer2() - { + void func_pointer2() { check("class UnusedPrivateFunctionMemberPointer\n" "{\n" "public:\n" @@ -284,8 +273,7 @@ private: } - void func_pointer3() - { + void func_pointer3() { check("class c1\n" "{\n" "public:\n" @@ -299,8 +287,7 @@ private: } - void func_pointer4() // ticket #2807 - { + void func_pointer4() { // ticket #2807 check("class myclass {\n" "public:\n" " myclass();\n" @@ -314,8 +301,7 @@ private: } - void ctor() - { + void ctor() { check("class PrivateCtor\n" "{\n" "private:\n" @@ -331,8 +317,7 @@ private: } - void classInClass() - { + void classInClass() { check("class A\n" "{\n" "public:\n" @@ -368,8 +353,7 @@ private: } - void sameFunctionNames() - { + void sameFunctionNames() { check("class A\n" "{\n" "public:\n" @@ -385,8 +369,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void incompleteImplementation() - { + void incompleteImplementation() { // The implementation for "A::a" is missing - so don't check if // "A::b" is used or not check("#file \"test.h\"\n" @@ -404,8 +387,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void derivedClass() - { + void derivedClass() { // skip warning in derived classes in case the function is virtual check("class derived : public base\n" "{\n" @@ -417,8 +399,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void friendClass() - { + void friendClass() { // ticket #2459 - friend class check("class Foo {\n" "private:\n" @@ -428,8 +409,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void borland() - { + void borland() { // ticket #2034 - Borland C++ __property check("class Foo {\n" "private:\n" @@ -443,8 +423,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void template1() - { + void template1() { // ticket #2067 - Template methods do not "use" private ones check("class A {\n" "public:\n" @@ -462,8 +441,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void fp_operator() - { + void fp_operator() { // #2407 - FP when function is called from operator() check("class Fred\n" "{\n" @@ -491,8 +469,7 @@ private: ASSERT_EQUALS("[test.cpp:8]: (style) Unused private function 'Fred::startListening'\n", errout.str()); } - void testDoesNotIdentifyMethodAsFirstFunctionArgument() - { + void testDoesNotIdentifyMethodAsFirstFunctionArgument() { check("#include " "void callback(void (*func)(int), int arg)" "{" @@ -520,8 +497,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testDoesNotIdentifyMethodAsMiddleFunctionArgument() - { + void testDoesNotIdentifyMethodAsMiddleFunctionArgument() { check("#include " "void callback(char, void (*func)(int), int arg)" "{" @@ -549,8 +525,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void testDoesNotIdentifyMethodAsLastFunctionArgument() - { + void testDoesNotIdentifyMethodAsLastFunctionArgument() { check("#include " "void callback(int arg, void (*func)(int))" "{" @@ -578,8 +553,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void multiFile() // ticket #2567 - { + void multiFile() { // ticket #2567 check("#file \"test.h\"\n" "struct Fred\n" "{\n" @@ -598,8 +572,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void unknownBaseTemplate() // ticket #2580 - { + void unknownBaseTemplate() { // ticket #2580 check("class Bla : public Base2 {\n" "public:\n" " Bla() {}\n" diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index 94def02f6..69ac15dc8 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -27,15 +27,13 @@ #include extern std::ostringstream errout; -class TestUnusedVar : public TestFixture -{ +class TestUnusedVar : public TestFixture { public: TestUnusedVar() : TestFixture("TestUnusedVar") { } private: - void run() - { + void run() { TEST_CASE(structmember1); TEST_CASE(structmember2); TEST_CASE(structmember3); @@ -127,8 +125,7 @@ private: TEST_CASE(localvarIfNOT); // #3104 - if ( NOT var ) } - void checkStructMemberUsage(const char code[]) - { + void checkStructMemberUsage(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -145,8 +142,7 @@ private: checkUnusedVar.checkStructMemberUsage(); } - void structmember1() - { + void structmember1() { checkStructMemberUsage("struct abc\n" "{\n" " int a;\n" @@ -158,8 +154,7 @@ private: "[test.cpp:5]: (style) struct or union member 'abc::c' is never used\n", errout.str()); } - void structmember2() - { + void structmember2() { checkStructMemberUsage("struct ABC\n" "{\n" " int a;\n" @@ -177,8 +172,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember3() - { + void structmember3() { checkStructMemberUsage("struct ABC\n" "{\n" " int a;\n" @@ -197,8 +191,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember4() - { + void structmember4() { checkStructMemberUsage("struct ABC\n" "{\n" " const int a;\n" @@ -212,8 +205,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember5() - { + void structmember5() { checkStructMemberUsage("struct AB\n" "{\n" " int a;\n" @@ -233,8 +225,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember6() - { + void structmember6() { checkStructMemberUsage("struct AB\n" "{\n" " int a;\n" @@ -260,8 +251,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember7() - { + void structmember7() { checkStructMemberUsage("struct AB\n" "{\n" " int a;\n" @@ -287,8 +277,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember8() - { + void structmember8() { checkStructMemberUsage("struct AB\n" "{\n" " int a;\n" @@ -302,8 +291,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember9() - { + void structmember9() { checkStructMemberUsage("struct base {\n" " int a;\n" "};\n" @@ -313,8 +301,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember10() - { + void structmember10() { // Fred may have some useful side-effects checkStructMemberUsage("struct abc {\n" " Fred fred;\n" @@ -322,8 +309,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void structmember_extern() - { + void structmember_extern() { // extern struct => no false positive checkStructMemberUsage("extern struct AB\n" "{\n" @@ -364,8 +350,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) struct or union member 'AB::a' is never used\n", errout.str()); } - void functionVariableUsage(const char code[]) - { + void functionVariableUsage(const char code[]) { // Clear the error buffer.. errout.str(""); @@ -382,8 +367,7 @@ private: checkUnusedVar.checkFunctionVariableUsage(); } - void localvar1() - { + void localvar1() { functionVariableUsage("void foo()\n" "{\n" " int i = 0;\n" @@ -570,8 +554,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used\n", errout.str()); } - void localvar2() - { + void localvar2() { functionVariableUsage("int foo()\n" "{\n" " int i;\n" @@ -691,8 +674,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar3() - { + void localvar3() { functionVariableUsage("void foo()\n" "{\n" " int i;\n" @@ -703,8 +685,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used\n", errout.str()); } - void localvar4() - { + void localvar4() { functionVariableUsage("void foo()\n" "{\n" " int i = 0;\n" @@ -720,8 +701,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar5() - { + void localvar5() { functionVariableUsage("void foo()\n" "{\n" " int a = 0;\n" @@ -730,8 +710,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar6() - { + void localvar6() { functionVariableUsage("void foo()\n" "{\n" " int b[10];\n" @@ -750,8 +729,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used\n", errout.str()); } - void localvar7()// ticket 1253 - { + void localvar7() { // ticket 1253 functionVariableUsage("void foo()\n" "{\n" " int i;\n" @@ -776,8 +754,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value\n", errout.str()); } - void localvar8() - { + void localvar8() { functionVariableUsage("void foo()\n" "{\n" " int i;\n" @@ -968,8 +945,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar9() - { + void localvar9() { // ticket #1605 functionVariableUsage("void foo()\n" "{\n" @@ -980,8 +956,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used\n", errout.str()); } - void localvar10() - { + void localvar10() { functionVariableUsage("void foo(int x)\n" "{\n" " int i;\n" @@ -1035,8 +1010,7 @@ private: "[test.cpp:7]: (style) Unused variable: i\n", errout.str()); } - void localvar11() - { + void localvar11() { functionVariableUsage("void foo(int x)\n" "{\n" " int a = 0;\n" @@ -1065,8 +1039,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar12() - { + void localvar12() { // ticket #1574 functionVariableUsage("void foo()\n" "{\n" @@ -1100,8 +1073,7 @@ private: errout.str()); } - void localvar13() // ticket #1640 - { + void localvar13() { // ticket #1640 functionVariableUsage("void foo( OBJECT *obj )\n" "{\n" " int x;\n" @@ -1110,8 +1082,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used\n", errout.str()); } - void localvar14() - { + void localvar14() { // ticket #5 functionVariableUsage("void foo()\n" "{\n" @@ -1120,8 +1091,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n", errout.str()); } - void localvar15() - { + void localvar15() { functionVariableUsage("int foo()\n" "{\n" " int a = 5;\n" @@ -1168,8 +1138,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar16() // ticket #1709 - { + void localvar16() { // ticket #1709 functionVariableUsage("int foo()\n" "{\n" " char buf[5];\n" @@ -1187,8 +1156,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar17() // ticket #1720 - { + void localvar17() { // ticket #1720 // Don't crash when checking the code below! functionVariableUsage("void foo()\n" "{\n" @@ -1204,8 +1172,7 @@ private: ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'line_start' is assigned a value that is never used\n", errout.str()); } - void localvar18() // ticket #1723 - { + void localvar18() { // ticket #1723 functionVariableUsage("A::A(int iValue) {\n" " UserDefinedException* pe = new UserDefinedException();\n" " throw pe;\n" @@ -1213,8 +1180,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar19() // ticket #1776 - { + void localvar19() { // ticket #1776 functionVariableUsage("void foo() {\n" " int a[10];\n" " int c;\n" @@ -1224,8 +1190,7 @@ private: "[test.cpp:3]: (style) Variable 'c' is assigned a value that is never used\n", errout.str()); } - void localvar20() // ticket #1799 - { + void localvar20() { // ticket #1799 functionVariableUsage("void foo()\n" "{\n" " char c1 = 'c';\n" @@ -1235,8 +1200,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar21() // ticket #1807 - { + void localvar21() { // ticket #1807 functionVariableUsage("void foo()\n" "{\n" " char buffer[1024];\n" @@ -1245,8 +1209,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar22() // ticket #1811 - { + void localvar22() { // ticket #1811 functionVariableUsage("int foo(int u, int v)\n" "{\n" " int h, i;\n" @@ -1257,8 +1220,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar23() // ticket #1808 - { + void localvar23() { // ticket #1808 functionVariableUsage("int foo(int c)\n" "{\n" " int a;\n" @@ -1269,8 +1231,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar24() // ticket #1803 - { + void localvar24() { // ticket #1803 functionVariableUsage("class MyException\n" "{\n" " virtual void raise() const\n" @@ -1281,8 +1242,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar25() // ticket #1729 - { + void localvar25() { // ticket #1729 functionVariableUsage("int main() {\n" " int ppos = 1;\n" " int pneg = 0;\n" @@ -1293,8 +1253,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar26() // ticket #1894 - { + void localvar26() { // ticket #1894 functionVariableUsage("int main() {\n" " const Fred &fred = getfred();\n" " int *p = fred.x();\n" @@ -1303,8 +1262,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar27() // ticket #2160 - { + void localvar27() { // ticket #2160 functionVariableUsage("void f(struct s *ptr) {\n" " int param = 1;\n" " ptr->param = param++;\n" @@ -1312,8 +1270,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar28() // ticket #2205 - { + void localvar28() { // ticket #2205 functionVariableUsage("void f(char* buffer, int value) {\n" " char* pos = buffer;\n" " int size = value;\n" @@ -1322,8 +1279,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar29() // ticket #2206 - { + void localvar29() { // ticket #2206 functionVariableUsage("void f() {\n" " float s_ranges[] = { 0, 256 };\n" " float* ranges[] = { s_ranges };\n" @@ -1332,8 +1288,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar30() // ticket #2264 - { + void localvar30() { // ticket #2264 functionVariableUsage("void f() {\n" " Engine *engine = e;\n" " x->engine = engine->clone();\n" @@ -1341,8 +1296,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar31() // ticket #2286 - { + void localvar31() { // ticket #2286 functionVariableUsage("void f() {\n" " int x = 0;\n" " a.x = x - b;\n" @@ -1350,8 +1304,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar32() // ticket #2330 - { + void localvar32() { // ticket #2330 functionVariableUsage("void f() {\n" " int x;\n" " fstream &f = getfile();\n" @@ -1360,8 +1313,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar33() // ticket #2345 - { + void localvar33() { // ticket #2345 functionVariableUsage("void f() {\n" " Abc* abc = getabc();\n" " while (0 != (abc = abc->next())) {\n" @@ -1371,8 +1323,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar34() // ticket #2368 - { + void localvar34() { // ticket #2368 functionVariableUsage("void f() {\n" " int i = 0;\n" " if (false) {\n" @@ -1383,8 +1334,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar35() // ticket #2535 - { + void localvar35() { // ticket #2535 functionVariableUsage("void f() {\n" " int a, b;\n" " x(1,a,b);\n" @@ -1392,8 +1342,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar36() // ticket #2805 - { + void localvar36() { // ticket #2805 functionVariableUsage("int f() {\n" " int a, b;\n" " a = 2 * (b = 3);\n" @@ -1402,8 +1351,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvar37() // ticket #3078 - { + void localvar37() { // ticket #3078 functionVariableUsage("void f() {\n" " int a = 2;\n" " ints.at(a) = 0;\n" @@ -1411,8 +1359,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias1() - { + void localvaralias1() { functionVariableUsage("void foo()\n" "{\n" " int a;\n" @@ -1858,8 +1805,7 @@ private: "[test.cpp:5]: (style) Variable 'c' is assigned a value that is never used\n", errout.str()); } - void localvaralias2() // ticket 1637 - { + void localvaralias2() { // ticket 1637 functionVariableUsage("void foo()\n" "{\n" " int * a;\n" @@ -1868,8 +1814,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias3() // ticket 1639 - { + void localvaralias3() { // ticket 1639 functionVariableUsage("void foo()\n" "{\n" " BROWSEINFO info;\n" @@ -1880,8 +1825,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias4() // ticket 1643 - { + void localvaralias4() { // ticket 1643 functionVariableUsage("struct AB { int a; int b; } ab;\n" "void foo()\n" "{\n" @@ -1916,8 +1860,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias5() // ticket 1647 - { + void localvaralias5() { // ticket 1647 functionVariableUsage("char foo()\n" "{\n" " char buf[8];\n" @@ -1955,8 +1898,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias6() // ticket 1729 - { + void localvaralias6() { // ticket 1729 functionVariableUsage("void foo()\n" "{\n" " char buf[8];\n" @@ -2091,8 +2033,7 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) Unused variable: vdata\n", errout.str()); } - void localvaralias7() // ticket 1732 - { + void localvaralias7() { // ticket 1732 functionVariableUsage("void foo()\n" "{\n" " char *c[10];\n" @@ -2103,8 +2044,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias8() - { + void localvaralias8() { functionVariableUsage("void foo()\n" "{\n" " char b1[8];\n" @@ -2289,8 +2229,7 @@ private: "[test.cpp:5]: (style) Unused variable: b3\n", errout.str()); } - void localvaralias9() // ticket 1996 - { + void localvaralias9() { // ticket 1996 functionVariableUsage("void foo()\n" "{\n" " Foo foo;\n" @@ -2300,8 +2239,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvaralias10() // ticket 2004 - { + void localvaralias10() { // ticket 2004 functionVariableUsage("void foo(Foo &foo)\n" "{\n" " Foo &ref = foo;\n" @@ -2311,8 +2249,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarasm() - { + void localvarasm() { functionVariableUsage("void foo(int &b)\n" "{\n" " int a;\n" @@ -2322,8 +2259,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarStruct1() - { + void localvarStruct1() { functionVariableUsage("void foo()\n" "{\n" " static const struct{ int x, y, w, h; } bounds = {1,2,3,4};\n" @@ -2332,8 +2268,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarStruct2() - { + void localvarStruct2() { functionVariableUsage("void foo()\n" "{\n" " struct ABC { int a, b, c; };\n" @@ -2342,8 +2277,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'abc' is assigned a value that is never used\n", errout.str()); } - void localvarStruct3() - { + void localvarStruct3() { functionVariableUsage("void foo()\n" "{\n" " int a = 10;\n" @@ -2358,16 +2292,14 @@ private: "", errout.str()); } - void localvarStruct4() - { + void localvarStruct4() { /* This must not SIGSEGV: */ functionVariableUsage("void foo()\n" "{\n" " struct { \n"); } - void localvarStruct5() - { + void localvarStruct5() { functionVariableUsage("int foo() {\n" " A a;\n" " return a.i;\n" @@ -2467,8 +2399,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarStruct6() - { + void localvarStruct6() { functionVariableUsage("class Type { };\n" "class A {\n" "public:\n" @@ -2479,11 +2410,9 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarOp() - { + void localvarOp() { const char op[] = "+-*/%&|^"; - for (const char *p = op; *p; ++p) - { + for (const char *p = op; *p; ++p) { std::string code("int main()\n" "{\n" " int tmp = 10;\n" @@ -2494,8 +2423,7 @@ private: } } - void localvarInvert() - { + void localvarInvert() { functionVariableUsage("int main()\n" "{\n" " int tmp = 10;\n" @@ -2504,8 +2432,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarIf() - { + void localvarIf() { functionVariableUsage("int main()\n" "{\n" " int tmp = 10;\n" @@ -2516,8 +2443,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarIfElse() - { + void localvarIfElse() { functionVariableUsage("int foo()\n" "{\n" " int tmp1 = 1;\n" @@ -2528,8 +2454,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarOpAssign() - { + void localvarOpAssign() { functionVariableUsage("void foo()\n" "{\n" " int a = 1;\n" @@ -2545,8 +2470,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarFor() - { + void localvarFor() { functionVariableUsage("void foo()\n" "{\n" " int a = 1;\n" @@ -2555,8 +2479,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarShift1() - { + void localvarShift1() { functionVariableUsage("int foo()\n" "{\n" " int var = 1;\n" @@ -2565,8 +2488,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarShift2() - { + void localvarShift2() { functionVariableUsage("int foo()\n" "{\n" " int var = 1;\n" @@ -2575,8 +2497,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarCast() - { + void localvarCast() { functionVariableUsage("int foo()\n" "{\n" " int a = 1;\n" @@ -2586,8 +2507,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarClass() - { + void localvarClass() { functionVariableUsage("int foo()\n" "{\n" " class B : public A {\n" @@ -2598,8 +2518,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarUnused() - { + void localvarUnused() { functionVariableUsage("int foo()\n" "{\n" " bool test __attribute__((unused));\n" @@ -2625,8 +2544,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarFunction() - { + void localvarFunction() { functionVariableUsage("void check_dlsym(void*& h)\n" "{\n" " typedef void (*function_type) (void);\n" @@ -2637,8 +2555,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarstatic() - { + void localvarstatic() { functionVariableUsage("void foo()\n" "{\n" " static int i;\n" @@ -2684,8 +2601,7 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used\n", errout.str()); } - void localvardynamic1() - { + void localvardynamic1() { functionVariableUsage("void foo()\n" "{\n" " void* ptr = malloc(16);\n" @@ -2802,8 +2718,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvardynamic2() - { + void localvardynamic2() { functionVariableUsage("struct Fred { int i; };\n" "void foo()\n" "{\n" @@ -2923,8 +2838,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvararray1() - { + void localvararray1() { functionVariableUsage("void foo() {\n" " int p[5];\n" " *p = 0;\n" @@ -2932,8 +2846,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarstring1() // ticket #1597 - { + void localvarstring1() { // ticket #1597 functionVariableUsage("void foo() {\n" " std::string s;\n" "}\n"); @@ -2963,8 +2876,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void localvarstring2() // ticket #2929 - { + void localvarstring2() { // ticket #2929 functionVariableUsage("void foo() {\n" " std::string s;\n" " int i;\n" @@ -2973,8 +2885,7 @@ private: "[test.cpp:3]: (style) Unused variable: i\n", errout.str()); } - void localvarconst() - { + void localvarconst() { functionVariableUsage("void foo() {\n" " const bool b = true;\n" "}\n"); @@ -2982,8 +2893,7 @@ private: } // ticket #3104 - false positive when variable is read with "if (NOT var)" - void localvarIfNOT() - { + void localvarIfNOT() { functionVariableUsage("void f() {\n" " bool x = foo();\n" " if (NOT x) { }\n" diff --git a/test/testutils.h b/test/testutils.h index edc3b56d9..2a683029d 100644 --- a/test/testutils.h +++ b/test/testutils.h @@ -22,8 +22,7 @@ #include "tokenize.h" #include "token.h" -class givenACodeSampleToTokenize -{ +class givenACodeSampleToTokenize { private: std::istringstream _sample; const Token* _tokens; @@ -33,15 +32,13 @@ private: public: givenACodeSampleToTokenize(const std::string& sample) :_sample(sample) - ,_tokens(NULL) - { + ,_tokens(NULL) { _tokenizer.setSettings(&_settings); _tokenizer.tokenize(_sample, "test.cpp"); _tokens = _tokenizer.tokens(); } - const Token* tokens() const - { + const Token* tokens() const { return _tokens; } }; diff --git a/tools/dmake.cpp b/tools/dmake.cpp index 6ce39bd78..a076856b1 100644 --- a/tools/dmake.cpp +++ b/tools/dmake.cpp @@ -40,8 +40,7 @@ void getDeps(const std::string &filename, std::vector &depfiles) return; std::ifstream f(filename.c_str()); - if (! f.is_open()) - { + if (! f.is_open()) { if (filename.compare(0, 4, "cli/") == 0 || filename.compare(0, 5, "test/") == 0) getDeps("lib" + filename.substr(filename.find("/")), depfiles); return; @@ -54,8 +53,7 @@ void getDeps(const std::string &filename, std::vector &depfiles) path.erase(1 + path.rfind("/")); std::string line; - while (std::getline(f, line)) - { + while (std::getline(f, line)) { std::string::size_type pos1 = line.find("#include \""); if (pos1 == std::string::npos) continue; @@ -71,8 +69,7 @@ void getDeps(const std::string &filename, std::vector &depfiles) static void compilefiles(std::ostream &fout, const std::vector &files, const std::string &args) { - for (unsigned int i = 0; i < files.size(); ++i) - { + for (unsigned int i = 0; i < files.size(); ++i) { fout << objfile(files[i]) << ": " << files[i]; std::vector depfiles; getDeps(files[i], depfiles); @@ -87,8 +84,7 @@ static void getCppFiles(std::vector &files, const std::string &path std::map filesizes; FileLister::recursiveAddFiles(files, filesizes, path); // only get *.cpp files.. - for (std::vector::iterator it = files.begin(); it != files.end();) - { + for (std::vector::iterator it = files.begin(); it != files.end();) { if (it->find(".cpp") == std::string::npos) it = files.erase(it); else @@ -120,30 +116,23 @@ static void makeExtObj(std::ostream &fout, const std::vector &exter bool start = true; std::ostringstream libNames; std::string libName; - for (unsigned int i = 0; i < externalfiles.size(); ++i) - { - if (start) - { + for (unsigned int i = 0; i < externalfiles.size(); ++i) { + if (start) { libName = getLibName(externalfiles[i]); fout << "ifndef " << libName << std::endl; fout << " " << libName << " = " << objfile(externalfiles[i]); libNames << "EXTOBJ += $(" << libName << ")" << std::endl; start = false; - } - else - { + } else { fout << std::string(14, ' ') << objfile(externalfiles[i]); } - if (i+1 >= externalfiles.size() || libName != getLibName(externalfiles[i+1])) - { + if (i+1 >= externalfiles.size() || libName != getLibName(externalfiles[i+1])) { // This was the last file for this library fout << std::endl << "endif" << std::endl; fout << "\n\n"; start = true; - } - else - { + } else { // There are more files for this library fout << " \\" << std::endl; } @@ -166,8 +155,7 @@ int main(int argc, char **argv) std::vector testfiles; getCppFiles(testfiles, "test/"); - if (libfiles.empty() && clifiles.empty() && testfiles.empty()) - { + if (libfiles.empty() && clifiles.empty() && testfiles.empty()) { std::cerr << "No files found. Are you in the correct directory?" << std::endl; return EXIT_FAILURE; } @@ -179,14 +167,12 @@ int main(int argc, char **argv) // QMAKE - lib/lib.pri { std::ofstream fout1("lib/lib.pri"); - if (fout1.is_open()) - { + if (fout1.is_open()) { fout1 << "# no manual edits - this file is autogenerated by dmake\n\n"; fout1 << "include($$PWD/pcrerules.pri)\n"; fout1 << "INCLUDEPATH += ../externals/tinyxml\n"; fout1 << "HEADERS += $${BASEPATH}check.h \\\n"; - for (unsigned int i = 0; i < libfiles.size(); ++i) - { + for (unsigned int i = 0; i < libfiles.size(); ++i) { std::string fname(libfiles[i].substr(4)); if (fname.find(".cpp") == std::string::npos) continue; // shouldn't happen @@ -196,8 +182,7 @@ int main(int argc, char **argv) fout1 << " \\\n"; } fout1 << "\n\nSOURCES += "; - for (unsigned int i = 0; i < libfiles.size(); ++i) - { + for (unsigned int i = 0; i < libfiles.size(); ++i) { fout1 << "$${BASEPATH}" << libfiles[i].substr(4); if (i < libfiles.size() - 1) fout1 << " \\\n" << std::string(11, ' '); @@ -209,8 +194,7 @@ int main(int argc, char **argv) static const char makefile[] = "Makefile"; std::ofstream fout(makefile, std::ios_base::trunc); - if (!fout.is_open()) - { + if (!fout.is_open()) { std::cerr << "An error occurred while trying to open " << makefile << ".\n"; @@ -222,12 +206,9 @@ int main(int argc, char **argv) makeConditionalVariable(fout, "HAVE_RULES", "yes"); // Makefile settings.. - if (release) - { + if (release) { makeConditionalVariable(fout, "CXXFLAGS", "-O2 -DNDEBUG -Wall"); - } - else - { + } else { // TODO: add more compiler warnings. // -Wlogical-op : doesn't work on older GCC // -Wconversion : too many warnings diff --git a/tools/extracttests.cpp b/tools/extracttests.cpp index 0bf3a3024..b89a9fd36 100644 --- a/tools/extracttests.cpp +++ b/tools/extracttests.cpp @@ -15,8 +15,7 @@ static std::string str(unsigned int value) int main(const int argc, const char * const * const argv) { - if (argc != 2) - { + if (argc != 2) { std::cerr << "syntax: extracttests testfile" << std::endl; return 0; } @@ -26,39 +25,33 @@ int main(const int argc, const char * const * const argv) std::ifstream f(argv[1]); std::string line; - while (std::getline(f, line)) - { + while (std::getline(f, line)) { { std::string::size_type pos = line.find_first_not_of(" "); if (pos > 0 && pos != std::string::npos) line.erase(0, pos); } - if (line.compare(0, 5, "void ") == 0) - { + if (line.compare(0, 5, "void ") == 0) { testname = line.substr(5, line.size() - 7); subcount = 0; continue; } - if (line == "}") - { + if (line == "}") { testname = ""; subcount = 0; continue; } - if (!testname.empty() && line.compare(0, 5, "check") == 0 && line.find("(\"") != std::string::npos) - { + if (!testname.empty() && line.compare(0, 5, "check") == 0 && line.find("(\"") != std::string::npos) { std::ofstream fout((testname + str(++subcount) + ext).c_str()); fout << "#include " << std::endl; fout << "#include " << std::endl; fout << "#include " << std::endl; - if (testname == "nullpointer1") - { - if (subcount < 6) - { + if (testname == "nullpointer1") { + if (subcount < 6) { fout << "class Token\n" << "{\n" << "public:\n" @@ -69,9 +62,7 @@ int main(const int argc, const char * const * const argv) << " operator bool() const;\n" << "};\n" << "static Token *tokens;\n"; - } - else - { + } else { fout << "struct A\n" "{\n" " char b();\n" @@ -80,8 +71,7 @@ int main(const int argc, const char * const * const argv) } } - if (testname == "nullpointer2") - { + if (testname == "nullpointer2") { fout << "class Fred\n" << "{\n" << "public:\n" @@ -90,8 +80,7 @@ int main(const int argc, const char * const * const argv) << "};\n"; } - if (testname == "nullpointer3") - { + if (testname == "nullpointer3") { fout << "struct DEF { };\n" << "struct ABC : public DEF\n" << "{\n" @@ -101,8 +90,7 @@ int main(const int argc, const char * const * const argv) << "void bar(int); void f(struct ABC **);\n"; } - if (testname == "nullpointer4") - { + if (testname == "nullpointer4") { fout << "void bar(int);\n" << "int** f(int **p = 0);\n" << "extern int x;\n" @@ -112,16 +100,14 @@ int main(const int argc, const char * const * const argv) << "};\n"; } - if (testname == "nullpointer5") - { + if (testname == "nullpointer5") { fout << "struct A {\n" << " char c() const;\n" << " operator bool() const;\n" << "};\n"; } - if (testname == "nullpointer6") - { + if (testname == "nullpointer6") { fout << "struct Foo {\n" << " void abcd() const;\n" << "};\n" @@ -130,16 +116,14 @@ int main(const int argc, const char * const * const argv) << "extern int a;\n"; } - if (testname == "nullpointer7") - { + if (testname == "nullpointer7") { fout << "struct wxLongLong {\n" << " wxLongLong(int) { }\n" << " long GetValue() const;\n" << "};\n"; } - do - { + do { std::string::size_type pos = line.find("\""); if (pos == std::string::npos) break; @@ -152,8 +136,7 @@ int main(const int argc, const char * const * const argv) line.erase(pos); pos = 0; - while ((pos = line.find("\\", pos)) != std::string::npos) - { + while ((pos = line.find("\\", pos)) != std::string::npos) { line.erase(pos, 1); if (line[pos] == 'n') line.erase(pos, 1); @@ -165,8 +148,7 @@ int main(const int argc, const char * const * const argv) if (lastline) break; - } - while (std::getline(f, line)); + } while (std::getline(f, line)); fout << std::endl; continue; }