id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
26,433
vf_debug.h
danmar_cppcheck/lib/vf_debug.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfDebugH #define vfDebugH class TokenList; class ErrorLogger; class Settings; namespace ValueFlow { void analyzeDebug(TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings); } #endif // vfDebugH
992
C++
.h
27
34.851852
96
0.761707
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,434
mathlib.h
danmar_cppcheck/lib/mathlib.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef mathlibH #define mathlibH //--------------------------------------------------------------------------- #include "config.h" #include <cstdint> #include <string> /// @addtogroup Core /// @{ /** @brief simple math functions that uses operands stored in std::string. useful when performing math on tokens. */ class CPPCHECKLIB MathLib { friend class TestMathLib; public: /** @brief value class */ class value { private: long long mIntValue{}; double mDoubleValue{}; enum class Type : std::uint8_t { INT, LONG, LONGLONG, FLOAT } mType; bool mIsUnsigned{}; void promote(const value &v); public: explicit value(const std::string &s); std::string str() const; bool isInt() const { return mType != Type::FLOAT; } bool isFloat() const { return mType == Type::FLOAT; } double getDoubleValue() const { return isFloat() ? mDoubleValue : (double)mIntValue; } static value calc(char op, const value &v1, const value &v2); int compare(const value &v) const; value add(int v) const; value shiftLeft(const value &v) const; value shiftRight(const value &v) const; }; using bigint = long long; using biguint = unsigned long long; static const int bigint_bits; /** @brief for conversion of numeric literals - for atoi-like conversions please use strToInt() */ static bigint toBigNumber(const std::string & str); /** @brief for conversion of numeric literals - for atoi-like conversions please use strToInt() */ static biguint toBigUNumber(const std::string & str); template<class T> static std::string toString(T value) = delete; /** @brief for conversion of numeric literals */ static double toDoubleNumber(const std::string & str); static bool isInt(const std::string & str); static bool isFloat(const std::string &str); static bool isDecimalFloat(const std::string &str); static bool isNegative(const std::string &str); static bool isPositive(const std::string &str); static bool isDec(const std::string & str); static bool isFloatHex(const std::string& str); static bool isIntHex(const std::string& str); static bool isOct(const std::string& str); static bool isBin(const std::string& str); static std::string getSuffix(const std::string& value); /** * Only used in unit tests * * \param[in] str string * \param[in] supportMicrosoftExtensions support Microsoft extension: i64 * \return true if str is a non-empty valid integer suffix */ static bool isValidIntegerSuffix(const std::string& str, bool supportMicrosoftExtensions=true); static std::string add(const std::string & first, const std::string & second); static std::string subtract(const std::string & first, const std::string & second); static std::string multiply(const std::string & first, const std::string & second); static std::string divide(const std::string & first, const std::string & second); static std::string mod(const std::string & first, const std::string & second); static std::string calculate(const std::string & first, const std::string & second, char action); static std::string sin(const std::string & tok); static std::string cos(const std::string & tok); static std::string tan(const std::string & tok); static std::string abs(const std::string & tok); static bool isEqual(const std::string & first, const std::string & second); static bool isNotEqual(const std::string & first, const std::string & second); static bool isGreater(const std::string & first, const std::string & second); static bool isGreaterEqual(const std::string & first, const std::string & second); static bool isLess(const std::string & first, const std::string & second); static bool isLessEqual(const std::string & first, const std::string & second); static bool isNullValue(const std::string & str); /** * Return true if given character is 0,1,2,3,4,5,6 or 7. * @param[in] c The character to check * @return true if given character is octal digit. */ static bool isOctalDigit(char c); static unsigned int encodeMultiChar(const std::string& str); }; MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator-(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator*(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator/(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator%(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator&(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator|(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator^(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator<<(const MathLib::value &v1, const MathLib::value &v2); MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2); template<> CPPCHECKLIB std::string MathLib::toString<double>(double value); /// @} //--------------------------------------------------------------------------- #endif // mathlibH
6,148
C++
.h
124
44.83871
116
0.672276
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,435
color.h
danmar_cppcheck/lib/color.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef colorH #define colorH #include "config.h" #include <cstdint> #include <ostream> #include <string> enum class Color : std::uint8_t { Reset = 0, Bold = 1, Dim = 2, FgRed = 31, FgGreen = 32, FgBlue = 34, FgMagenta = 35, FgDefault = 39 }; CPPCHECKLIB std::ostream& operator<<(std::ostream& os, Color c); CPPCHECKLIB std::string toString(Color c); extern CPPCHECKLIB bool gDisableColors; // for testing #endif
1,246
C++
.h
37
31.189189
72
0.704659
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,436
platform.h
danmar_cppcheck/lib/platform.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef platformH #define platformH //--------------------------------------------------------------------------- #include "config.h" #include "standards.h" #include <climits> #include <cstddef> #include <cstdint> #include <stdexcept> #include <string> #include <vector> /// @addtogroup Core /// @{ namespace tinyxml2 { class XMLDocument; } /** * @brief Platform settings */ class CPPCHECKLIB Platform { private: static long long min_value(int bit) { if (bit >= 64) return LLONG_MIN; return -(1LL << (bit-1)); } static long long max_value(int bit) { if (bit >= 64) return (~0ULL) >> 1; return (1LL << (bit-1)) - 1LL; } /** provides list of defines specified by the limit.h/climits includes */ std::string getLimitsDefines(bool c99) const; public: Platform(); bool isIntValue(long long value) const { return value >= min_value(int_bit) && value <= max_value(int_bit); } bool isIntValue(unsigned long long value) const { const unsigned long long intMax = max_value(int_bit); return value <= intMax; } bool isLongValue(long long value) const { return value >= min_value(long_bit) && value <= max_value(long_bit); } bool isLongValue(unsigned long long value) const { const unsigned long long longMax = max_value(long_bit); return value <= longMax; } bool isLongLongValue(unsigned long long value) const { const unsigned long long longLongMax = max_value(long_long_bit); return value <= longLongMax; } nonneg int char_bit; /// bits in char nonneg int short_bit; /// bits in short nonneg int int_bit; /// bits in int nonneg int long_bit; /// bits in long nonneg int long_long_bit; /// bits in long long /** size of standard types */ std::size_t sizeof_bool; std::size_t sizeof_short; std::size_t sizeof_int; std::size_t sizeof_long; std::size_t sizeof_long_long; std::size_t sizeof_float; std::size_t sizeof_double; std::size_t sizeof_long_double; std::size_t sizeof_wchar_t; std::size_t sizeof_size_t; std::size_t sizeof_pointer; char defaultSign; // unsigned:'u', signed:'s', unknown:'\0' enum Type : std::uint8_t { Unspecified, // No platform specified Native, // whatever system this code was compiled on Win32A, Win32W, Win64, Unix32, Unix64, File }; /** platform type */ Type type; /** set the platform type for predefined platforms - deprecated use set(const std::string&, std::string&) instead */ bool set(Type t); /** set the platform type */ bool set(const std::string& platformstr, std::string& errstr, const std::vector<std::string>& paths = {}, bool debug = false); /** * load platform file * @param exename application path * @param filename platform filename * @param debug log verbose information about the lookup * @return returns true if file was loaded successfully */ bool loadFromFile(const char exename[], const std::string &filename, bool debug = false); /** load platform from xml document, primarily for testing */ bool loadFromXmlDocument(const tinyxml2::XMLDocument *doc); /** * @brief Returns true if platform type is Windows * @return true if Windows platform type. */ bool isWindows() const { return type == Type::Win32A || type == Type::Win32W || type == Type::Win64; } const char *toString() const { return toString(type); } static const char *toString(Type pt) { switch (pt) { case Type::Unspecified: return "unspecified"; case Type::Native: return "native"; case Type::Win32A: return "win32A"; case Type::Win32W: return "win32W"; case Type::Win64: return "win64"; case Type::Unix32: return "unix32"; case Type::Unix64: return "unix64"; case Type::File: return "platformFile"; default: throw std::runtime_error("unknown platform"); } } long long unsignedCharMax() const { return max_value(char_bit + 1); } long long signedCharMax() const { return max_value(char_bit); } long long signedCharMin() const { return min_value(char_bit); } /** provides list of defines specified by the limit.h/climits includes */ std::string getLimitsDefines(Standards::cstd_t cstd) const; /** provides list of defines specified by the limit.h/climits includes */ std::string getLimitsDefines(Standards::cppstd_t cppstd) const; }; /// @} //--------------------------------------------------------------------------- #endif // platformH
5,794
C++
.h
166
29.066265
130
0.61254
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,437
vf_settokenvalue.h
danmar_cppcheck/lib/vf_settokenvalue.h
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfSetTokenValueH #define vfSetTokenValueH #include "sourcelocation.h" class Token; class Settings; namespace ValueFlow { class Value; } namespace ValueFlow { void setTokenValue(Token* tok, Value value, const Settings& settings, SourceLocation loc = SourceLocation::current()); } #endif // vfSetTokenValueH
1,142
C++
.h
31
32.806452
72
0.725136
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,438
checkvaarg.h
danmar_cppcheck/lib/checkvaarg.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkvaargtH #define checkvaargtH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "tokenize.h" #include <string> class ErrorLogger; class Settings; class Token; /// @addtogroup Checks /// @{ /** * @brief Checking for misusage of variable argument lists */ class CPPCHECKLIB CheckVaarg : public Check { public: CheckVaarg() : Check(myName()) {} private: CheckVaarg(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckVaarg check(&tokenizer, &tokenizer.getSettings(), errorLogger); check.va_start_argument(); check.va_list_usage(); } void va_start_argument(); void va_list_usage(); void wrongParameterTo_va_start_error(const Token *tok, const std::string& paramIsName, const std::string& paramShouldName); void referenceAs_va_start_error(const Token *tok, const std::string& paramName); void va_end_missingError(const Token *tok, const std::string& varname); void va_list_usedBeforeStartedError(const Token *tok, const std::string& varname); void va_start_subsequentCallsError(const Token *tok, const std::string& varname); void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckVaarg c(nullptr, settings, errorLogger); c.wrongParameterTo_va_start_error(nullptr, "arg1", "arg2"); c.referenceAs_va_start_error(nullptr, "arg1"); c.va_end_missingError(nullptr, "vl"); c.va_list_usedBeforeStartedError(nullptr, "vl"); c.va_start_subsequentCallsError(nullptr, "vl"); } static std::string myName() { return "Vaarg"; } std::string classInfo() const override { return "Check for misusage of variable argument lists:\n" "- Wrong parameter passed to va_start()\n" "- Reference passed to va_start()\n" "- Missing va_end()\n" "- Using va_list before it is opened\n" "- Subsequent calls to va_start/va_copy()\n"; } }; /// @} //--------------------------------------------------------------------------- #endif // checkvaargtH
3,204
C++
.h
74
38.594595
127
0.648571
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,439
pathmatch.h
danmar_cppcheck/lib/pathmatch.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PATHMATCH_H #define PATHMATCH_H #include "config.h" #include <string> #include <vector> /// @addtogroup CLI /// @{ /** * @brief Simple path matching for ignoring paths in CLI. */ class CPPCHECKLIB PathMatch { public: /** * The constructor. * @param paths List of masks. * @param caseSensitive Match the case of the characters when * matching paths? */ explicit PathMatch(std::vector<std::string> paths, bool caseSensitive = true); /** * @brief Match path against list of masks. * @param path Path to match. * @return true if any of the masks match the path, false otherwise. */ bool match(const std::string &path) const; protected: /** * @brief Remove filename part from the path. * @param path Path to edit. * @return path without filename part. */ static std::string removeFilename(const std::string &path); private: std::vector<std::string> mPaths; bool mCaseSensitive; std::vector<std::string> mWorkingDirectory; }; /// @} #endif // PATHMATCH_H
1,836
C++
.h
56
29.446429
82
0.703054
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,440
vf_arraybool.h
danmar_cppcheck/lib/vf_arraybool.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfArrayBoolH #define vfArrayBoolH class TokenList; class Settings; namespace ValueFlow { void analyzeArrayBool(TokenList &tokenlist, const Settings &settings); } #endif // vfArrayBoolH
963
C++
.h
26
35.115385
74
0.760986
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,441
checkers.h
danmar_cppcheck/lib/checkers.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef checkersH #define checkersH #include <map> #include <string> #include <vector> #include "config.h" namespace checkers { extern CPPCHECKLIB const std::map<std::string, std::string> allCheckers; extern CPPCHECKLIB const std::map<std::string, std::string> premiumCheckers; struct CPPCHECKLIB MisraInfo { int a; int b; const char* str; int amendment; }; struct CPPCHECKLIB MisraCppInfo { int a; int b; int c; const char* classification; }; extern CPPCHECKLIB const char Req[]; // = "Required"; extern CPPCHECKLIB const char Adv[]; // = "Advisory"; extern CPPCHECKLIB const char Man[]; // = "Mandatory"; extern CPPCHECKLIB const char Doc[]; // = "Document"; extern CPPCHECKLIB const std::vector<MisraInfo> misraC2012Directives; extern CPPCHECKLIB const std::vector<MisraInfo> misraC2012Rules; extern CPPCHECKLIB const std::vector<MisraCppInfo> misraCpp2008Rules; extern CPPCHECKLIB const std::vector<MisraCppInfo> misraCpp2023Rules; extern CPPCHECKLIB const std::map<std::string, std::string> misraRuleSeverity; struct CPPCHECKLIB IdMapping { const char* guideline; const char* cppcheckId; }; extern std::vector<IdMapping> idMappingMisraC; extern std::vector<IdMapping> idMappingMisraCpp2008; extern std::vector<IdMapping> idMappingMisraCpp2023; extern std::vector<IdMapping> idMappingAutosar; extern std::vector<IdMapping> idMappingCertC; extern std::vector<IdMapping> idMappingCertCpp; struct CPPCHECKLIB Info { const char* guideline; const char* classification; }; extern std::vector<Info> autosarInfo; extern std::vector<Info> certCInfo; extern std::vector<Info> certCppInfo; } #endif
2,574
C++
.h
66
34.424242
82
0.721955
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,442
precompiled.h
danmar_cppcheck/lib/precompiled.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // IWYU pragma: begin_keep #include "astutils.h" #include "errorlogger.h" #include "library.h" //#include "matchcompiler.h" #include "mathlib.h" #include "token.h" #include "settings.h" #include "suppressions.h" #include "utils.h" #include "valueflow.h" // IWYU pragma: end_keep
1,056
C++
.h
30
33.6
72
0.746094
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,443
vf_globalconstvar.h
danmar_cppcheck/lib/vf_globalconstvar.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfGlobalConstVarH #define vfGlobalConstVarH class TokenList; class Settings; namespace ValueFlow { void analyzeGlobalConstVar(TokenList& tokenList, const Settings &settings); } #endif // vfGlobalConstVarH
983
C++
.h
26
35.884615
79
0.766002
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,444
analyzer.h
danmar_cppcheck/lib/analyzer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef analyzerH #define analyzerH #include "config.h" #include "mathlib.h" #include <cstdint> #include <string> #include <type_traits> #include <vector> class Token; template<class T> class ValuePtr; struct Analyzer { struct Action { Action() = default; Action(const Action&) = default; Action& operator=(const Action& rhs) & = default; template<class T, REQUIRES("T must be convertible to unsigned int", std::is_convertible<T, unsigned int> ), REQUIRES("T must not be a bool", !std::is_same<T, bool> )> // NOLINTNEXTLINE(google-explicit-constructor) Action(T f) : mFlag(f) // cppcheck-suppress noExplicitConstructor {} enum : std::uint16_t { None = 0, Read = (1 << 0), Write = (1 << 1), Invalid = (1 << 2), Inconclusive = (1 << 3), Match = (1 << 4), Idempotent = (1 << 5), Incremental = (1 << 6), SymbolicMatch = (1 << 7), Internal = (1 << 8), }; void set(unsigned int f, bool state = true) { mFlag = state ? mFlag | f : mFlag & ~f; } bool get(unsigned int f) const { return ((mFlag & f) != 0); } bool isRead() const { return get(Read); } bool isWrite() const { return get(Write); } bool isInvalid() const { return get(Invalid); } bool isInconclusive() const { return get(Inconclusive); } bool isNone() const { return mFlag == None; } bool isModified() const { return isWrite() || isInvalid(); } bool isIdempotent() const { return get(Idempotent); } bool isIncremental() const { return get(Incremental); } bool isSymbolicMatch() const { return get(SymbolicMatch); } bool isInternal() const { return get(Internal); } bool matches() const { return get(Match); } Action& operator|=(Action a) { set(a.mFlag); return *this; } friend Action operator|(Action a, Action b) { a |= b; return a; } friend bool operator==(Action a, Action b) { return a.mFlag == b.mFlag; } friend bool operator!=(Action a, Action b) { return a.mFlag != b.mFlag; } private: unsigned int mFlag{}; }; enum class Terminate : std::uint8_t { None, Bail, Escape, Modified, Inconclusive, Conditional }; struct Result { explicit Result(Action action = Action::None, Terminate terminate = Terminate::None) : action(action), terminate(terminate) {} Action action; Terminate terminate; void update(Result rhs) { if (terminate == Terminate::None) terminate = rhs.terminate; action |= rhs.action; } }; enum class Direction : std::uint8_t { Forward, Reverse }; struct Assume { enum Flags : std::uint8_t { None = 0, Quiet = (1 << 0), Absolute = (1 << 1), ContainerEmpty = (1 << 2), }; }; enum class Evaluate : std::uint8_t { Integral, ContainerEmpty }; /// Analyze a token virtual Action analyze(const Token* tok, Direction d) const = 0; /// Update the state of the value virtual void update(Token* tok, Action a, Direction d) = 0; /// Try to evaluate the value of a token(most likely a condition) virtual std::vector<MathLib::bigint> evaluate(Evaluate e, const Token* tok, const Token* ctx = nullptr) const = 0; std::vector<MathLib::bigint> evaluate(const Token* tok, const Token* ctx = nullptr) const { return evaluate(Evaluate::Integral, tok, ctx); } /// Lower any values to possible virtual bool lowerToPossible() = 0; /// Lower any values to inconclusive virtual bool lowerToInconclusive() = 0; /// If the analysis is unsure whether to update a scope, this will return true if the analysis should bifurcate the scope virtual bool updateScope(const Token* endBlock, bool modified) const = 0; /// If the value is conditional virtual bool isConditional() const = 0; /// If analysis should stop on the condition virtual bool stopOnCondition(const Token* condTok) const = 0; /// The condition that will be assumed during analysis virtual void assume(const Token* tok, bool state, unsigned int flags = 0) = 0; /// Update the state of the program at the token virtual void updateState(const Token* tok) = 0; /// Return analyzer for expression at token virtual ValuePtr<Analyzer> reanalyze(Token* tok, const std::string& msg = emptyString) const = 0; virtual bool invalid() const { return false; } virtual ~Analyzer() = default; Analyzer(const Analyzer&) = default; protected: Analyzer() = default; }; #endif
5,934
C++
.h
165
28.151515
125
0.597908
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,445
checkunusedfunctions.h
danmar_cppcheck/lib/checkunusedfunctions.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkunusedfunctionsH #define checkunusedfunctionsH //--------------------------------------------------------------------------- #include "config.h" #include <list> #include <set> #include <string> #include <unordered_map> class ErrorLogger; class Function; class Settings; class Tokenizer; /** @brief Check for functions never called */ /// @{ class CPPCHECKLIB CheckUnusedFunctions { friend class TestSuppressions; friend class TestSingleExecutorBase; friend class TestProcessExecutorBase; friend class TestThreadExecutorBase; friend class TestUnusedFunctions; public: CheckUnusedFunctions() = default; // Parse current tokens and determine.. // * Check what functions are used // * What functions are declared void parseTokens(const Tokenizer &tokenizer, const Settings &settings); std::string analyzerInfo() const; static void analyseWholeProgram(const Settings &settings, ErrorLogger& errorLogger, const std::string &buildDir); static void getErrorMessages(ErrorLogger &errorLogger) { unusedFunctionError(errorLogger, emptyString, 0, 0, "funcName"); } // Return true if an error is reported. bool check(const Settings& settings, ErrorLogger& errorLogger) const; void updateFunctionData(const CheckUnusedFunctions& check); private: static void unusedFunctionError(ErrorLogger& errorLogger, const std::string &filename, unsigned int fileIndex, unsigned int lineNumber, const std::string &funcname); struct CPPCHECKLIB FunctionUsage { std::string filename; unsigned int lineNumber{}; unsigned int fileIndex{}; bool usedSameFile{}; bool usedOtherFile{}; }; std::unordered_map<std::string, FunctionUsage> mFunctions; class CPPCHECKLIB FunctionDecl { public: explicit FunctionDecl(const Function *f); std::string functionName; std::string fileName; unsigned int lineNumber; }; std::list<FunctionDecl> mFunctionDecl; std::set<std::string> mFunctionCalls; }; /// @} //--------------------------------------------------------------------------- #endif // checkunusedfunctionsH
3,096
C++
.h
77
35.441558
117
0.669444
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,446
fwdanalysis.h
danmar_cppcheck/lib/fwdanalysis.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef fwdanalysisH #define fwdanalysisH //--------------------------------------------------------------------------- #include "config.h" #include <cstdint> #include <set> #include <vector> class Token; class Settings; /** * Forward data flow analysis for checks * - unused value * - redundant assignment * - valueflow analysis */ class FwdAnalysis { public: explicit FwdAnalysis(const Settings &settings) : mSettings(settings) {} bool hasOperand(const Token *tok, const Token *lhs) const; /** * Check if "expr" is reassigned. The "expr" can be a tree (x.y[12]). * @param expr Symbolic expression to perform forward analysis for * @param startToken First token in forward analysis * @param endToken Last token in forward analysis * @return Token where expr is reassigned. If it's not reassigned then nullptr is returned. */ const Token *reassign(const Token *expr, const Token *startToken, const Token *endToken); /** * Check if "expr" is used. The "expr" can be a tree (x.y[12]). * @param expr Symbolic expression to perform forward analysis for * @param startToken First token in forward analysis * @param endToken Last token in forward analysis * @return true if expr is used. */ bool unusedValue(const Token *expr, const Token *startToken, const Token *endToken); struct KnownAndToken { bool known{}; const Token* token{}; }; /** Is there some possible alias for given expression */ bool possiblyAliased(const Token *expr, const Token *startToken) const; std::set<nonneg int> getExprVarIds(const Token* expr, bool* localOut = nullptr, bool* unknownVarIdOut = nullptr) const; private: static bool isEscapedAlias(const Token* expr); /** Result of forward analysis */ struct Result { enum class Type : std::uint8_t { NONE, READ, WRITE, BREAK, RETURN, BAILOUT } type; explicit Result(Type type) : type(type) {} Result(Type type, const Token *token) : type(type), token(token) {} const Token* token{}; }; Result check(const Token *expr, const Token *startToken, const Token *endToken); Result checkRecursive(const Token *expr, const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local, bool inInnerClass, int depth=0); const Settings &mSettings; enum class What : std::uint8_t { Reassign, UnusedValue, ValueFlow } mWhat = What::Reassign; std::vector<KnownAndToken> mValueFlow; bool mValueFlowKnown = true; }; #endif // fwdanalysisH
3,429
C++
.h
77
40.571429
177
0.680851
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,447
check.h
danmar_cppcheck/lib/check.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkH #define checkH //--------------------------------------------------------------------------- #include "config.h" #include "errortypes.h" #include <list> #include <string> #include <utility> namespace tinyxml2 { class XMLElement; } namespace CTU { class FileInfo; } namespace ValueFlow { class Value; } class Settings; class Token; class ErrorLogger; class ErrorMessage; class Tokenizer; /** Use WRONG_DATA in checkers to mark conditions that check that data is correct */ #define WRONG_DATA(COND, TOK) ((COND) && wrongData((TOK), #COND)) /// @addtogroup Core /// @{ /** * @brief Interface class that cppcheck uses to communicate with the checks. * All checking classes must inherit from this class */ class CPPCHECKLIB Check { public: /** This constructor is used when registering the CheckClass */ explicit Check(const std::string &aname); protected: /** This constructor is used when running checks. */ Check(std::string aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger), mName(std::move(aname)) {} public: virtual ~Check() { if (!mTokenizer) instances().remove(this); } Check(const Check &) = delete; Check& operator=(const Check &) = delete; /** List of registered check classes. This is used by Cppcheck to run checks and generate documentation */ static std::list<Check *> &instances(); /** run checks, the token list is not simplified */ virtual void runChecks(const Tokenizer &, ErrorLogger *) = 0; /** get error messages */ virtual void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const = 0; /** class name, used to generate documentation */ const std::string& name() const { return mName; } /** get information about this class, used to generate documentation */ virtual std::string classInfo() const = 0; /** * Write given error to stdout in xml format. * This is for for printout out the error list with --errorlist * @param errmsg Error message to write */ static void writeToErrorList(const ErrorMessage &errmsg); /** Base class used for whole-program analysis */ class CPPCHECKLIB FileInfo { public: FileInfo() = default; virtual ~FileInfo() = default; virtual std::string toString() const { return std::string(); } }; virtual FileInfo * getFileInfo(const Tokenizer& /*tokenizer*/, const Settings& /*settings*/) const { return nullptr; } virtual FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const { (void)xmlElement; return nullptr; } // Return true if an error is reported. virtual bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<FileInfo*> &fileInfo, const Settings& /*settings*/, ErrorLogger & /*errorLogger*/) { (void)ctu; (void)fileInfo; //(void)settings; //(void)errorLogger; return false; } protected: static std::string getMessageId(const ValueFlow::Value &value, const char id[]); const Tokenizer* const mTokenizer{}; const Settings* const mSettings{}; ErrorLogger* const mErrorLogger{}; /** report an error */ void reportError(const Token *tok, const Severity severity, const std::string &id, const std::string &msg) { reportError(tok, severity, id, msg, CWE(0U), Certainty::normal); } /** report an error */ void reportError(const Token *tok, const Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty) { const std::list<const Token *> callstack(1, tok); reportError(callstack, severity, id, msg, cwe, certainty); } /** report an error */ void reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg) { reportError(callstack, severity, id, msg, CWE(0U), Certainty::normal); } /** report an error */ void reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty); void reportError(const ErrorPath &errorPath, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty); /** log checker */ void logChecker(const char id[]); ErrorPath getErrorPath(const Token* errtok, const ValueFlow::Value* value, std::string bug) const; /** * Use WRONG_DATA in checkers when you check for wrong data. That * will call this method */ bool wrongData(const Token *tok, const char *str); private: const std::string mName; }; /// @} //--------------------------------------------------------------------------- #endif // checkH
5,796
C++
.h
140
36.878571
167
0.666607
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,448
tokenrange.h
danmar_cppcheck/lib/tokenrange.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef tokenrangeH #define tokenrangeH //--------------------------------------------------------------------------- #include "config.h" #include <cstddef> #include <iterator> #include <type_traits> class Token; template<typename T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> class TokenRangeBase { T* mFront; T* mBack; public: TokenRangeBase(T* front, T* back) : mFront(front), mBack(back) {} struct TokenIterator { using iterator_category = std::forward_iterator_tag; using value_type = T*; using difference_type = std::ptrdiff_t; using pointer = void; using reference = T*; T* mt; TokenIterator() : mt(nullptr) {} explicit TokenIterator(T* t) : mt(t) {} TokenIterator& operator++() { mt = mt->next(); return *this; } bool operator==(const TokenIterator& b) const { return mt == b.mt; } bool operator!=(const TokenIterator& b) const { return mt != b.mt; } T* operator*() const { return mt; } }; TokenIterator begin() const { return TokenIterator(mFront); } TokenIterator end() const { return TokenIterator(mBack); } }; class TokenRange : public TokenRangeBase<Token> { public: TokenRange(Token* front, Token* back) : TokenRangeBase<Token>(front, back) {} }; class ConstTokenRange : public TokenRangeBase<const Token> { public: ConstTokenRange(const Token* front, const Token* back) : TokenRangeBase<const Token>(front, back) {} }; #endif // tokenrangeH
2,490
C++
.h
71
30.183099
104
0.622351
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,449
settings.h
danmar_cppcheck/lib/settings.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef settingsH #define settingsH //--------------------------------------------------------------------------- #include "addoninfo.h" #include "config.h" #include "errortypes.h" #include "library.h" #include "platform.h" #include "standards.h" #include "suppressions.h" #include <algorithm> #include <atomic> #include <cstddef> #include <cstdint> #include <functional> #include <list> #include <map> #include <set> #include <string> #include <tuple> #include <vector> #include <unordered_set> #include <utility> enum class SHOWTIME_MODES : std::uint8_t; namespace ValueFlow { class Value; } /// @addtogroup Core /// @{ template<typename T> class SimpleEnableGroup { uint32_t mFlags = 0; public: uint32_t intValue() const { return mFlags; } void clear() { mFlags = 0; } void fill() { mFlags = 0xFFFFFFFF; } bool isEnabled(T flag) const { return (mFlags & (1U << (uint32_t)flag)) != 0; } void enable(T flag) { mFlags |= (1U << (uint32_t)flag); } void enable(SimpleEnableGroup<T> group) { mFlags |= group.intValue(); } void disable(T flag) { mFlags &= ~(1U << (uint32_t)flag); } void disable(SimpleEnableGroup<T> group) { mFlags &= ~(group.intValue()); } void setEnabled(T flag, bool enabled) { if (enabled) enable(flag); else disable(flag); } }; /** * @brief This is just a container for general settings so that we don't need * to pass individual values to functions or constructors now or in the * future when we might have even more detailed settings. */ class CPPCHECKLIB WARN_UNUSED Settings { private: /** @brief terminate checking */ static std::atomic<bool> mTerminated; public: Settings(); static std::string loadCppcheckCfg(Settings& settings, Suppressions& suppressions, bool debug = false); static std::pair<std::string, std::string> getNameAndVersion(const std::string& productName); /** @brief addons, either filename of python/json file or json data */ std::unordered_set<std::string> addons; /** @brief the loaded addons infos */ std::vector<AddonInfo> addonInfos; /** @brief Path to the python interpreter to be used to run addons. */ std::string addonPython; /** @brief Paths used as base for conversion to relative paths. */ std::vector<std::string> basePaths; /** @brief --cppcheck-build-dir. Always uses / as path separator. No trailing path separator. */ std::string buildDir; /** @brief check all configurations (false if -D or --max-configs is used */ bool checkAllConfigurations = true; /** Is the 'configuration checking' wanted? */ bool checkConfiguration{}; /** * Check code in the headers, this is on by default but can * be turned off to save CPU */ bool checkHeaders = true; /** Check for incomplete info in library files? */ bool checkLibrary{}; /** @brief The maximum time in seconds for the checks of a single file */ int checksMaxTime{}; /** @brief --checkers-report=<filename> : Generate report of executed checkers */ std::string checkersReportFilename; /** @brief check unknown function return values */ std::set<std::string> checkUnknownFunctionReturn; /** Check unused/uninstantiated templates */ bool checkUnusedTemplates = true; /** Use Clang */ bool clang{}; /** Custom Clang executable */ std::string clangExecutable = "clang"; /** Use clang-tidy */ bool clangTidy{}; /** Internal: Clear the simplecpp non-existing include cache */ bool clearIncludeCache{}; /** @brief include paths excluded from checking the configuration */ std::set<std::string> configExcludePaths; /** cppcheck.cfg: Custom product name */ std::string cppcheckCfgProductName; /** cppcheck.cfg: About text */ std::string cppcheckCfgAbout; /** @brief check Emacs marker to detect extension-less and *.h files as C++ */ bool cppHeaderProbe{}; /** @brief Are we running from DACA script? */ bool daca{}; /** @brief Internal: Is --debug-lookup or --debug-lookup=all given? */ bool debuglookup{}; /** @brief Internal: Is --debug-lookup=addon given? */ bool debuglookupAddon{}; /** @brief Internal: Is --debug-lookup=config given? */ bool debuglookupConfig{}; /** @brief Internal: Is --debug-lookup=library given? */ bool debuglookupLibrary{}; /** @brief Internal: Is --debug-lookup=platform given? */ bool debuglookupPlatform{}; /** @brief Is --debug-normal given? */ bool debugnormal{}; /** @brief Is --debug-simplified given? */ bool debugSimplified{}; /** @brief Is --debug-template given? */ bool debugtemplate{}; /** @brief Is --debug-warnings given? */ bool debugwarnings{}; /** @brief Is --dump given? */ bool dump{}; std::string dumpFile; /** @brief Name of the language that is enforced. Empty per default. */ Standards::Language enforcedLang{}; #if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING) /** @brief Is --exception-handling given */ bool exceptionHandling{}; FILE* exceptionOutput = stdout; #endif enum class ExecutorType : std::uint8_t { #ifdef HAS_THREADING_MODEL_THREAD Thread, #endif #ifdef HAS_THREADING_MODEL_FORK Process #endif }; ExecutorType executor; // argv[0] std::string exename; /** @brief If errors are found, this value is returned from main(). Default value is 0. */ int exitCode{}; /** @brief List of --file-filter for analyzing special files */ std::vector<std::string> fileFilters; /** @brief Force checking the files with "too many" configurations (--force). */ bool force{}; /** @brief List of include paths, e.g. "my/includes/" which should be used for finding include files inside source files. (-I) */ std::list<std::string> includePaths; /** @brief Is --inline-suppr given? */ bool inlineSuppressions{}; /** @brief How many processes/threads should do checking at the same time. Default is 1. (-j N) */ unsigned int jobs = 1; /** @brief --library= */ std::list<std::string> libraries; /** Library */ Library library; /** @brief Load average value */ int loadAverage{}; /** @brief Maximum number of configurations to check before bailing. Default is 12. (--max-configs=N) */ int maxConfigs = 12; /** @brief --max-ctu-depth */ int maxCtuDepth = 2; /** @brief max template recursion */ int maxTemplateRecursion = 100; /** @brief write results (--output-file=&lt;file&gt;) */ std::string outputFile; enum class OutputFormat : std::uint8_t {text, plist, sarif, xml}; OutputFormat outputFormat = OutputFormat::text; Platform platform; /** @brief pid of cppcheck. Intention is that this is set in the main process. */ int pid; /** @brief plist output (--plist-output=&lt;dir&gt;) */ std::string plistOutput; /** @brief Extra arguments for Cppcheck Premium addon */ std::string premiumArgs; /** Is checker id enabled by premiumArgs */ bool isPremiumEnabled(const char id[]) const; /** @brief Using -E for debugging purposes */ bool preprocessOnly{}; /** @brief Is --quiet given? */ bool quiet{}; /** @brief Use relative paths in output. */ bool relativePaths{}; /** @brief --report-progress */ int reportProgress{-1}; #ifdef HAVE_RULES /** Rule */ struct CPPCHECKLIB Rule { std::string tokenlist = "normal"; // use normal tokenlist std::string pattern; std::string id = "rule"; // default id std::string summary; Severity severity = Severity::style; // default severity }; /** * @brief Extra rules */ std::list<Rule> rules; #endif /** * @brief Safety certified behavior * Show checkers report when Cppcheck finishes * Make cppcheck checking more strict about critical errors * - returns nonzero if there is critical errors * - a critical error id is not suppressed (by mistake?) with glob pattern */ bool safety = false; /** Do not only check how interface is used. Also check that interface is safe. */ struct CPPCHECKLIB SafeChecks { static const char XmlRootName[]; static const char XmlClasses[]; static const char XmlExternalFunctions[]; static const char XmlInternalFunctions[]; static const char XmlExternalVariables[]; void clear() { classes = externalFunctions = internalFunctions = externalVariables = false; } /** * Public interface of classes * - public function parameters can have any value * - public functions can be called in any order * - public variables can have any value */ bool classes{}; /** * External functions * - external functions can be called in any order * - function parameters can have any values */ bool externalFunctions{}; /** * Experimental: assume that internal functions can be used in any way * This is only available in the GUI. */ bool internalFunctions{}; /** * Global variables that can be modified outside the TU. * - Such variable can have "any" value */ bool externalVariables{}; }; SafeChecks safeChecks; SimpleEnableGroup<Severity> severity; SimpleEnableGroup<Certainty> certainty; SimpleEnableGroup<Checks> checks; /** @brief show timing information (--showtime=file|summary|top5) */ SHOWTIME_MODES showtime{}; /** Struct contains standards settings */ Standards standards; /** @brief suppressions */ Suppressions supprs; /** @brief The output format in which the errors are printed in text mode, e.g. "{severity} {file}:{line} {message} {id}" */ std::string templateFormat; /** @brief The output format in which the error locations are printed in * text mode, e.g. "{file}:{line} {info}" */ std::string templateLocation; /** @brief The maximum time in seconds for the template instantiation */ std::size_t templateMaxTime{}; /** @brief The maximum time in seconds for the typedef simplification */ std::size_t typedefMaxTime{}; /** @brief defines given by the user */ std::string userDefines; /** @brief undefines given by the user */ std::set<std::string> userUndefs; /** @brief forced includes given by the user */ std::list<std::string> userIncludes; // TODO: adjust all options so 0 means "disabled" and -1 "means "unlimited" struct ValueFlowOptions { /** @brief the maximum iterations to execute */ std::size_t maxIterations = 4; /** @brief maximum numer if-branches */ int maxIfCount = -1; /** @brief maximum number of sets of arguments to pass to subfuncions */ int maxSubFunctionArgs = 256; /** @brief Experimental: maximum execution time */ int maxTime = -1; /** @brief Control if condition expression analysis is performed */ bool doConditionExpressionAnalysis = true; /** @brief Maximum performed for-loop count */ int maxForLoopCount = 10000; /** @brief Maximum performed forward branches */ int maxForwardBranches = -1; /** @brief Maximum performed alignof recursion */ int maxAlignOfRecursion = 100; /** @brief Maximum performed sizeof recursion */ int maxSizeOfRecursion = 100; /** @brief Maximum expression varid depth */ int maxExprVarIdDepth = 4; }; /** @brief The ValueFlow options */ ValueFlowOptions vfOptions; /** @brief Is --verbose given? */ bool verbose{}; /** @brief write XML results (--xml) */ bool xml{}; /** @brief XML version (--xml-version=..) */ int xml_version = 2; /** * @brief return true if a included file is to be excluded in Preprocessor::getConfigs * @return true for the file to be excluded. */ bool configurationExcluded(const std::string &file) const { return std::any_of(configExcludePaths.begin(), configExcludePaths.end(), [&file](const std::string& path) { return file.length() >= path.length() && file.compare(0, path.length(), path) == 0; }); } /** * @brief Enable extra checks by id. See isEnabled() * @param str single id or list of id values to be enabled * or empty string to enable all. e.g. "style,possibleError" * @return error message. empty upon success */ std::string addEnabled(const std::string &str); /** * @brief Disable extra checks by id * @param str single id or list of id values to be enabled * or empty string to enable all. e.g. "style,possibleError" * @return error message. empty upon success */ std::string removeEnabled(const std::string &str); /** * @brief Returns true if given value can be shown * @return true if the value can be shown */ bool isEnabled(const ValueFlow::Value *value, bool inconclusiveCheck=false) const; /** Is library specified? */ bool hasLib(const std::string &lib) const { return std::find(libraries.cbegin(), libraries.cend(), lib) != libraries.cend(); } /** @brief Request termination of checking */ static void terminate(bool t = true) { Settings::mTerminated = t; } /** @brief termination requested? */ static bool terminated() { return Settings::mTerminated; } std::set<std::string> summaryReturn; void loadSummaries(); bool useSingleJob() const { return jobs == 1; } enum class CheckLevel : std::uint8_t { normal, exhaustive }; CheckLevel checkLevel = CheckLevel::exhaustive; void setCheckLevel(CheckLevel level); using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>; void setMisraRuleTexts(const ExecuteCmdFn& executeCommand); void setMisraRuleTexts(const std::string& data); std::string getMisraRuleText(const std::string& id, const std::string& text) const; static ExecutorType defaultExecutor(); private: static std::string parseEnabled(const std::string &str, std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> &groups); std::string applyEnabled(const std::string &str, bool enable); std::map<std::string, std::string> mMisraRuleTexts; }; /// @} //--------------------------------------------------------------------------- #endif // settingsH
15,746
C++
.h
408
32.968137
136
0.650431
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,450
checkersreport.h
danmar_cppcheck/lib/checkersreport.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef checkersReportH #define checkersReportH #include "config.h" #include <set> #include <string> class Settings; class CPPCHECKLIB CheckersReport { public: CheckersReport(const Settings& settings, const std::set<std::string>& activeCheckers); int getActiveCheckersCount(); int getAllCheckersCount(); std::string getReport(const std::string& criticalErrors) const; std::string getXmlReport(const std::string& criticalErrors) const; private: const Settings& mSettings; const std::set<std::string>& mActiveCheckers; void countCheckers(); int mActiveCheckersCount = 0; int mAllCheckersCount = 0; }; #endif
1,419
C++
.h
38
34.578947
90
0.754015
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,451
checknullpointer.h
danmar_cppcheck/lib/checknullpointer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checknullpointerH #define checknullpointerH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "tokenize.h" #include "vfvalue.h" #include <list> #include <string> class ErrorLogger; class Library; class Settings; class Token; namespace CTU { class FileInfo; } namespace tinyxml2 { class XMLElement; } /// @addtogroup Checks /// @{ /** @brief check for null pointer dereferencing */ class CPPCHECKLIB CheckNullPointer : public Check { friend class TestNullPointer; public: /** @brief This constructor is used when registering the CheckNullPointer */ CheckNullPointer() : Check(myName()) {} /** * Is there a pointer dereference? Everything that should result in * a nullpointer dereference error message will result in a true * return value. If it's unknown if the pointer is dereferenced false * is returned. * @param tok token for the pointer * @param unknown it is not known if there is a pointer dereference (could be reported as a debug message) * @return true => there is a dereference */ bool isPointerDeRef(const Token *tok, bool &unknown) const; static bool isPointerDeRef(const Token *tok, bool &unknown, const Settings &settings, bool checkNullArg = true); private: /** * @brief parse a function call and extract information about variable usage * @param tok first token * @param var variables that the function read / write. * @param library --library files data */ static void parseFunctionCall(const Token &tok, std::list<const Token *> &var, const Library &library, bool checkNullArg = true); /** @brief This constructor is used when running checks. */ CheckNullPointer(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} /** @brief Run checks against the normal token list */ void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckNullPointer checkNullPointer(&tokenizer, &tokenizer.getSettings(), errorLogger); checkNullPointer.nullPointer(); checkNullPointer.arithmetic(); checkNullPointer.nullConstantDereference(); } /** @brief possible null pointer dereference */ void nullPointer(); /** @brief dereferencing null constant (after Tokenizer::simplifyKnownVariables) */ void nullConstantDereference(); void nullPointerError(const Token *tok) { ValueFlow::Value v(0); v.setKnown(); nullPointerError(tok, emptyString, &v, false); } void nullPointerError(const Token *tok, const std::string &varname, const ValueFlow::Value* value, bool inconclusive); /** @brief Parse current TU and extract file info */ Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override; Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override; /** @brief Analyse all file infos for all TU */ bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override; /** Get error messages. Used by --errorlist */ void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckNullPointer c(nullptr, settings, errorLogger); c.nullPointerError(nullptr, "pointer", nullptr, false); c.pointerArithmeticError(nullptr, nullptr, false); c.redundantConditionWarning(nullptr, nullptr, nullptr, false); } /** Name of check */ static std::string myName() { return "Null pointer"; } /** class info in WIKI format. Used by --doc */ std::string classInfo() const override { return "Null pointers\n" "- null pointer dereferencing\n" "- undefined null pointer arithmetic\n"; } /** * @brief Does one part of the check for nullPointer(). * Dereferencing a pointer and then checking if it's NULL.. */ void nullPointerByDeRefAndCheck(); /** undefined null pointer arithmetic */ void arithmetic(); void pointerArithmeticError(const Token* tok, const ValueFlow::Value *value, bool inconclusive); void redundantConditionWarning(const Token* tok, const ValueFlow::Value *value, const Token *condition, bool inconclusive); }; /// @} //--------------------------------------------------------------------------- #endif // checknullpointerH
5,521
C++
.h
121
40.479339
161
0.680007
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,452
smallvector.h
danmar_cppcheck/lib/smallvector.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef smallvectorH #define smallvectorH #include <cstddef> static constexpr std::size_t DefaultSmallVectorSize = 3; #ifdef HAVE_BOOST #include <boost/container/small_vector.hpp> template<typename T, std::size_t N = DefaultSmallVectorSize> using SmallVector = boost::container::small_vector<T, N>; #else #include <utility> #include <vector> template<class T, std::size_t N> struct TaggedAllocator : std::allocator<T> { template<class ... Ts> // cppcheck-suppress noExplicitConstructor // NOLINTNEXTLINE(google-explicit-constructor) TaggedAllocator(Ts&&... ts) : std::allocator<T>(std::forward<Ts>(ts)...) {} template<class U> // cppcheck-suppress noExplicitConstructor // NOLINTNEXTLINE(google-explicit-constructor) TaggedAllocator(const TaggedAllocator<U, N> /*unused*/) {} template<class U> struct rebind { using other = TaggedAllocator<U, N>; }; }; template<typename T, std::size_t N = DefaultSmallVectorSize> class SmallVector : public std::vector<T, TaggedAllocator<T, N>> { public: template<class ... Ts> // NOLINTNEXTLINE(google-explicit-constructor) SmallVector(Ts&&... ts) : std::vector<T, TaggedAllocator<T, N>>(std::forward<Ts>(ts)...) { this->reserve(N); } }; #endif #endif
2,063
C++
.h
61
30.688525
72
0.720382
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,453
checkautovariables.h
danmar_cppcheck/lib/checkautovariables.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkautovariablesH #define checkautovariablesH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "errortypes.h" #include "tokenize.h" #include <string> #include <set> class Settings; class Token; class ErrorLogger; class Variable; namespace ValueFlow { class Value; } /// @addtogroup Checks /** @brief Various small checks for automatic variables */ /// @{ class CPPCHECKLIB CheckAutoVariables : public Check { public: /** This constructor is used when registering the CheckClass */ CheckAutoVariables() : Check(myName()) {} private: /** This constructor is used when running checks. */ CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} /** @brief Run checks against the normal token list */ void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckAutoVariables checkAutoVariables(&tokenizer, &tokenizer.getSettings(), errorLogger); checkAutoVariables.assignFunctionArg(); checkAutoVariables.checkVarLifetime(); checkAutoVariables.autoVariables(); } /** assign function argument */ void assignFunctionArg(); /** Check auto variables */ void autoVariables(); /** * Check variable assignment.. value must be changed later or there will be a error reported * @return true if error is reported */ bool checkAutoVariableAssignment(const Token *expr, bool inconclusive, const Token *startToken = nullptr); void checkVarLifetime(); void checkVarLifetimeScope(const Token * start, const Token * end); void errorAutoVariableAssignment(const Token *tok, bool inconclusive); void errorReturnDanglingLifetime(const Token *tok, const ValueFlow::Value* val); void errorInvalidLifetime(const Token *tok, const ValueFlow::Value* val); void errorDanglngLifetime(const Token *tok, const ValueFlow::Value *val); void errorDanglingTemporaryLifetime(const Token* tok, const ValueFlow::Value* val, const Token* tempTok); void errorReturnReference(const Token* tok, ErrorPath errorPath, bool inconclusive); void errorDanglingReference(const Token *tok, const Variable *var, ErrorPath errorPath); void errorDanglingTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive); void errorReturnTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive); void errorInvalidDeallocation(const Token *tok, const ValueFlow::Value *val); void errorUselessAssignmentArg(const Token *tok); void errorUselessAssignmentPtrArg(const Token *tok); void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckAutoVariables c(nullptr,settings,errorLogger); c.errorAutoVariableAssignment(nullptr, false); c.errorReturnReference(nullptr, ErrorPath{}, false); c.errorDanglingReference(nullptr, nullptr, ErrorPath{}); c.errorReturnTempReference(nullptr, ErrorPath{}, false); c.errorDanglingTempReference(nullptr, ErrorPath{}, false); c.errorInvalidDeallocation(nullptr, nullptr); c.errorUselessAssignmentArg(nullptr); c.errorUselessAssignmentPtrArg(nullptr); c.errorReturnDanglingLifetime(nullptr, nullptr); c.errorInvalidLifetime(nullptr, nullptr); c.errorDanglngLifetime(nullptr, nullptr); c.errorDanglingTemporaryLifetime(nullptr, nullptr, nullptr); } static std::string myName() { return "Auto Variables"; } std::string classInfo() const override { 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" "- assigning address of an variable to an effective parameter of a function\n" "- returning reference to local/temporary variable\n" "- returning address of function parameter\n" "- suspicious assignment of pointer argument\n" "- useless assignment of function argument\n"; } /** returns true if tokvalue has already been diagnosed */ bool diag(const Token* tokvalue); std::set<const Token*> mDiagDanglingTemp; }; /// @} //--------------------------------------------------------------------------- #endif // checkautovariablesH
5,354
C++
.h
109
43.889908
110
0.70113
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,454
library.h
danmar_cppcheck/lib/library.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef libraryH #define libraryH //--------------------------------------------------------------------------- #include "config.h" #include "mathlib.h" #include "standards.h" #include <array> #include <cstdint> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> class Token; enum class Severity : std::uint8_t; namespace tinyxml2 { class XMLDocument; class XMLElement; } /// @addtogroup Core /// @{ /** * @brief Library definitions handling */ class CPPCHECKLIB Library { friend struct LibraryHelper; // for testing public: Library(); ~Library(); Library(const Library& other); Library& operator=(const Library& other) &; enum class ErrorCode : std::uint8_t { OK, FILE_NOT_FOUND, BAD_XML, UNKNOWN_ELEMENT, MISSING_ATTRIBUTE, BAD_ATTRIBUTE_VALUE, UNSUPPORTED_FORMAT, DUPLICATE_PLATFORM_TYPE, PLATFORM_TYPE_REDEFINED, DUPLICATE_DEFINE }; class Error { public: Error() : errorcode(ErrorCode::OK) {} explicit Error(ErrorCode e) : errorcode(e) {} template<typename T> Error(ErrorCode e, T&& r) : errorcode(e), reason(r) {} ErrorCode errorcode; std::string reason; }; Error load(const char exename[], const char path[], bool debug = false); struct AllocFunc { int groupId{}; int arg{}; enum class BufferSize : std::uint8_t {none,malloc,calloc,strdup}; BufferSize bufferSize{BufferSize::none}; int bufferSizeArg1{}; int bufferSizeArg2{}; int reallocArg{}; bool initData{}; }; /** get allocation info for function */ const AllocFunc* getAllocFuncInfo(const Token *tok) const; /** get deallocation info for function */ const AllocFunc* getDeallocFuncInfo(const Token *tok) const; /** get reallocation info for function */ const AllocFunc* getReallocFuncInfo(const Token *tok) const; /** get allocation id for function */ int getAllocId(const Token *tok, int arg) const; /** get deallocation id for function */ int getDeallocId(const Token *tok, int arg) const; /** get reallocation id for function */ int getReallocId(const Token *tok, int arg) const; // TODO: get rid of this /** get allocation info for function by name (deprecated, use other alloc) */ const AllocFunc* getAllocFuncInfo(const char name[]) const; // TODO: get rid of this /** get deallocation info for function by name (deprecated, use other alloc) */ const AllocFunc* getDeallocFuncInfo(const char name[]) const; // TODO: get rid of this /** get allocation id for function by name (deprecated, use other alloc) */ int allocId(const char name[]) const; // TODO: get rid of this /** get deallocation id for function by name (deprecated, use other alloc) */ int deallocId(const char name[]) const; static bool isCompliantValidationExpression(const char* p); /** is allocation type memory? */ static bool ismemory(const int id) { return ((id > 0) && ((id & 1) == 0)); } static bool ismemory(const AllocFunc* const func) { return func && (func->groupId > 0) && ((func->groupId & 1) == 0); } /** is allocation type resource? */ static bool isresource(const int id) { return ((id > 0) && ((id & 1) == 1)); } static bool isresource(const AllocFunc* const func) { return func && (func->groupId > 0) && ((func->groupId & 1) == 1); } bool formatstr_function(const Token* ftok) const; int formatstr_argno(const Token* ftok) const; bool formatstr_scan(const Token* ftok) const; bool formatstr_secure(const Token* ftok) const; struct NonOverlappingData { int ptr1Arg; int ptr2Arg; int sizeArg; int strlenArg; int countArg; }; const NonOverlappingData* getNonOverlappingData(const Token *ftok) const; struct WarnInfo { std::string message; Standards standards; Severity severity; }; const std::map<std::string, WarnInfo>& functionwarn() const; const WarnInfo* getWarnInfo(const Token* ftok) const; struct Function; // returns true if ftok is not a library function bool isNotLibraryFunction(const Token *ftok, const Function **func = nullptr) const; bool matchArguments(const Token *ftok, const std::string &functionName, const Function **func = nullptr) const; enum class UseRetValType : std::uint8_t { NONE, DEFAULT, ERROR_CODE }; UseRetValType getUseRetValType(const Token* ftok) const; const std::string& returnValue(const Token *ftok) const; const std::string& returnValueType(const Token *ftok) const; int returnValueContainer(const Token *ftok) const; std::vector<MathLib::bigint> unknownReturnValues(const Token *ftok) const; bool isnoreturn(const Token *ftok) const; bool isnotnoreturn(const Token *ftok) const; bool isScopeNoReturn(const Token *end, std::string *unknownFunc) const; class Container { public: Container() = default; enum class Action : std::uint8_t { RESIZE, CLEAR, PUSH, POP, FIND, FIND_CONST, INSERT, ERASE, APPEND, CHANGE_CONTENT, CHANGE, CHANGE_INTERNAL, NO_ACTION }; enum class Yield : std::uint8_t { AT_INDEX, ITEM, BUFFER, BUFFER_NT, START_ITERATOR, END_ITERATOR, ITERATOR, SIZE, EMPTY, NO_YIELD }; struct Function { Action action; Yield yield; std::string returnType; }; struct RangeItemRecordTypeItem { std::string name; int templateParameter; // TODO: use this }; std::string startPattern, startPattern2, endPattern, itEndPattern; std::map<std::string, Function> functions; int type_templateArgNo = -1; std::vector<RangeItemRecordTypeItem> rangeItemRecordType; int size_templateArgNo = -1; bool arrayLike_indexOp{}; bool stdStringLike{}; bool stdAssociativeLike{}; bool opLessAllowed = true; bool hasInitializerListConstructor{}; bool unstableErase{}; bool unstableInsert{}; bool view{}; Action getAction(const std::string& function) const { const std::map<std::string, Function>::const_iterator i = functions.find(function); if (i != functions.end()) return i->second.action; return Action::NO_ACTION; } Yield getYield(const std::string& function) const { const std::map<std::string, Function>::const_iterator i = functions.find(function); if (i != functions.end()) return i->second.yield; return Yield::NO_YIELD; } const std::string& getReturnType(const std::string& function) const { auto i = functions.find(function); return (i != functions.end()) ? i->second.returnType : emptyString; } static Yield yieldFrom(const std::string& yieldName); static Action actionFrom(const std::string& actionName); }; const std::unordered_map<std::string, Container>& containers() const; const Container* detectContainer(const Token* typeStart) const; const Container* detectIterator(const Token* typeStart) const; const Container* detectContainerOrIterator(const Token* typeStart, bool* isIterator = nullptr, bool withoutStd = false) const; struct ArgumentChecks { bool notbool{}; bool notnull{}; int notuninit = -1; bool formatstr{}; bool strz{}; bool optional{}; bool variadic{}; std::string valid; struct IteratorInfo { int container{}; bool it{}; bool first{}; bool last{}; }; IteratorInfo iteratorInfo; struct MinSize { enum class Type : std::uint8_t { NONE, STRLEN, ARGVALUE, SIZEOF, MUL, VALUE }; MinSize(Type t, int a) : type(t), arg(a) {} Type type; int arg; int arg2 = 0; long long value = 0; std::string baseType; }; std::vector<MinSize> minsizes; enum class Direction : std::uint8_t { DIR_IN, ///< Input to called function. Data is treated as read-only. DIR_OUT, ///< Output to caller. Data is passed by reference or address and is potentially written. DIR_INOUT, ///< Input to called function, and output to caller. Data is passed by reference or address and is potentially modified. DIR_UNKNOWN ///< direction not known / specified }; // argument directions up to ** indirect level (only one can be configured explicitly at the moment) std::array<Direction, 3> direction = { { Direction::DIR_UNKNOWN, Direction::DIR_UNKNOWN, Direction::DIR_UNKNOWN } }; }; struct Function { std::map<int, ArgumentChecks> argumentChecks; // argument nr => argument data bool use{}; bool leakignore{}; bool isconst{}; bool ispure{}; UseRetValType useretval = UseRetValType::NONE; bool ignore{}; // ignore functions/macros from a library (gtk, qt etc) bool formatstr{}; bool formatstr_scan{}; bool formatstr_secure{}; Container::Action containerAction = Container::Action::NO_ACTION; Container::Yield containerYield = Container::Yield::NO_YIELD; std::string returnType; }; const Function *getFunction(const Token *ftok) const; const std::unordered_map<std::string, Function>& functions() const; bool isUse(const std::string& functionName) const; bool isLeakIgnore(const std::string& functionName) const; bool isFunctionConst(const std::string& functionName, bool pure) const; bool isFunctionConst(const Token *ftok) const; bool isboolargbad(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg && arg->notbool; } bool isnullargbad(const Token *ftok, int argnr) const; bool isuninitargbad(const Token *ftok, int argnr, int indirect = 0, bool *hasIndirect=nullptr) const; bool isargformatstr(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg && arg->formatstr; } bool isargstrz(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg && arg->strz; } bool isIntArgValid(const Token *ftok, int argnr, MathLib::bigint argvalue) const; bool isFloatArgValid(const Token *ftok, int argnr, double argvalue) const; const std::string& validarg(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg ? arg->valid : emptyString; } const ArgumentChecks::IteratorInfo *getArgIteratorInfo(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg && arg->iteratorInfo.it ? &arg->iteratorInfo : nullptr; } bool hasminsize(const Token *ftok) const; const std::vector<ArgumentChecks::MinSize> *argminsizes(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); return arg ? &arg->minsizes : nullptr; } ArgumentChecks::Direction getArgDirection(const Token* ftok, int argnr, int indirect = 0) const; bool markupFile(const std::string &path) const; bool processMarkupAfterCode(const std::string &path) const; const std::set<std::string> &markupExtensions() const; bool reportErrors(const std::string &path) const; bool ignorefunction(const std::string &functionName) const; bool isexecutableblock(const std::string &file, const std::string &token) const; int blockstartoffset(const std::string &file) const; const std::string& blockstart(const std::string &file) const; const std::string& blockend(const std::string &file) const; bool iskeyword(const std::string &file, const std::string &keyword) const; bool isexporter(const std::string &prefix) const; bool isexportedprefix(const std::string &prefix, const std::string &token) const; bool isexportedsuffix(const std::string &prefix, const std::string &token) const; bool isimporter(const std::string& file, const std::string &importer) const; const Token* getContainerFromYield(const Token* tok, Container::Yield yield) const; const Token* getContainerFromAction(const Token* tok, Container::Action action) const; static bool isContainerYield(const Token* cond, Library::Container::Yield y, const std::string& fallback = emptyString); static Library::Container::Yield getContainerYield(const Token* cond); bool isreflection(const std::string &token) const; int reflectionArgument(const std::string &token) const; bool isentrypoint(const std::string &func) const; const std::set<std::string>& defines() const; // to provide some library defines struct SmartPointer { std::string name; bool unique = false; }; const std::unordered_map<std::string, SmartPointer>& smartPointers() const; bool isSmartPointer(const Token *tok) const; const SmartPointer* detectSmartPointer(const Token* tok, bool withoutStd = false) const; struct PodType { unsigned int size{}; char sign{}; enum class Type : std::uint8_t { NO, BOOL, CHAR, SHORT, INT, LONG, LONGLONG } stdtype = Type::NO; }; const PodType *podtype(const std::string &name) const; struct PlatformType { bool operator == (const PlatformType & type) const { return (mSigned == type.mSigned && mUnsigned == type.mUnsigned && mLong == type.mLong && mPointer == type.mPointer && mPtrPtr == type.mPtrPtr && mConstPtr == type.mConstPtr && mType == type.mType); } bool operator != (const PlatformType & type) const { return !(*this == type); } std::string mType; bool mSigned{}; bool mUnsigned{}; bool mLong{}; bool mPointer{}; bool mPtrPtr{}; bool mConstPtr{}; }; const PlatformType *platform_type(const std::string &name, const std::string & platform) const; /** * Get function name for function call */ std::string getFunctionName(const Token *ftok) const; /** Suppress/check a type */ enum class TypeCheck : std::uint8_t { def, check, suppress, checkFiniteLifetime, // (unusedvar) object has side effects, but immediate destruction is wrong }; TypeCheck getTypeCheck(std::string check, std::string typeName) const; bool hasAnyTypeCheck(const std::string& typeName) const; private: Error load(const tinyxml2::XMLDocument &doc); // load a <function> xml node Error loadFunction(const tinyxml2::XMLElement * node, const std::string &name, std::set<std::string> &unknown_elements); struct LibraryData; std::unique_ptr<LibraryData> mData; const ArgumentChecks * getarg(const Token *ftok, int argnr) const; std::string getFunctionName(const Token *ftok, bool &error) const; static const AllocFunc* getAllocDealloc(const std::map<std::string, AllocFunc> &data, const std::string &name) { const std::map<std::string, AllocFunc>::const_iterator it = data.find(name); return (it == data.end()) ? nullptr : &it->second; } enum DetectContainer : std::uint8_t { ContainerOnly, IteratorOnly, Both }; const Library::Container* detectContainerInternal(const Token* typeStart, DetectContainer detect, bool* isIterator = nullptr, bool withoutStd = false) const; }; CPPCHECKLIB const Library::Container * getLibraryContainer(const Token * tok); /// @} //--------------------------------------------------------------------------- #endif // libraryH
17,268
C++
.h
397
36.095718
161
0.646621
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,455
errortypes.h
danmar_cppcheck/lib/errortypes.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef errortypesH #define errortypesH //--------------------------------------------------------------------------- #include "config.h" #include <cstdint> #include <stdexcept> #include <list> #include <string> #include <utility> /// @addtogroup Core /// @{ class Token; /** @brief Simple container to be thrown when internal error is detected. */ struct CPPCHECKLIB InternalError { enum Type : std::uint8_t {AST, SYNTAX, UNKNOWN_MACRO, INTERNAL, LIMIT, INSTANTIATION}; InternalError(const Token *tok, std::string errorMsg, Type type = INTERNAL); InternalError(const Token *tok, std::string errorMsg, std::string details, Type type = INTERNAL); const Token *token; std::string errorMessage; std::string details; Type type; std::string id; }; class TerminateException : public std::runtime_error { public: TerminateException() : std::runtime_error("terminate") {} }; enum class Certainty : std::uint8_t { normal, inconclusive }; enum class Checks : std::uint8_t { unusedFunction, missingInclude, internalCheck }; /** @brief enum class for severity. Used when reporting errors. */ enum class Severity : std::uint8_t { /** * No severity (default value). */ none, /** * Programming error. * This indicates severe error like memory leak etc. * The error is certain. */ error, /** * Warning. * Used for dangerous coding style that can cause severe runtime errors. * For example: forgetting to initialize a member variable in a constructor. */ warning, /** * Style warning. * Used for general code cleanup recommendations. Fixing these * will not fix any bugs but will make the code easier to maintain. * For example: redundant code, unreachable code, etc. */ style, /** * Performance warning. * Not an error as is but suboptimal code and fixing it probably leads * to faster performance of the compiled code. */ performance, /** * Portability warning. * This warning indicates the code is not properly portable for * different platforms and bitnesses (32/64 bit). If the code is meant * to compile in different platforms and bitnesses these warnings * should be fixed. */ portability, /** * Checking information. * Information message about the checking (process) itself. These * messages inform about header files not found etc issues that are * not errors in the code but something user needs to know. */ information, /** * Debug message. * Debug-mode message useful for the developers. */ debug, /** * Internal message. * Message will not be shown to the user. * Tracking what checkers is executed, tracking suppressed critical errors, etc. */ internal }; CPPCHECKLIB std::string severityToString(Severity severity); CPPCHECKLIB Severity severityFromString(const std::string &severity); struct CWE { explicit CWE(unsigned short cweId) : id(cweId) {} unsigned short id; }; using ErrorPathItem = std::pair<const Token *, std::string>; using ErrorPath = std::list<ErrorPathItem>; /// @} //--------------------------------------------------------------------------- #endif // errortypesH
4,146
C++
.h
120
30.716667
101
0.663675
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,456
forwardanalyzer.h
danmar_cppcheck/lib/forwardanalyzer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef forwardanalyzerH #define forwardanalyzerH #include "analyzer.h" class ErrorLogger; class Settings; class Token; class TokenList; template<class T> class ValuePtr; Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings); Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings); #endif
1,499
C++
.h
33
37.545455
164
0.671918
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,457
tokenlist.h
danmar_cppcheck/lib/tokenlist.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef tokenlistH #define tokenlistH //--------------------------------------------------------------------------- #include "config.h" #include "standards.h" #include <cstddef> #include <iosfwd> #include <string> #include <vector> class Token; class TokenList; class Settings; namespace simplecpp { class TokenList; } /// @addtogroup Core /// @{ /** * @brief This struct stores pointers to the front and back tokens of the list this token is in. */ struct TokensFrontBack { explicit TokensFrontBack(const TokenList& list) : list(list) {} Token *front{}; Token* back{}; const TokenList& list; }; class CPPCHECKLIB TokenList { public: // TODO: pass settings as reference explicit TokenList(const Settings* settings); ~TokenList(); TokenList(const TokenList &) = delete; TokenList &operator=(const TokenList &) = delete; /** @return the source file path. e.g. "file.cpp" */ const std::string& getSourceFilePath() const; /** @return true if the code is C */ bool isC() const; /** @return true if the code is C++ */ bool isCPP() const; // TODO: get rid of this void setLang(Standards::Language lang, bool force = false); /** * Delete all tokens in given token list * @param tok token list to delete */ static void deleteTokens(Token *tok); void addtoken(const std::string& str, nonneg int lineno, nonneg int column, nonneg int fileno, bool split = false); void addtoken(const std::string& str, const Token *locationTok); void addtoken(const Token *tok, nonneg int lineno, nonneg int column, nonneg int fileno); void addtoken(const Token *tok, const Token *locationTok); void addtoken(const Token *tok); static void insertTokens(Token *dest, const Token *src, nonneg int n); /** * Copy tokens. * @param dest destination token where copied tokens will be inserted after * @param first first token to copy * @param last last token to copy * @param one_line true=>copy all tokens to the same line as dest. false=>copy all tokens to dest while keeping the 'line breaks' * @return new location of last token copied */ static Token *copyTokens(Token *dest, const Token *first, const Token *last, bool one_line = true); /** * Create tokens from code. * The code must be preprocessed first: * - multiline strings are not handled. * - UTF in the code are not handled. * - comments are not handled. * @param code input stream for code * @param file0 source file name */ bool createTokens(std::istream &code, const std::string& file0); bool createTokens(std::istream &code, Standards::Language lang); void createTokens(simplecpp::TokenList&& tokenList); /** Deallocate list */ void deallocateTokens(); /** append file name if seen the first time; return its index in any case */ int appendFileIfNew(std::string fileName); /** get first token of list */ const Token *front() const { return mTokensFrontBack.front; } // NOLINTNEXTLINE(readability-make-member-function-const) - do not allow usage of mutable pointer from const object Token *front() { return mTokensFrontBack.front; } /** get last token of list */ const Token *back() const { return mTokensFrontBack.back; } // NOLINTNEXTLINE(readability-make-member-function-const) - do not allow usage of mutable pointer from const object Token *back() { return mTokensFrontBack.back; } /** * Get filenames (the sourcefile + the files it include). * The first filename is the filename for the sourcefile * @return vector with filenames */ const std::vector<std::string>& getFiles() const { return mFiles; } std::string getOrigFile(const Token *tok) const; /** * get filename for given token * @param tok The given token * @return filename for the given token */ const std::string& file(const Token *tok) const; /** * Get file:line for a given token * @param tok given token * @return location for given token */ std::string fileLine(const Token *tok) const; /** * Calculates a hash of the token list used to compare multiple * token lists with each other as quickly as possible. */ std::size_t calculateHash() const; /** * Create abstract syntax tree. */ void createAst() const; /** * Check abstract syntax tree. * Throws InternalError on failure */ void validateAst(bool print) const; /** * Verify that the given token is an element of the tokenlist. * That method is implemented for debugging purposes. * @param[in] tok token to be checked * \return true if token was found in tokenlist, false else. In case of nullptr true is returned. */ bool validateToken(const Token* tok) const; /** * Convert platform dependent types to standard types. * 32 bits: size_t -> unsigned long * 64 bits: size_t -> unsigned long long */ void simplifyPlatformTypes(); /** * Collapse compound standard types into a single token. * unsigned long long int => long _isUnsigned=true,_isLong=true */ void simplifyStdType(); void clangSetOrigFiles(); bool isKeyword(const std::string &str) const; private: void determineCppC(); bool createTokensInternal(std::istream &code, const std::string& file0); /** Token list */ TokensFrontBack mTokensFrontBack; /** filenames for the tokenized source code (source + included) */ std::vector<std::string> mFiles; /** Original filenames for the tokenized source code (source + included) */ std::vector<std::string> mOrigFiles; /** settings */ const Settings* const mSettings{}; /** File is known to be C/C++ code */ Standards::Language mLang{Standards::Language::None}; }; /// @} const Token* isLambdaCaptureList(const Token* tok); const Token* findLambdaEndTokenWithoutAST(const Token* tok); //--------------------------------------------------------------------------- #endif // tokenlistH
7,046
C++
.h
185
33.4
133
0.664857
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,459
checkmemoryleak.h
danmar_cppcheck/lib/checkmemoryleak.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkmemoryleakH #define checkmemoryleakH //--------------------------------------------------------------------------- /** * @file * * %Check for memory leaks * * The checking is split up into three specialized classes. * - CheckMemoryLeakInFunction can detect when a function variable is allocated but not deallocated properly. * - CheckMemoryLeakInClass can detect when a class variable is allocated but not deallocated properly. * - CheckMemoryLeakStructMember checks allocation/deallocation of structs and struct members */ #include "check.h" #include "config.h" #include "tokenize.h" #include <cstdint> #include <list> #include <string> class Function; class Scope; class Settings; class Token; class Variable; class ErrorLogger; struct CWE; enum class Severity : std::uint8_t; /// @addtogroup Core /// @{ /** @brief Base class for memory leaks checking */ class CPPCHECKLIB CheckMemoryLeak { private: /** For access to the tokens */ const Tokenizer * const mTokenizer_; /** ErrorLogger used to report errors */ ErrorLogger * const mErrorLogger_; /** Enabled standards */ const Settings * const mSettings_; /** * Report error. Similar with the function Check::reportError * @param tok the token where the error occurs * @param severity the severity of the bug * @param id type of message * @param msg text * @param cwe cwe number */ void reportErr(const Token *tok, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const; /** * Report error. Similar with the function Check::reportError * @param callstack callstack of error * @param severity the severity of the bug * @param id type of message * @param msg text * @param cwe cwe number */ void reportErr(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const; public: CheckMemoryLeak() = delete; CheckMemoryLeak(const CheckMemoryLeak &) = delete; CheckMemoryLeak& operator=(const CheckMemoryLeak &) = delete; CheckMemoryLeak(const Tokenizer *t, ErrorLogger *e, const Settings *s) : mTokenizer_(t), mErrorLogger_(e), mSettings_(s) {} /** @brief What type of allocation are used.. the "Many" means that several types of allocation and deallocation are used */ enum AllocType : std::uint8_t { No, Malloc, New, NewArray, File, Fd, Pipe, OtherMem, OtherRes, Many }; void memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype) const; /** * @brief Get type of deallocation at given position * @param tok position * @param varid variable id * @return type of deallocation */ AllocType getDeallocationType(const Token *tok, nonneg int varid) const; /** * @brief Get type of allocation at given position */ AllocType getAllocationType(const Token *tok2, nonneg int varid, std::list<const Function*> *callstack = nullptr) const; /** * @brief Get type of reallocation at given position */ AllocType getReallocationType(const Token *tok2, nonneg int varid) const; /** * Check if token reopens a standard stream * @param tok token to check */ bool isReopenStandardStream(const Token *tok) const; /** * Check if token opens /dev/null * @param tok token to check */ bool isOpenDevNull(const Token *tok) const; /** * Report that there is a memory leak (new/malloc/etc) * @param tok token where memory is leaked * @param varname name of variable */ void memleakError(const Token *tok, const std::string &varname) const; /** * Report that there is a resource leak (fopen/popen/etc) * @param tok token where resource is leaked * @param varname name of variable */ void resourceLeakError(const Token *tok, const std::string &varname) const; void deallocuseError(const Token *tok, const std::string &varname) const; void mismatchAllocDealloc(const std::list<const Token *> &callstack, const std::string &varname) const; void memleakUponReallocFailureError(const Token *tok, const std::string &reallocfunction, const std::string &varname) const; /** What type of allocated memory does the given function return? */ AllocType functionReturnType(const Function* func, std::list<const Function*> *callstack = nullptr) const; }; /// @} /// @addtogroup Checks /// @{ /** * @brief %CheckMemoryLeakInFunction detects when a function variable is allocated but not deallocated properly. * * The checking is done by looking at each function variable separately. By repeating these 4 steps over and over: * -# locate a function variable * -# create a simple token list that describes the usage of the function variable. * -# simplify the token list. * -# finally, check if the simplified token list contain any leaks. */ class CPPCHECKLIB CheckMemoryLeakInFunction : public Check, public CheckMemoryLeak { friend class TestMemleakInFunction; public: /** @brief This constructor is used when registering this class */ CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {} private: /** @brief This constructor is used when running checks */ CheckMemoryLeakInFunction(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {} void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckMemoryLeakInFunction checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger); checkMemoryLeak.checkReallocUsage(); } /** * Checking for a memory leak caused by improper realloc usage. */ void checkReallocUsage(); /** Report all possible errors (for the --errorlist) */ void getErrorMessages(ErrorLogger *e, const Settings *settings) const override { CheckMemoryLeakInFunction c(nullptr, settings, e); c.memleakError(nullptr, "varname"); c.resourceLeakError(nullptr, "varname"); c.deallocuseError(nullptr, "varname"); const std::list<const Token *> callstack; c.mismatchAllocDealloc(callstack, "varname"); c.memleakUponReallocFailureError(nullptr, "realloc", "varname"); } /** * Get name of class (--doc) * @return name of class */ static std::string myName() { return "Memory leaks (function variables)"; } /** * Get class information (--doc) * @return Wiki formatted information about this class */ std::string classInfo() const override { return "Is there any allocated memory when a function goes out of scope\n"; } }; /** * @brief %Check class variables, variables that are allocated in the constructor should be deallocated in the destructor */ class CPPCHECKLIB CheckMemoryLeakInClass : public Check, private CheckMemoryLeak { friend class TestMemleakInClass; public: CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {} private: CheckMemoryLeakInClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {} void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { if (!tokenizer.isCPP()) return; CheckMemoryLeakInClass checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger); checkMemoryLeak.check(); } void check(); void variable(const Scope *scope, const Token *tokVarname); /** Public functions: possible double-allocation */ void checkPublicFunctions(const Scope *scope, const Token *classtok); void publicAllocationError(const Token *tok, const std::string &varname); void unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname); void getErrorMessages(ErrorLogger *e, const Settings *settings) const override { CheckMemoryLeakInClass c(nullptr, settings, e); c.publicAllocationError(nullptr, "varname"); c.unsafeClassError(nullptr, "class", "class::varname"); } static std::string myName() { return "Memory leaks (class variables)"; } std::string classInfo() const override { return "If the constructor allocate memory then the destructor must deallocate it.\n"; } }; /** @brief detect simple memory leaks for struct members */ class CPPCHECKLIB CheckMemoryLeakStructMember : public Check, private CheckMemoryLeak { friend class TestMemleakStructMember; public: CheckMemoryLeakStructMember() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {} private: CheckMemoryLeakStructMember(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {} void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckMemoryLeakStructMember checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger); checkMemoryLeak.check(); } void check(); /** Is local variable allocated with malloc? */ bool isMalloc(const Variable *variable) const; void checkStructVariable(const Variable* variable) const; void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) const override {} static std::string myName() { return "Memory leaks (struct members)"; } std::string classInfo() const override { return "Don't forget to deallocate struct members\n"; } }; /** @brief detect simple memory leaks (address not taken) */ class CPPCHECKLIB CheckMemoryLeakNoVar : public Check, private CheckMemoryLeak { friend class TestMemleakNoVar; public: CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {} private: CheckMemoryLeakNoVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {} void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckMemoryLeakNoVar checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger); checkMemoryLeak.check(); } void check(); /** * @brief %Check if an input argument to a function is the return value of an allocation function * like malloc(), and the function does not release it. * @param scope The scope of the function to check. */ void checkForUnreleasedInputArgument(const Scope *scope); /** * @brief %Check if a call to an allocation function like malloc() is made and its return value is not assigned. * @param scope The scope of the function to check. */ void checkForUnusedReturnValue(const Scope *scope); /** * @brief %Check if an exception could cause a leak in an argument constructed with shared_ptr/unique_ptr. * @param scope The scope of the function to check. */ void checkForUnsafeArgAlloc(const Scope *scope); void functionCallLeak(const Token *loc, const std::string &alloc, const std::string &functionCall); void returnValueNotUsedError(const Token* tok, const std::string &alloc); void unsafeArgAllocError(const Token *tok, const std::string &funcName, const std::string &ptrType, const std::string &objType); void getErrorMessages(ErrorLogger *e, const Settings *settings) const override { CheckMemoryLeakNoVar c(nullptr, settings, e); c.functionCallLeak(nullptr, "funcName", "funcName"); c.returnValueNotUsedError(nullptr, "funcName"); c.unsafeArgAllocError(nullptr, "funcName", "shared_ptr", "int"); } static std::string myName() { return "Memory leaks (address not taken)"; } std::string classInfo() const override { return "Not taking the address to allocated memory\n"; } }; /// @} //--------------------------------------------------------------------------- #endif // checkmemoryleakH
13,258
C++
.h
286
41.465035
150
0.707904
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,460
sourcelocation.h
danmar_cppcheck/lib/sourcelocation.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef sourcelocationH #define sourcelocationH #include "config.h" #ifdef __CPPCHECK__ #define CPPCHECK_HAS_SOURCE_LOCATION 0 #define CPPCHECK_HAS_SOURCE_LOCATION_TS 0 #define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0 #else #if __has_include(<source_location>) && __cplusplus >= 202003L #define CPPCHECK_HAS_SOURCE_LOCATION 1 #else #define CPPCHECK_HAS_SOURCE_LOCATION 0 #endif #if __has_include(<experimental/source_location>) && __cplusplus >= 201402L #define CPPCHECK_HAS_SOURCE_LOCATION_TS 1 #else #define CPPCHECK_HAS_SOURCE_LOCATION_TS 0 #endif #if __has_builtin(__builtin_FILE) #define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 1 #if !__has_builtin(__builtin_COLUMN) #define __builtin_COLUMN() 0 #endif #else #define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0 #endif #endif #if CPPCHECK_HAS_SOURCE_LOCATION #include <source_location> using SourceLocation = std::source_location; #elif CPPCHECK_HAS_SOURCE_LOCATION_TS #include <experimental/source_location> using SourceLocation = std::experimental::source_location; #else #include <cstdint> struct SourceLocation { #if CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS static SourceLocation current(std::uint_least32_t line = __builtin_LINE(), std::uint_least32_t column = __builtin_COLUMN(), const char* file_name = __builtin_FILE(), const char* function_name = __builtin_FUNCTION()) { SourceLocation result{}; result.m_line = line; result.m_column = column; result.m_file_name = file_name; result.m_function_name = function_name; return result; } #else static SourceLocation current() { return SourceLocation(); } #endif std::uint_least32_t m_line = 0; std::uint_least32_t m_column = 0; const char* m_file_name = ""; const char* m_function_name = ""; std::uint_least32_t line() const { return m_line; } std::uint_least32_t column() const { return m_column; } const char* file_name() const { return m_file_name; } const char* function_name() const { return m_function_name; } }; #endif #endif
2,967
C++
.h
90
28.833333
83
0.698153
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,461
checkother.h
danmar_cppcheck/lib/checkother.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkotherH #define checkotherH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "errortypes.h" #include "tokenize.h" #include <set> #include <string> #include <vector> namespace ValueFlow { class Value; } class Settings; class Token; class Function; class Variable; class ErrorLogger; /// @addtogroup Checks /// @{ /** @brief Various small checks */ class CPPCHECKLIB CheckOther : public Check { friend class TestCharVar; friend class TestIncompleteStatement; friend class TestOther; public: /** @brief This constructor is used when registering the CheckClass */ CheckOther() : Check(myName()) {} /** Is expression a comparison that checks if a nonzero (unsigned/pointer) expression is less than zero? */ static bool comparisonNonZeroExpressionLessThanZero(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr, bool suppress = false); /** Is expression a comparison that checks if a nonzero (unsigned/pointer) expression is positive? */ static bool testIfNonZeroExpressionIsPositive(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr); private: /** @brief This constructor is used when running checks. */ CheckOther(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} /** @brief Run checks against the normal token list */ void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckOther checkOther(&tokenizer, &tokenizer.getSettings(), errorLogger); // Checks checkOther.warningOldStylePointerCast(); checkOther.suspiciousFloatingPointCast(); checkOther.invalidPointerCast(); checkOther.checkCharVariable(); checkOther.redundantBitwiseOperationInSwitchError(); checkOther.checkSuspiciousCaseInSwitch(); checkOther.checkDuplicateBranch(); checkOther.checkDuplicateExpression(); checkOther.checkRedundantAssignment(); checkOther.checkUnreachableCode(); checkOther.checkSuspiciousSemicolon(); checkOther.checkVariableScope(); checkOther.checkSignOfUnsignedVariable(); // don't ignore casts (#3574) checkOther.checkIncompleteArrayFill(); checkOther.checkVarFuncNullUB(); checkOther.checkNanInArithmeticExpression(); checkOther.checkCommaSeparatedReturn(); checkOther.checkRedundantPointerOp(); checkOther.checkZeroDivision(); checkOther.checkNegativeBitwiseShift(); checkOther.checkInterlockedDecrement(); checkOther.checkUnusedLabel(); checkOther.checkEvaluationOrder(); checkOther.checkFuncArgNamesDifferent(); checkOther.checkShadowVariables(); checkOther.checkKnownArgument(); checkOther.checkKnownPointerToBool(); checkOther.checkComparePointers(); checkOther.checkIncompleteStatement(); checkOther.checkRedundantCopy(); checkOther.clarifyCalculation(); checkOther.checkPassByReference(); checkOther.checkConstVariable(); checkOther.checkConstPointer(); checkOther.checkComparisonFunctionIsAlwaysTrueOrFalse(); checkOther.checkInvalidFree(); checkOther.clarifyStatement(); checkOther.checkCastIntToCharAndBack(); checkOther.checkMisusedScopedObject(); checkOther.checkAccessOfMovedVariable(); checkOther.checkModuloOfOne(); checkOther.checkOverlappingWrite(); } /** @brief Clarify calculation for ".. a * b ? .." */ void clarifyCalculation(); /** @brief Suspicious statement like '*A++;' */ void clarifyStatement(); /** @brief Are there C-style pointer casts in a c++ file? */ void warningOldStylePointerCast(); void suspiciousFloatingPointCast(); /** @brief Check for pointer casts to a type with an incompatible binary data representation */ void invalidPointerCast(); /** @brief %Check scope of variables */ void checkVariableScope(); bool checkInnerScope(const Token *tok, const Variable* var, bool& used) const; /** @brief %Check for comma separated statements in return */ void checkCommaSeparatedReturn(); /** @brief %Check for function parameters that should be passed by reference */ void checkPassByReference(); void checkConstVariable(); void checkConstPointer(); /** @brief Using char variable as array index / as operand in bit operation */ void checkCharVariable(); /** @brief Incomplete statement. A statement that only contains a constant or variable */ void checkIncompleteStatement(); /** @brief %Check zero division*/ void checkZeroDivision(); /** @brief Check for NaN (not-a-number) in an arithmetic expression */ void checkNanInArithmeticExpression(); /** @brief copying to memory or assigning to a variable twice */ void checkRedundantAssignment(); /** @brief %Check for redundant bitwise operation in switch statement*/ void redundantBitwiseOperationInSwitchError(); /** @brief %Check for code like 'case A||B:'*/ void checkSuspiciousCaseInSwitch(); /** @brief %Check for objects that are destroyed immediately */ void checkMisusedScopedObject(); /** @brief %Check for suspicious code where if and else branch are the same (e.g "if (a) b = true; else b = true;") */ void checkDuplicateBranch(); /** @brief %Check for suspicious code with the same expression on both sides of operator (e.g "if (a && a)") */ void checkDuplicateExpression(); /** @brief %Check for code that gets never executed, such as duplicate break statements */ void checkUnreachableCode(); /** @brief %Check for testing sign of unsigned variable */ void checkSignOfUnsignedVariable(); /** @brief %Check for suspicious use of semicolon */ void checkSuspiciousSemicolon(); /** @brief %Check for free() operations on invalid memory locations */ void checkInvalidFree(); void invalidFreeError(const Token *tok, const std::string &allocation, bool inconclusive); /** @brief %Check for code creating redundant copies */ void checkRedundantCopy(); /** @brief %Check for bitwise shift with negative right operand */ void checkNegativeBitwiseShift(); /** @brief %Check for buffers that are filled incompletely with memset and similar functions */ void checkIncompleteArrayFill(); /** @brief %Check that variadic function calls don't use NULL. If NULL is \#defined as 0 and the function expects a pointer, the behaviour is undefined. */ void checkVarFuncNullUB(); /** @brief %Check to avoid casting a return value to unsigned char and then back to integer type. */ void checkCastIntToCharAndBack(); /** @brief %Check for using of comparison functions evaluating always to true or false. */ void checkComparisonFunctionIsAlwaysTrueOrFalse(); /** @brief %Check for redundant pointer operations */ void checkRedundantPointerOp(); /** @brief %Check for race condition with non-interlocked access after InterlockedDecrement() */ void checkInterlockedDecrement(); /** @brief %Check for unused labels */ void checkUnusedLabel(); /** @brief %Check for expression that depends on order of evaluation of side effects */ void checkEvaluationOrder(); /** @brief %Check for access of moved or forwarded variable */ void checkAccessOfMovedVariable(); /** @brief %Check if function declaration and definition argument names different */ void checkFuncArgNamesDifferent(); /** @brief %Check for shadow variables. Less noisy than gcc/clang -Wshadow. */ void checkShadowVariables(); void checkKnownArgument(); void checkKnownPointerToBool(); void checkComparePointers(); void checkModuloOfOne(); void checkOverlappingWrite(); void overlappingWriteUnion(const Token *tok); void overlappingWriteFunction(const Token *tok); // Error messages.. void checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, bool result); void checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName); void clarifyCalculationError(const Token *tok, const std::string &op); void clarifyStatementError(const Token* tok); void cstyleCastError(const Token *tok, bool isPtr = true); void suspiciousFloatingPointCastError(const Token *tok); void invalidPointerCastError(const Token* tok, const std::string& from, const std::string& to, bool inconclusive, bool toIsInt); void passedByValueError(const Variable* var, bool inconclusive, bool isRangeBasedFor = false); void constVariableError(const Variable *var, const Function *function); void constStatementError(const Token *tok, const std::string &type, bool inconclusive); void signedCharArrayIndexError(const Token *tok); void unknownSignCharArrayIndexError(const Token *tok); void charBitOpError(const Token *tok); void variableScopeError(const Token *tok, const std::string &varname); void zerodivError(const Token *tok, const ValueFlow::Value *value); void nanInArithmeticExpressionError(const Token *tok); void redundantAssignmentError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive); void redundantInitializationError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive); void redundantAssignmentInSwitchError(const Token *tok1, const Token *tok2, const std::string &var); void redundantAssignmentSameValueError(const Token* tok, const ValueFlow::Value* val, const std::string& var); void redundantCopyError(const Token *tok1, const Token* tok2, const std::string& var); void redundantBitwiseOperationInSwitchError(const Token *tok, const std::string &varname); void suspiciousCaseInSwitchError(const Token* tok, const std::string& operatorString); void selfAssignmentError(const Token *tok, const std::string &varname); void misusedScopeObjectError(const Token *tok, const std::string &varname, bool isAssignment = false); void duplicateBranchError(const Token *tok1, const Token *tok2, ErrorPath errors); void duplicateAssignExpressionError(const Token *tok1, const Token *tok2, bool inconclusive); void oppositeExpressionError(const Token *opTok, ErrorPath errors); void duplicateExpressionError(const Token *tok1, const Token *tok2, const Token *opTok, ErrorPath errors, bool hasMultipleExpr = false); void duplicateValueTernaryError(const Token *tok); void duplicateExpressionTernaryError(const Token *tok, ErrorPath errors); void duplicateBreakError(const Token *tok, bool inconclusive); void unreachableCodeError(const Token* tok, const Token* noreturn, bool inconclusive); void redundantContinueError(const Token* tok); void unsignedLessThanZeroError(const Token *tok, const ValueFlow::Value *v, const std::string &varname); void pointerLessThanZeroError(const Token *tok, const ValueFlow::Value *v); void unsignedPositiveError(const Token *tok, const ValueFlow::Value *v, const std::string &varname); void pointerPositiveError(const Token *tok, const ValueFlow::Value *v); void suspiciousSemicolonError(const Token *tok); void negativeBitwiseShiftError(const Token *tok, int op); void redundantCopyError(const Token *tok, const std::string &varname); void incompleteArrayFillError(const Token* tok, const std::string& buffer, const std::string& function, bool boolean); void varFuncNullUBError(const Token *tok); void commaSeparatedReturnError(const Token *tok); void redundantPointerOpError(const Token* tok, const std::string& varname, bool inconclusive, bool addressOfDeref); void raceAfterInterlockedDecrementError(const Token* tok); void unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef); void unknownEvaluationOrder(const Token* tok, bool isUnspecifiedBehavior = false); void accessMovedError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive); void funcArgNamesDifferent(const std::string & functionName, nonneg int index, const Token* declaration, const Token* definition); void funcArgOrderDifferent(const std::string & functionName, const Token * declaration, const Token * definition, const std::vector<const Token*> & declarations, const std::vector<const Token*> & definitions); void shadowError(const Token *var, const Token *shadowed, const std::string& type); void knownArgumentError(const Token *tok, const Token *ftok, const ValueFlow::Value *value, const std::string &varexpr, bool isVariableExpressionHidden); void knownPointerToBoolError(const Token* tok, const ValueFlow::Value* value); void comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2); void checkModuloOfOneError(const Token *tok); void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckOther c(nullptr, settings, errorLogger); // error c.zerodivError(nullptr, nullptr); c.misusedScopeObjectError(nullptr, "varname"); c.invalidPointerCastError(nullptr, "float *", "double *", false, false); c.negativeBitwiseShiftError(nullptr, 1); c.negativeBitwiseShiftError(nullptr, 2); c.raceAfterInterlockedDecrementError(nullptr); c.invalidFreeError(nullptr, "malloc", false); c.overlappingWriteUnion(nullptr); c.overlappingWriteFunction(nullptr); //performance c.redundantCopyError(nullptr, "varname"); c.redundantCopyError(nullptr, nullptr, "var"); // style/warning c.checkComparisonFunctionIsAlwaysTrueOrFalseError(nullptr, "isless","varName",false); c.checkCastIntToCharAndBackError(nullptr, "func_name"); c.cstyleCastError(nullptr); c.suspiciousFloatingPointCastError(nullptr); c.passedByValueError(nullptr, false); c.constVariableError(nullptr, nullptr); c.constStatementError(nullptr, "type", false); c.signedCharArrayIndexError(nullptr); c.unknownSignCharArrayIndexError(nullptr); c.charBitOpError(nullptr); c.variableScopeError(nullptr, "varname"); c.redundantAssignmentInSwitchError(nullptr, nullptr, "var"); c.suspiciousCaseInSwitchError(nullptr, "||"); c.selfAssignmentError(nullptr, "varname"); c.clarifyCalculationError(nullptr, "+"); c.clarifyStatementError(nullptr); c.duplicateBranchError(nullptr, nullptr, ErrorPath{}); c.duplicateAssignExpressionError(nullptr, nullptr, true); c.oppositeExpressionError(nullptr, ErrorPath{}); c.duplicateExpressionError(nullptr, nullptr, nullptr, ErrorPath{}); c.duplicateValueTernaryError(nullptr); c.duplicateExpressionTernaryError(nullptr, ErrorPath{}); c.duplicateBreakError(nullptr, false); c.unreachableCodeError(nullptr, nullptr, false); c.unsignedLessThanZeroError(nullptr, nullptr, "varname"); c.unsignedPositiveError(nullptr, nullptr, "varname"); c.pointerLessThanZeroError(nullptr, nullptr); c.pointerPositiveError(nullptr, nullptr); c.suspiciousSemicolonError(nullptr); c.incompleteArrayFillError(nullptr, "buffer", "memset", false); c.varFuncNullUBError(nullptr); c.nanInArithmeticExpressionError(nullptr); c.commaSeparatedReturnError(nullptr); c.redundantPointerOpError(nullptr, "varname", false, /*addressOfDeref*/ true); c.unusedLabelError(nullptr, false, false); c.unusedLabelError(nullptr, false, true); c.unusedLabelError(nullptr, true, false); c.unusedLabelError(nullptr, true, true); c.unknownEvaluationOrder(nullptr); c.accessMovedError(nullptr, "v", nullptr, false); c.funcArgNamesDifferent("function", 1, nullptr, nullptr); c.redundantBitwiseOperationInSwitchError(nullptr, "varname"); c.shadowError(nullptr, nullptr, "variable"); c.shadowError(nullptr, nullptr, "function"); c.shadowError(nullptr, nullptr, "argument"); c.knownArgumentError(nullptr, nullptr, nullptr, "x", false); c.knownPointerToBoolError(nullptr, nullptr); c.comparePointersError(nullptr, nullptr, nullptr); c.redundantAssignmentError(nullptr, nullptr, "var", false); c.redundantInitializationError(nullptr, nullptr, "var", false); const std::vector<const Token *> nullvec; c.funcArgOrderDifferent("function", nullptr, nullptr, nullvec, nullvec); c.checkModuloOfOneError(nullptr); } static std::string myName() { return "Other"; } std::string classInfo() const override { return "Other checks\n" // error "- division with zero\n" "- scoped object destroyed immediately after construction\n" "- assignment in an assert statement\n" "- free() or delete of an invalid memory location\n" "- bitwise operation with negative right operand\n" "- cast the return values of getc(),fgetc() and getchar() to character and compare it to EOF\n" "- race condition with non-interlocked access after InterlockedDecrement() call\n" "- expression 'x = x++;' depends on order of evaluation of side effects\n" "- overlapping write of union\n" // warning "- either division by zero or useless condition\n" "- access of moved or forwarded variable.\n" // performance "- redundant data copying for const variable\n" "- subsequent assignment or copying to a variable or buffer\n" "- passing parameter by value\n" // portability "- Passing NULL pointer to function with variable number of arguments leads to UB.\n" // style "- C-style pointer cast in C++ code\n" "- casting between incompatible pointer types\n" "- [Incomplete statement](IncompleteStatement)\n" "- [check how signed char variables are used](CharVar)\n" "- variable scope can be limited\n" "- unusual pointer arithmetic. For example: \"abc\" + 'd'\n" "- redundant assignment, increment, or bitwise operation in a switch statement\n" "- redundant strcpy in a switch statement\n" "- Suspicious case labels in switch()\n" "- assignment of a variable to itself\n" "- Comparison of values leading always to true or false\n" "- Clarify calculation with parentheses\n" "- suspicious comparison of '\\0' with a char\\* variable\n" "- duplicate break statement\n" "- unreachable code\n" "- testing if unsigned variable is negative/positive\n" "- Suspicious use of ; at the end of 'if/for/while' statement.\n" "- Array filled incompletely using memset/memcpy/memmove.\n" "- NaN (not a number) value used in arithmetic expression.\n" "- comma in return statement (the comma can easily be misread as a semicolon).\n" "- prefer erfc, expm1 or log1p to avoid loss of precision.\n" "- identical code in both branches of if/else or ternary operator.\n" "- redundant pointer operation on pointer like &\\*some_ptr.\n" "- find unused 'goto' labels.\n" "- function declaration and definition argument names different.\n" "- function declaration and definition argument order different.\n" "- shadow variable.\n" "- variable can be declared const.\n" "- calculating modulo of one.\n" "- known function argument, suspicious calculation.\n"; } bool diag(const Token* tok) { return !mRedundantAssignmentDiag.emplace(tok).second; } std::set<const Token*> mRedundantAssignmentDiag; }; /// @} //--------------------------------------------------------------------------- #endif // checkotherH
21,430
C++
.h
372
50.129032
213
0.703564
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,462
errorlogger.h
danmar_cppcheck/lib/errorlogger.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef errorloggerH #define errorloggerH //--------------------------------------------------------------------------- #include "config.h" #include "errortypes.h" #include "color.h" #include <cstddef> #include <list> #include <set> #include <string> #include <utility> #include <vector> class Token; class TokenList; namespace tinyxml2 { class XMLElement; } /// @addtogroup Core /// @{ /** * Wrapper for error messages, provided by reportErr() */ class CPPCHECKLIB 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 CPPCHECKLIB WARN_UNUSED FileLocation { public: FileLocation(const std::string &file, int line, unsigned int column) : fileIndex(0), line(line), column(column), mOrigFileName(file), mFileName(file) {} FileLocation(const std::string &file, std::string info, int line, unsigned int column) : fileIndex(0), line(line), column(column), mOrigFileName(file), mFileName(file), mInfo(std::move(info)) {} FileLocation(const Token* tok, const TokenList* tokenList); FileLocation(const Token* tok, std::string info, const TokenList* tokenList); /** * Return the filename. * @param convert If true convert path to native separators. * @return filename. */ std::string getfile(bool convert = true) const; /** * Filename with the whole path (no --rp) * @param convert If true convert path to native separators. * @return filename. */ std::string getOrigFile(bool convert = true) const; /** * Set the filename. * @param file Filename to set. */ void setfile(std::string file); /** * @return the location as a string. Format: [file:line] */ std::string stringify() const; unsigned int fileIndex; int line; // negative value means "no line" unsigned int column; const std::string& getinfo() const { return mInfo; } private: std::string mOrigFileName; std::string mFileName; std::string mInfo; }; ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, Certainty certainty); ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, const CWE &cwe, Certainty certainty); ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, Certainty certainty); ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, const CWE &cwe, Certainty certainty); ErrorMessage(const ErrorPath &errorPath, const TokenList *tokenList, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty); ErrorMessage(); explicit ErrorMessage(const tinyxml2::XMLElement * errmsg); /** * Format the error message in XML format */ std::string toXML() const; static std::string getXMLHeader(std::string productName, int xmlVersion = 2); static std::string getXMLFooter(int xmlVersion); /** * Format the error message into a string. * @param verbose use verbose message * @param templateFormat Empty string to use default output format * or template to be used. E.g. "{file}:{line},{severity},{id},{message}" * @param templateLocation Format Empty string to use default output format * or template to be used. E.g. "{file}:{line},{info}" * @return formatted string */ std::string toString(bool verbose, const std::string &templateFormat = emptyString, const std::string &templateLocation = emptyString) const; std::string serialize() const; void deserialize(const std::string &data); std::list<FileLocation> callStack; std::string id; /** For GUI rechecking; source file (not header) */ std::string file0; Severity severity; CWE cwe; Certainty certainty; /** remark from REMARK comment */ std::string remark; /** Warning hash */ std::size_t hash; /** set short and verbose messages */ void setmsg(const std::string &msg); /** Short message (single line short message) */ const std::string &shortMessage() const { return mShortMessage; } /** Verbose message (may be the same as the short message) */ // cppcheck-suppress unusedFunction - used by GUI only const std::string &verboseMessage() const { return mVerboseMessage; } /** Symbol names */ const std::string &symbolNames() const { return mSymbolNames; } static ErrorMessage fromInternalError(const InternalError &internalError, const TokenList *tokenList, const std::string &filename, const std::string& msg = emptyString); private: static std::string fixInvalidChars(const std::string& raw); /** Short message */ std::string mShortMessage; /** Verbose message */ std::string mVerboseMessage; /** symbol names */ std::string mSymbolNames; }; /** * @brief This is an interface, which the class responsible of error logging * should implement. */ class CPPCHECKLIB ErrorLogger { public: ErrorLogger() = default; virtual ~ErrorLogger() = default; /** * Information about progress is directed here. * Override this to receive the progress messages. * * @param outmsg Message to show e.g. "Checking main.cpp..." */ virtual void reportOut(const std::string &outmsg, Color c = Color::Reset) = 0; /** * Information about found errors and warnings is directed * here. Override this to receive the errormessages. * * @param msg Location and other information about the found error. */ virtual void reportErr(const ErrorMessage &msg) = 0; /** * Report progress to client * @param filename main file that is checked * @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 std::size_t value) { (void)filename; (void)stage; (void)value; } static std::string callStackToString(const std::list<ErrorMessage::FileLocation> &callStack); /** * Convert XML-sensitive characters into XML entities * @param str The input string containing XML-sensitive characters * @return The output string containing XML entities */ static std::string toxml(const std::string &str); static std::string plistHeader(const std::string &version, const std::vector<std::string> &files); static std::string plistData(const ErrorMessage &msg); static const char *plistFooter() { return " </array>\r\n" "</dict>\r\n" "</plist>"; } static bool isCriticalErrorId(const std::string& id) { return mCriticalErrorIds.count(id) != 0; } private: static const std::set<std::string> mCriticalErrorIds; }; /** Replace substring. Example replaceStr("1,NR,3", "NR", "2") => "1,2,3" */ std::string replaceStr(std::string s, const std::string &from, const std::string &to); /** replaces the static parts of the location template **/ CPPCHECKLIB void substituteTemplateFormatStatic(std::string& templateFormat); /** replaces the static parts of the location template **/ CPPCHECKLIB void substituteTemplateLocationStatic(std::string& templateLocation); /// @} //--------------------------------------------------------------------------- #endif // errorloggerH
9,287
C++
.h
239
31.857741
173
0.630667
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,463
analyzerinfo.h
danmar_cppcheck/lib/analyzerinfo.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef analyzerinfoH #define analyzerinfoH //--------------------------------------------------------------------------- #include "config.h" #include <cstddef> #include <fstream> #include <list> #include <string> class ErrorMessage; struct FileSettings; /// @addtogroup Core /// @{ /** * @brief Analyzer information * * Store various analysis information: * - checksum * - error messages * - whole program analysis data * * The information can be used for various purposes. It allows: * - 'make' - only analyze TUs that are changed and generate full report * - should be possible to add distributed analysis later * - multi-threaded whole program analysis */ class CPPCHECKLIB AnalyzerInformation { public: ~AnalyzerInformation(); static void writeFilesTxt(const std::string &buildDir, const std::list<std::string> &sourcefiles, const std::string &userDefines, const std::list<FileSettings> &fileSettings); /** Close current TU.analyzerinfo file */ void close(); bool analyzeFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg, std::size_t hash, std::list<ErrorMessage> &errors); void reportErr(const ErrorMessage &msg); void setFileInfo(const std::string &check, const std::string &fileInfo); static std::string getAnalyzerInfoFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg); protected: static std::string getAnalyzerInfoFileFromFilesTxt(std::istream& filesTxt, const std::string &sourcefile, const std::string &cfg); private: std::ofstream mOutputStream; std::string mAnalyzerInfoFile; }; /// @} //--------------------------------------------------------------------------- #endif // analyzerinfoH
2,583
C++
.h
62
39.354839
179
0.681927
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,464
vf_bailout.h
danmar_cppcheck/lib/vf_bailout.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfBailoutH #define vfBailoutH #include <string> class TokenList; class ErrorLogger; class Token; namespace ValueFlow { void bailoutInternal(const std::string& type, const TokenList &tokenlist, ErrorLogger &errorLogger, const Token *tok, const std::string &what, const std::string &file, int line, std::string function); } #define bailout2(type, tokenlist, errorLogger, tok, what) ValueFlow::bailoutInternal((type), (tokenlist), (errorLogger), (tok), (what), __FILE__, __LINE__, __func__) #define bailout(tokenlist, errorLogger, tok, what) bailout2("valueFlowBailout", (tokenlist), (errorLogger), (tok), (what)) #define bailoutIncompleteVar(tokenlist, errorLogger, tok, what) ValueFlow::bailoutInternal("valueFlowBailoutIncompleteVar", (tokenlist), (errorLogger), (tok), (what), "", 0, __func__) #endif // vfBailoutH
1,598
C++
.h
31
49.645161
204
0.748557
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,465
vf_enumvalue.h
danmar_cppcheck/lib/vf_enumvalue.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfEnumValueH #define vfEnumValueH class SymbolDatabase; class Settings; namespace ValueFlow { void analyzeEnumValue(SymbolDatabase & symboldatabase, const Settings & settings); } #endif // vfEnumValueH
980
C++
.h
26
35.769231
86
0.763158
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,466
vf_switchvariable.h
danmar_cppcheck/lib/vf_switchvariable.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfSwitchVariableH #define vfSwitchVariableH class TokenList; class SymbolDatabase; class ErrorLogger; class Settings; namespace ValueFlow { void analyzeSwitchVariable(const TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings); } #endif // vfSwitchVariableH
1,094
C++
.h
28
37.214286
149
0.776836
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,467
vf_reverse.h
danmar_cppcheck/lib/vf_reverse.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfReverseeH #define vfReverseeH #include "sourcelocation.h" #include <list> class TokenList; class ErrorLogger; class Settings; class Token; namespace ValueFlow { class Value; } namespace ValueFlow { void valueFlowReverse(Token* tok, const Token* const endToken, const Token* const varToken, std::list<ValueFlow::Value> values, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings, SourceLocation loc = SourceLocation::current()); } #endif // vfReverseeH
1,448
C++
.h
40
29.875
74
0.670949
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,468
infer.h
danmar_cppcheck/lib/infer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef inferH #define inferH #include "config.h" #include "mathlib.h" #include "vfvalue.h" #include <list> #include <string> #include <vector> class Token; template<class T> class ValuePtr; struct InferModel { virtual bool match(const ValueFlow::Value& value) const = 0; virtual ValueFlow::Value yield(MathLib::bigint value) const = 0; virtual ~InferModel() = default; InferModel(const InferModel&) = default; protected: InferModel() = default; }; std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, std::list<ValueFlow::Value> lhsValues, std::list<ValueFlow::Value> rhsValues); std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, MathLib::bigint lhs, std::list<ValueFlow::Value> rhsValues); std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, std::list<ValueFlow::Value> lhsValues, MathLib::bigint rhs); CPPCHECKLIB std::vector<MathLib::bigint> getMinValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values); std::vector<MathLib::bigint> getMaxValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values); ValuePtr<InferModel> makeIntegralInferModel(); ValueFlow::Value inferCondition(const std::string& op, const Token* varTok, MathLib::bigint val); #endif
2,454
C++
.h
52
39.038462
131
0.658996
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,469
checkunusedvar.h
danmar_cppcheck/lib/checkunusedvar.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkunusedvarH #define checkunusedvarH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "tokenize.h" #include <list> #include <map> #include <string> class ErrorLogger; class Scope; class Settings; class Token; class Type; class Variables; class Variable; class Function; /// @addtogroup Checks /// @{ /** @brief Various small checks */ class CPPCHECKLIB CheckUnusedVar : public Check { friend class TestUnusedVar; public: /** @brief This constructor is used when registering the CheckClass */ CheckUnusedVar() : Check(myName()) {} private: /** @brief This constructor is used when running checks. */ CheckUnusedVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} /** @brief Run checks against the normal token list */ void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { CheckUnusedVar checkUnusedVar(&tokenizer, &tokenizer.getSettings(), errorLogger); // Coding style checks checkUnusedVar.checkStructMemberUsage(); checkUnusedVar.checkFunctionVariableUsage(); } /** @brief %Check for unused function variables */ void checkFunctionVariableUsage_iterateScopes(const Scope* scope, Variables& variables); void checkFunctionVariableUsage(); /** @brief %Check that all struct members are used */ void checkStructMemberUsage(); bool isRecordTypeWithoutSideEffects(const Type* type); bool isVariableWithoutSideEffects(const Variable& var, const Type* type = nullptr); bool isEmptyType(const Type* type); bool isFunctionWithoutSideEffects(const Function& func, const Token* functionUsageToken, std::list<const Function*> checkedFuncs); // Error messages.. void unusedStructMemberError(const Token *tok, const std::string &structname, const std::string &varname, const std::string& prefix = "struct"); void unusedVariableError(const Token *tok, const std::string &varname); void allocatedButUnusedVariableError(const Token *tok, const std::string &varname); void unreadVariableError(const Token *tok, const std::string &varname, bool modified); void unassignedVariableError(const Token *tok, const std::string &varname); void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckUnusedVar c(nullptr, settings, errorLogger); c.unusedVariableError(nullptr, "varname"); c.allocatedButUnusedVariableError(nullptr, "varname"); c.unreadVariableError(nullptr, "varname", false); c.unassignedVariableError(nullptr, "varname"); c.unusedStructMemberError(nullptr, "structname", "variable"); } static std::string myName() { return "UnusedVar"; } std::string classInfo() const override { return "UnusedVar checks\n" // style "- unused variable\n" "- allocated but unused variable\n" "- unread variable\n" "- unassigned variable\n" "- unused struct member\n"; } std::map<const Type *,bool> mIsRecordTypeWithoutSideEffectsMap; std::map<const Type *,bool> mIsEmptyTypeMap; }; /// @} //--------------------------------------------------------------------------- #endif // checkunusedvarH
4,323
C++
.h
96
39.916667
148
0.677926
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,470
vf_string.h
danmar_cppcheck/lib/vf_string.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfStringH #define vfStringH class TokenList; class Settings; namespace ValueFlow { void analyzeString(TokenList &tokenlist, const Settings& settings); } #endif // vfStringH
951
C++
.h
26
34.653846
72
0.757872
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,471
cppcheck.h
danmar_cppcheck/lib/cppcheck.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef cppcheckH #define cppcheckH //--------------------------------------------------------------------------- #include "analyzerinfo.h" #include "check.h" #include "color.h" #include "config.h" #include "errorlogger.h" #include "settings.h" #include <cstddef> #include <cstdint> #include <fstream> #include <functional> #include <list> #include <map> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> class TokenList; enum class SHOWTIME_MODES : std::uint8_t; struct FileSettings; class CheckUnusedFunctions; class Tokenizer; class FileWithDetails; class RemarkComment; namespace simplecpp { class TokenList; } /// @addtogroup Core /// @{ /** * @brief This is the base class which will use other classes to do * static code analysis for C and C++ code to find possible * errors or places that could be improved. * Usage: See check() for more info. */ class CPPCHECKLIB CppCheck : ErrorLogger { public: using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>; /** * @brief Constructor. */ CppCheck(ErrorLogger &errorLogger, bool useGlobalSuppressions, ExecuteCmdFn executeCommand); /** * @brief Destructor. */ ~CppCheck() override; /** * @brief This starts the actual checking. Note that you must call * parseFromArgs() or settings() and addFile() before calling this. * @return amount of errors found or 0 if none were found. */ /** * @brief Check the file. * This function checks one given file for errors. * @param file The file to check. * @return amount of errors found or 0 if none were found. * @note You must set settings before calling this function (by calling * settings()). */ unsigned int check(const FileWithDetails &file); unsigned int check(const FileSettings &fs); /** * @brief Check the file. * This function checks one "virtual" file. The file is not read from * the disk but the content is given in @p content. In errors the @p path * is used as a filename. * @param file The file to check. * @param content File content as a string. * @return amount of errors found or 0 if none were found. * @note You must set settings before calling this function (by calling * settings()). */ unsigned int check(const FileWithDetails &file, const std::string &content); /** * @brief Get reference to current settings. * @return a reference to current settings */ Settings &settings(); /** * @brief Returns current version number as a string. * @return version, e.g. "1.38" */ static const char * version(); /** * @brief Returns extra version info as a string. * This is for returning extra version info, like Git commit id, build * time/date etc. * @return extra version info, e.g. "04d42151" (Git commit id). */ static const char * extraVersion(); /** * @brief Call all "getErrorMessages" in all registered Check classes. * Also print out XML header and footer. */ static void getErrorMessages(ErrorLogger &errorlogger); void tooManyConfigsError(const std::string &file, int numberOfConfigurations); void purgedConfigurationMessage(const std::string &file, const std::string& configuration); /** Analyse whole program, run this after all TUs has been scanned. * This is deprecated and the plan is to remove this when * .analyzeinfo is good enough. * Return true if an error is reported. */ bool analyseWholeProgram(); /** Analyze all files using clang-tidy */ void analyseClangTidy(const FileSettings &fileSettings); /** analyse whole program use .analyzeinfo files or ctuinfo string */ unsigned int analyseWholeProgram(const std::string &buildDir, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo); static void resetTimerResults(); static void printTimerResults(SHOWTIME_MODES mode); bool isPremiumCodingStandardId(const std::string& id) const; /** * @brief Get dumpfile <rawtokens> contents, this is only public for testing purposes */ std::string getDumpFileContentsRawTokens(const std::vector<std::string>& files, const simplecpp::TokenList& tokens1) const; std::string getLibraryDumpData() const; private: #ifdef HAVE_RULES /** Are there "simple" rules */ bool hasRule(const std::string &tokenlist) const; #endif /** @brief There has been an internal error => Report information message */ void internalError(const std::string &filename, const std::string &msg); /** * @brief Check a file using stream * @param file the file * @param cfgname cfg name * @param fileStream stream the file content can be read from * @return number of errors found */ unsigned int checkFile(const FileWithDetails& file, const std::string &cfgname, std::istream* fileStream = nullptr); /** * @brief Check normal tokens * @param tokenizer tokenizer instance */ void checkNormalTokens(const Tokenizer &tokenizer); /** * Execute addons */ void executeAddons(const std::vector<std::string>& files, const std::string& file0); void executeAddons(const std::string &dumpFile, const FileWithDetails& file); /** * Execute addons */ void executeAddonsWholeProgram(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo); #ifdef HAVE_RULES /** * @brief Execute rules, if any * @param tokenlist token list to use (define / normal / raw) * @param list token list */ void executeRules(const std::string &tokenlist, const TokenList &list); #endif unsigned int checkClang(const FileWithDetails &file); /** * @brief Errors and warnings are directed here. * * @param msg Errors messages are normally in format * "[filepath:line number] Message", e.g. * "[main.cpp:4] Uninitialized member variable" */ void reportErr(const ErrorMessage &msg) override; /** * @brief Information about progress is directed here. * * @param outmsg Message to show, e.g. "Checking main.cpp..." */ void reportOut(const std::string &outmsg, Color c = Color::Reset) override; // TODO: store hashes instead of the full messages std::unordered_set<std::string> mErrorList; Settings mSettings; void reportProgress(const std::string &filename, const char stage[], std::size_t value) override; ErrorLogger &mErrorLogger; /** @brief Current preprocessor configuration */ std::string mCurrentConfig; using Location = std::pair<std::string, int>; std::map<Location, std::set<std::string>> mLocationMacros; // What macros are used on a location? unsigned int mExitCode{}; bool mUseGlobalSuppressions; /** Are there too many configs? */ bool mTooManyConfigs{}; /** File info used for whole program analysis */ std::list<Check::FileInfo*> mFileInfo; AnalyzerInformation mAnalyzerInformation; /** Callback for executing a shell command (exe, args, output) */ ExecuteCmdFn mExecuteCommand; std::ofstream mPlistFile; std::unique_ptr<CheckUnusedFunctions> mUnusedFunctionsCheck; std::vector<RemarkComment> mRemarkComments; }; /// @} //--------------------------------------------------------------------------- #endif // cppcheckH
8,481
C++
.h
214
35.116822
180
0.683621
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,472
astutils.h
danmar_cppcheck/lib/astutils.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef astutilsH #define astutilsH //--------------------------------------------------------------------------- #include <cstdint> #include <functional> #include <list> #include <stack> #include <string> #include <type_traits> #include <utility> #include <vector> #include "config.h" #include "errortypes.h" #include "library.h" #include "mathlib.h" #include "smallvector.h" #include "symboldatabase.h" #include "token.h" class Settings; enum class ChildrenToVisit : std::uint8_t { none, op1, op2, op1_and_op2, done // found what we looked for, don't visit any more children }; /** * Visit AST nodes recursively. The order is not "well defined" */ template<class T, class TFunc, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> void visitAstNodes(T *ast, const TFunc &visitor) { if (!ast) return; // the size of 8 was determined in tests to be sufficient to avoid excess allocations. also add 1 as a buffer. // we might need to increase that value in the future. std::stack<T *, SmallVector<T *, 8 + 1>> tokens; T *tok = ast; do { const ChildrenToVisit c = visitor(tok); if (c == ChildrenToVisit::done) break; if (c == ChildrenToVisit::op2 || c == ChildrenToVisit::op1_and_op2) { T *t2 = tok->astOperand2(); if (t2) tokens.push(t2); } if (c == ChildrenToVisit::op1 || c == ChildrenToVisit::op1_and_op2) { T *t1 = tok->astOperand1(); if (t1) tokens.push(t1); } if (tokens.empty()) break; tok = tokens.top(); tokens.pop(); } while (true); } template<class TFunc> const Token* findAstNode(const Token* ast, const TFunc& pred) { const Token* result = nullptr; visitAstNodes(ast, [&](const Token* tok) { if (pred(tok)) { result = tok; return ChildrenToVisit::done; } return ChildrenToVisit::op1_and_op2; }); return result; } template<class TFunc> const Token* findParent(const Token* tok, const TFunc& pred) { if (!tok) return nullptr; const Token* parent = tok->astParent(); while (parent && !pred(parent)) { parent = parent->astParent(); } return parent; } const Token* findExpression(nonneg int exprid, const Token* start, const Token* end, const std::function<bool(const Token*)>& pred); const Token* findExpression(const Token* start, nonneg int exprid); std::vector<const Token*> astFlatten(const Token* tok, const char* op); std::vector<Token*> astFlatten(Token* tok, const char* op); nonneg int astCount(const Token* tok, const char* op, int depth = 100); bool astHasToken(const Token* root, const Token * tok); bool astHasExpr(const Token* tok, nonneg int exprid); bool astHasVar(const Token * tok, nonneg int varid); bool astIsPrimitive(const Token* tok); /** Is expression a 'signed char' if no promotion is used */ bool astIsSignedChar(const Token *tok); /** Is expression a 'char' if no promotion is used? */ bool astIsUnknownSignChar(const Token *tok); /** Is expression a char according to valueType? */ bool astIsGenericChar(const Token* tok); /** Is expression of integral type? */ bool astIsIntegral(const Token *tok, bool unknown); bool astIsUnsigned(const Token* tok); /** Is expression of floating point type? */ bool astIsFloat(const Token *tok, bool unknown); /** Is expression of boolean type? */ bool astIsBool(const Token *tok); bool astIsPointer(const Token *tok); bool astIsSmartPointer(const Token* tok); bool astIsUniqueSmartPointer(const Token* tok); bool astIsIterator(const Token *tok); bool astIsContainer(const Token *tok); bool astIsNonStringContainer(const Token *tok); bool astIsContainerView(const Token* tok); bool astIsContainerOwned(const Token* tok); bool astIsContainerString(const Token* tok); Library::Container::Action astContainerAction(const Token* tok, const Token** ftok = nullptr, const Settings* settings = nullptr); Library::Container::Yield astContainerYield(const Token* tok, const Token** ftok = nullptr, const Settings* settings = nullptr); Library::Container::Yield astFunctionYield(const Token* tok, const Settings& settings, const Token** ftok = nullptr); /** Is given token a range-declaration in a range-based for loop */ bool astIsRangeBasedForDecl(const Token* tok); /** * Get canonical type of expression. const/static/etc are not included and neither *&. * For example: * Expression type Return * std::string std::string * int * int * static const int int * std::vector<T> std::vector */ std::string astCanonicalType(const Token *expr, bool pointedToType); /** Is given syntax tree a variable comparison against value */ const Token * astIsVariableComparison(const Token *tok, const std::string &comp, const std::string &rhs, const Token **vartok=nullptr); bool isVariableDecl(const Token* tok); bool isStlStringType(const Token* tok); bool isTemporary(const Token* tok, const Library* library, bool unknown = false); const Token* previousBeforeAstLeftmostLeaf(const Token* tok); Token* previousBeforeAstLeftmostLeaf(Token* tok); CPPCHECKLIB const Token * nextAfterAstRightmostLeaf(const Token * tok); Token* nextAfterAstRightmostLeaf(Token* tok); Token* astParentSkipParens(Token* tok); const Token* astParentSkipParens(const Token* tok); const Token* getParentMember(const Token * tok); const Token* getParentLifetime(const Token* tok); const Token* getParentLifetime(const Token* tok, const Library& library); std::vector<ValueType> getParentValueTypes(const Token* tok, const Settings& settings, const Token** parent = nullptr); bool astIsLHS(const Token* tok); bool astIsRHS(const Token* tok); Token* getCondTok(Token* tok); const Token* getCondTok(const Token* tok); Token* getInitTok(Token* tok); const Token* getInitTok(const Token* tok); Token* getStepTok(Token* tok); const Token* getStepTok(const Token* tok); Token* getCondTokFromEnd(Token* endBlock); const Token* getCondTokFromEnd(const Token* endBlock); /// For a "break" token, locate the next token to execute. The token will /// be either a "}" or a ";". const Token *findNextTokenFromBreak(const Token *breakToken); /** * Extract for loop values: loopvar varid, init value, step value, last value (inclusive) */ bool extractForLoopValues(const Token *forToken, nonneg int &varid, bool &knownInitValue, long long &initValue, bool &partialCond, long long &stepValue, long long &lastValue); bool precedes(const Token * tok1, const Token * tok2); bool succeeds(const Token* tok1, const Token* tok2); bool exprDependsOnThis(const Token* expr, bool onVar = true, nonneg int depth = 0); struct ReferenceToken { ReferenceToken(const Token* t, ErrorPath e) : token(t) , errors(std::move(e)) {} const Token* token; ErrorPath errors; }; SmallVector<ReferenceToken> followAllReferences(const Token* tok, bool temporary = true, bool inconclusive = true, ErrorPath errors = ErrorPath{}, int depth = 20); const Token* followReferences(const Token* tok, ErrorPath* errors = nullptr); CPPCHECKLIB bool isSameExpression(bool macro, const Token *tok1, const Token *tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr); bool isEqualKnownValue(const Token * tok1, const Token * tok2); bool isStructuredBindingVariable(const Variable* var); const Token* isInLoopCondition(const Token* tok); /** * Is token used as boolean, that is to say cast to a bool, or used as a condition in a if/while/for */ CPPCHECKLIB bool isUsedAsBool(const Token* tok, const Settings& settings); /** * Are the tokens' flags equal? */ bool compareTokenFlags(const Token* tok1, const Token* tok2, bool macro); /** * Are two conditions opposite * @param isNot do you want to know if cond1 is !cond2 or if cond1 and cond2 are non-overlapping. true: cond1==!cond2 false: cond1==true => cond2==false * @param cond1 condition1 * @param cond2 condition2 * @param settings settings * @param pure boolean */ bool isOppositeCond(bool isNot, const Token * cond1, const Token * cond2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr); bool isOppositeExpression(const Token * tok1, const Token * tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr); bool isConstFunctionCall(const Token* ftok, const Library& library); bool isConstExpression(const Token *tok, const Library& library); bool isWithoutSideEffects(const Token* tok, bool checkArrayAccess = false, bool checkReference = true); bool isUniqueExpression(const Token* tok); bool isEscapeFunction(const Token* ftok, const Library* library); /** Is scope a return scope (scope will unconditionally return) */ CPPCHECKLIB bool isReturnScope(const Token* endToken, const Library& library, const Token** unknownFunc = nullptr, bool functionScope = false); /** Is tok within a scope of the given type, nested within var's scope? */ bool isWithinScope(const Token* tok, const Variable* var, Scope::ScopeType type); /// Return the token to the function and the argument number const Token * getTokenArgumentFunction(const Token * tok, int& argn); Token* getTokenArgumentFunction(Token* tok, int& argn); std::vector<const Variable*> getArgumentVars(const Token* tok, int argnr); /** Is variable changed by function call? * In case the answer of the question is inconclusive, e.g. because the function declaration is not known * the return value is false and the output parameter inconclusive is set to true * * @param tok ast tree * @param varid Variable Id * @param settings program settings * @param inconclusive pointer to output variable which indicates that the answer of the question is inconclusive */ bool isVariableChangedByFunctionCall(const Token *tok, int indirect, nonneg int varid, const Settings &settings, bool *inconclusive); /** Is variable changed by function call? * In case the answer of the question is inconclusive, e.g. because the function declaration is not known * the return value is false and the output parameter inconclusive is set to true * * @param tok token of variable in function call * @param settings program settings * @param inconclusive pointer to output variable which indicates that the answer of the question is inconclusive */ CPPCHECKLIB bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Settings &settings, bool *inconclusive); /** Is variable changed in block of code? */ CPPCHECKLIB bool isVariableChanged(const Token *start, const Token *end, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20); bool isVariableChanged(const Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20); bool isVariableChanged(const Token *tok, int indirect, const Settings &settings, int depth = 20); bool isVariableChanged(const Variable * var, const Settings &settings, int depth = 20); bool isVariablesChanged(const Token* start, const Token* end, int indirect, const std::vector<const Variable*> &vars, const Settings& settings); bool isThisChanged(const Token* tok, int indirect, const Settings& settings); const Token* findVariableChanged(const Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20); Token* findVariableChanged(Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20); CPPCHECKLIB const Token* findExpressionChanged(const Token* expr, const Token* start, const Token* end, const Settings& settings, int depth = 20); const Token* findExpressionChangedSkipDeadCode(const Token* expr, const Token* start, const Token* end, const Settings& settings, const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate, int depth = 20); bool isExpressionChangedAt(const Token* expr, const Token* tok, int indirect, bool globalvar, const Settings& settings, int depth = 20); /// If token is an alias if another variable bool isAliasOf(const Token *tok, nonneg int varid, bool* inconclusive = nullptr); bool isAliasOf(const Token* tok, const Token* expr, int* indirect = nullptr); const Token* getArgumentStart(const Token* ftok); /** Determines the number of arguments - if token is a function call or macro * @param ftok start token which is supposed to be the function/macro name. * @return Number of arguments */ int numberOfArguments(const Token* ftok); /// Get number of arguments without using AST int numberOfArgumentsWithoutAst(const Token* start); /** * Get arguments (AST) */ std::vector<const Token *> getArguments(const Token *ftok); int getArgumentPos(const Variable* var, const Function* f); const Token* getIteratorExpression(const Token* tok); /** * Are the arguments a pair of iterators/pointers? */ bool isIteratorPair(const std::vector<const Token*>& args); CPPCHECKLIB const Token *findLambdaStartToken(const Token *last); /** * find lambda function end token * \param first The [ token * \return nullptr or the } */ CPPCHECKLIB const Token *findLambdaEndToken(const Token *first); CPPCHECKLIB Token* findLambdaEndToken(Token* first); bool isLikelyStream(const Token *stream); /** * do we see a likely write of rhs through overloaded operator * s >> x; * a & x; */ bool isLikelyStreamRead(const Token *op); bool isCPPCast(const Token* tok); bool isConstVarExpression(const Token* tok, const std::function<bool(const Token*)>& skipPredicate = nullptr); bool isLeafDot(const Token* tok); enum class ExprUsage : std::uint8_t { None, NotUsed, PassedByReference, Used, Inconclusive }; ExprUsage getExprUsage(const Token* tok, int indirect, const Settings& settings); const Variable *getLHSVariable(const Token *tok); const Token* getLHSVariableToken(const Token* tok); std::vector<const Variable*> getLHSVariables(const Token* tok); /** Find a allocation function call in expression, so result of expression is allocated memory/resource. */ const Token* findAllocFuncCallToken(const Token *expr, const Library &library); bool isScopeBracket(const Token* tok); CPPCHECKLIB bool isNullOperand(const Token *expr); bool isGlobalData(const Token *expr); bool isUnevaluated(const Token *tok); bool isExhaustiveSwitch(const Token *startbrace); bool isUnreachableOperand(const Token *tok); #endif // astutilsH
16,724
C++
.h
348
41.767241
164
0.684777
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,474
ctu.h
danmar_cppcheck/lib/ctu.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef ctuH #define ctuH //--------------------------------------------------------------------------- #include "config.h" #include "check.h" #include "errorlogger.h" #include "mathlib.h" #include "vfvalue.h" #include <cstdint> #include <list> #include <map> #include <string> #include <utility> #include <vector> class Function; class Settings; class Token; class Tokenizer; namespace tinyxml2 { class XMLElement; } /// @addtogroup Core /// @{ /** @brief Whole program analysis (ctu=Cross Translation Unit) */ namespace CTU { class CPPCHECKLIB FileInfo : public Check::FileInfo { public: enum class InvalidValueType : std::uint8_t { null, uninit, bufferOverflow }; std::string toString() const override; struct Location { Location() = default; Location(const Tokenizer &tokenizer, const Token *tok); Location(std::string fileName, nonneg int lineNumber, nonneg int column) : fileName(std::move(fileName)), lineNumber(lineNumber), column(column) {} std::string fileName; nonneg int lineNumber{}; nonneg int column{}; }; struct UnsafeUsage { UnsafeUsage() = default; UnsafeUsage(std::string myId, nonneg int myArgNr, std::string myArgumentName, Location location, MathLib::bigint value) : myId(std::move(myId)), myArgNr(myArgNr), myArgumentName(std::move(myArgumentName)), location(std::move(location)), value(value) {} std::string myId; nonneg int myArgNr{}; std::string myArgumentName; Location location; MathLib::bigint value{}; std::string toString() const; }; class CallBase { public: CallBase() = default; CallBase(std::string callId, int callArgNr, std::string callFunctionName, Location loc) : callId(std::move(callId)), callArgNr(callArgNr), callFunctionName(std::move(callFunctionName)), location(std::move(loc)) {} CallBase(const Tokenizer &tokenizer, const Token *callToken); virtual ~CallBase() = default; CallBase(const CallBase&) = default; std::string callId; int callArgNr{}; std::string callFunctionName; Location location; protected: std::string toBaseXmlString() const; bool loadBaseFromXml(const tinyxml2::XMLElement *xmlElement); }; class FunctionCall : public CallBase { public: std::string callArgumentExpression; MathLib::bigint callArgValue; ValueFlow::Value::ValueType callValueType; std::vector<ErrorMessage::FileLocation> callValuePath; bool warning; std::string toXmlString() const; bool loadFromXml(const tinyxml2::XMLElement *xmlElement); }; class NestedCall : public CallBase { public: NestedCall() = default; NestedCall(std::string myId, nonneg int myArgNr, const std::string &callId, nonneg int callArgnr, const std::string &callFunctionName, const Location &location) : CallBase(callId, callArgnr, callFunctionName, location), myId(std::move(myId)), myArgNr(myArgNr) {} NestedCall(const Tokenizer &tokenizer, const Function *myFunction, const Token *callToken); std::string toXmlString() const; bool loadFromXml(const tinyxml2::XMLElement *xmlElement); std::string myId; nonneg int myArgNr{}; }; std::list<FunctionCall> functionCalls; std::list<NestedCall> nestedCalls; void loadFromXml(const tinyxml2::XMLElement *xmlElement); std::map<std::string, std::list<const CallBase *>> getCallsMap() const; static std::list<ErrorMessage::FileLocation> getErrorPath(InvalidValueType invalidValue, const UnsafeUsage &unsafeUsage, const std::map<std::string, std::list<const CallBase *>> &callsMap, const char info[], const FunctionCall ** functionCallPtr, bool warning, int maxCtuDepth); }; CPPCHECKLIB std::string toString(const std::list<FileInfo::UnsafeUsage> &unsafeUsage); CPPCHECKLIB std::string getFunctionId(const Tokenizer &tokenizer, const Function *function); /** @brief Parse current TU and extract file info */ CPPCHECKLIB FileInfo *getFileInfo(const Tokenizer &tokenizer); CPPCHECKLIB std::list<FileInfo::UnsafeUsage> getUnsafeUsage(const Tokenizer &tokenizer, const Settings &settings, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value)); CPPCHECKLIB std::list<FileInfo::UnsafeUsage> loadUnsafeUsageListFromXml(const tinyxml2::XMLElement *xmlElement); } /// @} //--------------------------------------------------------------------------- #endif // ctuH
6,155
C++
.h
127
38.070866
264
0.605268
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,475
summaries.h
danmar_cppcheck/lib/summaries.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef summariesH #define summariesH //--------------------------------------------------------------------------- #include "config.h" #include <set> #include <string> class Tokenizer; namespace Summaries { CPPCHECKLIB std::string create(const Tokenizer &tokenizer, const std::string &cfg); CPPCHECKLIB void loadReturn(const std::string &buildDir, std::set<std::string> &summaryReturn); } //--------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------
1,407
C++
.h
32
42.03125
99
0.584368
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,476
tokenize.h
danmar_cppcheck/lib/tokenize.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef tokenizeH #define tokenizeH //--------------------------------------------------------------------------- #include "config.h" #include "tokenlist.h" #include <cstdint> #include <iosfwd> #include <list> #include <map> #include <string> #include <vector> class Settings; class SymbolDatabase; class TimerResults; class Token; class TemplateSimplifier; class ErrorLogger; struct Directive; enum class Severity : std::uint8_t; /// @addtogroup Core /// @{ /** @brief The main purpose is to tokenize the source code. It also has functions that simplify the token list */ class CPPCHECKLIB Tokenizer { friend class SymbolDatabase; friend class TemplateSimplifier; friend class TestSimplifyTemplate; friend class TestSimplifyTypedef; friend class TestTokenizer; public: explicit Tokenizer(const Settings & settings, ErrorLogger &errorLogger); ~Tokenizer(); void setTimerResults(TimerResults *tr) { mTimerResults = tr; } /** Is the code C. Used for bailouts */ bool isC() const { return list.isC(); } /** Is the code CPP. Used for bailouts */ bool isCPP() const { return list.isCPP(); } /** * Check if inner scope ends with a call to a noreturn function * \param endScopeToken The '}' token * \param unknown set to true if it's unknown if the scope is noreturn * \return true if scope ends with a function call that might be 'noreturn' */ bool isScopeNoReturn(const Token *endScopeToken, bool *unknown = nullptr) const; bool simplifyTokens1(const std::string &configuration); private: /** Set variable id */ void setVarId(); void setVarIdPass1(); void setVarIdPass2(); /** * Basic simplification of tokenlist * * @param FileName The filename to run; used to do * markup checks. * * @return false if there is an error that requires aborting * the checking of this file. */ bool simplifyTokenList1(const char FileName[]); /** * If --check-headers=no has been given; then remove unneeded code in headers. * - All executable code. * - Unused types/variables/etc */ void simplifyHeadersAndUnusedTemplates(); /** * Remove extra "template" keywords that are not used by Cppcheck */ void removeExtraTemplateKeywords(); /** Split up template right angle brackets. * foo < bar < >> => foo < bar < > > */ void splitTemplateRightAngleBrackets(bool check); public: /** * Calculates sizeof value for given type. * @param type Token which will contain e.g. "int", "*", or string. * @return sizeof for given type, or 0 if it can't be calculated. */ nonneg int sizeOfType(const Token* type) const; nonneg int sizeOfType(const std::string& type) const; private: void simplifyDebug(); /** Simplify assignment where rhs is a block : "x=({123;});" => "{x=123;}" */ void simplifyAssignmentBlock(); /** Insert array size where it isn't given */ void arraySize(); void arraySizeAfterValueFlow(); // cppcheck-suppress functionConst /** Simplify labels and 'case|default' syntaxes. */ void simplifyLabelsCaseDefault(); /** simplify case ranges (gcc extension) */ void simplifyCaseRange(); /** Remove macros in global scope */ void removeMacrosInGlobalScope(); void addSemicolonAfterUnknownMacro(); // Remove C99 and CPP11 _Pragma(str) void removePragma(); /** Remove undefined macro in class definition: * class DLLEXPORT Fred { }; * class Fred FINAL : Base { }; */ void removeMacroInClassDef(); /** Add parentheses for sizeof: sizeof x => sizeof(x) */ void sizeofAddParentheses(); /** * Simplify variable declarations (split up) * \param only_k_r_fpar Only simplify K&R function parameters */ void simplifyVarDecl( bool only_k_r_fpar); void simplifyVarDecl(Token * tokBegin, const Token * tokEnd, bool only_k_r_fpar); // cppcheck-suppress functionConst // has side effects /** * Simplify variable initialization * '; int *p(0);' => '; int *p = 0;' */ void simplifyInitVar(); static Token* initVar(Token* tok); /** * Simplify the location of "static" and "const" qualifiers in * a variable declaration or definition. * Example: "int static const a;" => "static const a;" * Example: "long long const static b;" => "static const long long b;" */ void simplifyStaticConst(); /** * Simplify multiple assignments. * Example: "a = b = c = 0;" => "a = 0; b = 0; c = 0;" */ void simplifyVariableMultipleAssign(); /** * Simplify the 'C Alternative Tokens' * Examples: * "if(s and t)" => "if(s && t)" * "while((r bitand s) and not t)" => while((r & s) && !t)" * "a and_eq b;" => "a &= b;" */ bool simplifyCAlternativeTokens(); /** Add braces to an if-block, for-block, etc. * @return true if no syntax errors */ bool simplifyAddBraces(); /** Add braces to an if-block, for-block, etc. * for command starting at token including else-block * @return last token of command * or input token in case of an error where no braces are added * or NULL when syntaxError is called */ Token * simplifyAddBracesToCommand(Token * tok); /** Add pair of braces to an single if-block, else-block, for-block, etc. * for command starting at token * @return last token of command * or input token in case of an error where no braces are added * or NULL when syntaxError is called */ Token * simplifyAddBracesPair(Token *tok, bool commandWithCondition); // Convert "using ...;" to corresponding typedef void simplifyUsingToTypedef(); /** * typedef A mytype; * mytype c; * * Becomes: * typedef A mytype; * A c; */ void simplifyTypedef(); void simplifyTypedefCpp(); /** * Move typedef token to the left og the expression */ void simplifyTypedefLHS(); /** */ static bool isMemberFunction(const Token *openParen); /** */ bool simplifyUsing(); void simplifyUsingError(const Token* usingStart, const Token* usingEnd); /** Simplify useless C++ empty namespaces, like: 'namespace %name% { }'*/ void simplifyEmptyNamespaces(); /** Simplify "if else" */ void elseif(); /** Simplify C++17/C++20 if/switch/for initialization expression */ void simplifyIfSwitchForInit(); /** * Reduces "; ;" to ";", except in "( ; ; )" */ void removeRedundantSemicolons(); /** Struct simplification * "struct S { } s;" => "struct S { }; S s;" */ void simplifyStructDecl(); /** * Remove redundant parentheses: * - "((x))" => "(x)" * - "(function())" => "function()" * - "(delete x)" => "delete x" * - "(delete [] x)" => "delete [] x" * @return true if modifications to token-list are done. * false if no modifications are done. */ bool simplifyRedundantParentheses(); /** * Simplify functions like "void f(x) int x; {" * into "void f(int x) {" */ void simplifyFunctionParameters(); /** Simplify function level try blocks: * Convert "void f() try {} catch (int) {}" * to "void f() { try {} catch (int) {} }" */ void simplifyFunctionTryCatch(); /** * Simplify templates */ void simplifyTemplates(); void simplifyDoublePlusAndDoubleMinus(); void simplifyRedundantConsecutiveBraces(); void simplifyArrayAccessSyntax(); void simplifyParameterVoid(); void fillTypeSizes(); void combineOperators(); void combineStringAndCharLiterals(); void concatenateNegativeNumberAndAnyPositive(); void simplifyExternC(); void simplifyRoundCurlyParentheses(); void simplifyTypeIntrinsics(); void simplifySQL(); void checkForEnumsWithTypedef(); void findComplicatedSyntaxErrorsInTemplates(); /** * Modify strings in the token list by replacing hex and oct * values. E.g. "\x61" -> "a" and "\000" -> "\0" * @param source The string to be modified, e.g. "\x61" * @return Modified string, e.g. "a" */ static std::string simplifyString(const std::string &source); public: /** * is token pointing at function head? * @param tok A '(' or ')' token in a possible function head * @param endsWith string after function head * @return token matching with endsWith if syntax seems to be a function head else nullptr */ static const Token * isFunctionHead(const Token *tok, const std::string &endsWith); bool hasIfdef(const Token *start, const Token *end) const; bool isPacked(const Token * bodyStart) const; private: /** Simplify pointer to standard type (C only) */ void simplifyPointerToStandardType(); /** Simplify function pointers */ void simplifyFunctionPointers(); /** * Send error message to error logger about internal bug. * @param tok the token that this bug concerns. */ NORETURN void cppcheckError(const Token *tok) const; /** * Setup links for tokens so that one can call Token::link(). */ void createLinks(); /** * Setup links between < and >. */ void createLinks2(); /** * Set isCast() for C++ casts */ void markCppCasts(); public: /** Syntax error */ NORETURN void syntaxError(const Token *tok, const std::string &code = emptyString) const; /** Syntax error. Unmatched character. */ NORETURN void unmatchedToken(const Token *tok) const; /** Syntax error. C++ code in C file. */ NORETURN void syntaxErrorC(const Token *tok, const std::string &what) const; /** Warn about unknown macro(s), configuration is recommended */ NORETURN void unknownMacroError(const Token *tok1) const; void unhandledCharLiteral(const Token *tok, const std::string& msg) const; private: /** Report that there is an unhandled "class x y {" code */ void unhandled_macro_class_x_y(const Token *tok) const; /** Check configuration (unknown macros etc) */ void checkConfiguration() const; void macroWithSemicolonError(const Token *tok, const std::string &macroName) const; /** * Is there C++ code in C file? */ void validateC() const; /** * assert that tokens are ok - used during debugging for example * to catch problems in simplifyTokenList1/2. */ void validate() const; /** Detect unknown macros and throw unknownMacro */ void reportUnknownMacros() const; /** Detect garbage code and call syntaxError() if found. */ void findGarbageCode() const; /** Detect garbage expression */ static bool isGarbageExpr(const Token *start, const Token *end, bool allowSemicolon); /** * Remove __declspec() */ void simplifyDeclspec(); /** * Remove calling convention */ void simplifyCallingConvention(); /** * Remove \__attribute\__ ((?)) */ void simplifyAttribute(); /** Get function token for a attribute */ Token* getAttributeFuncTok(Token* tok, bool gccattr) const; /** * Remove \__cppcheck\__ ((?)) */ void simplifyCppcheckAttribute(); /** Simplify c++20 spaceship operator */ void simplifySpaceshipOperator(); /** * Remove keywords "volatile", "inline", "register", and "restrict" */ void simplifyKeyword(); /** * Remove __asm */ void simplifyAsm(); /** * asm heuristics, Put ^{} statements in asm() */ void simplifyAsm2(); /** * Simplify \@&hellip; (compiler extension) */ void simplifyAt(); /** * Simplify bitfields - the field width is removed as we don't use it. */ void simplifyBitfields(); /** * Remove unnecessary member qualification */ void removeUnnecessaryQualification(); /** * Add std:: in front of std classes, when using namespace std; was given */ void simplifyNamespaceStd(); /** * Convert Microsoft memory functions * CopyMemory(dst, src, len) -> memcpy(dst, src, len) * FillMemory(dst, len, val) -> memset(dst, val, len) * MoveMemory(dst, src, len) -> memmove(dst, src, len) * ZeroMemory(dst, len) -> memset(dst, 0, len) */ void simplifyMicrosoftMemoryFunctions(); /** * Convert Microsoft string functions * _tcscpy -> strcpy */ void simplifyMicrosoftStringFunctions(); /** * Remove Borland code */ void simplifyBorland(); /** * Collapse operator name tokens into single token * operator = => operator= */ void simplifyOperatorName(); /** simplify overloaded operators: 'obj(123)' => 'obj . operator() ( 123 )' */ void simplifyOverloadedOperators(); /** * Remove [[attribute]] (C++11, C23) from TokenList */ void simplifyCPPAttribute(); /** * Convert namespace aliases */ void simplifyNamespaceAliases(); /** * Convert C++17 style nested namespace to older style */ void simplifyNestedNamespace(); /** * Simplify coroutines - just put parentheses around arguments for * co_* keywords so they can be handled like function calls in data * flow. */ void simplifyCoroutines(); /** * Prepare ternary operators with parentheses so that the AST can be created * */ void prepareTernaryOpForAST(); /** * report error message */ void reportError(const Token* tok, Severity severity, const std::string& id, const std::string& msg, bool inconclusive = false) const; void reportError(const std::list<const Token*>& callstack, Severity severity, const std::string& id, const std::string& msg, bool inconclusive = false) const; bool duplicateTypedef(Token *&tokPtr, const Token *name, const Token *typeDef) const; void unsupportedTypedef(const Token *tok) const; static void setVarIdClassFunction(const std::string &classname, Token * startToken, const Token * endToken, const std::map<std::string, nonneg int> &varlist, std::map<nonneg int, std::map<std::string, nonneg int>>& structMembers, nonneg int &varId_); /** * Output list of unknown types. */ void printUnknownTypes() const; /** Find end of SQL (or PL/SQL) block */ static const Token *findSQLBlockEnd(const Token *tokSQLStart); static bool operatorEnd(const Token * tok); public: const SymbolDatabase *getSymbolDatabase() const { return mSymbolDatabase; } void createSymbolDatabase(); /** print --debug output if debug flags match the simplification: * 0=unknown/both simplifications * 1=1st simplifications * 2=2nd simplifications */ void printDebugOutput(int simplification, std::ostream &out) const; void dump(std::ostream &out) const; Token *deleteInvalidTypedef(Token *typeDef); /** * Get variable count. * @return number of variables */ nonneg int varIdCount() const { return mVarId; } /** * Token list: stores all tokens. */ TokenList list; // Implement tokens() as a wrapper for convenience when using the TokenList const Token* tokens() const { return list.front(); } Token* tokens() { return list.front(); } /** * Helper function to check whether number is one (1 or 0.1E+1 or 1E+0) or not? * @param s the string to check * @return true in case is is one and false otherwise. */ static bool isOneNumber(const std::string &s); /** * Helper function to check for start of function execution scope. * Do not use this in checks. Use the symbol database. * @param tok pointer to end parentheses of parameter list * @return pointer to start brace of function scope or nullptr if not start. */ static const Token * startOfExecutableScope(const Token * tok); const Settings &getSettings() const { return mSettings; } void calculateScopes(); /** Disable copy constructor */ Tokenizer(const Tokenizer &) = delete; /** Disable assignment operator */ Tokenizer &operator=(const Tokenizer &) = delete; void setDirectives(std::list<Directive> directives); std::string dumpTypedefInfo() const; private: const Token *processFunc(const Token *tok2, bool inOperator) const; Token *processFunc(Token *tok2, bool inOperator); /** * Get new variable id. * @return new variable id */ nonneg int newVarId() { return ++mVarId; } /** Set pod types */ void setPodTypes(); /** settings */ const Settings & mSettings; /** errorlogger */ ErrorLogger& mErrorLogger; /** Symbol database that all checks etc can use */ SymbolDatabase* mSymbolDatabase{}; TemplateSimplifier * const mTemplateSimplifier; /** E.g. "A" for code where "#ifdef A" is true. This is used to print additional information in error situations. */ std::string mConfiguration; /** sizeof information for known types */ std::map<std::string, int> mTypeSize; struct TypedefInfo { std::string name; std::string filename; int lineNumber; int column; bool used; bool isFunctionPointer; }; std::vector<TypedefInfo> mTypedefInfo; std::list<Directive> mDirectives; /** variable count */ nonneg int mVarId{}; /** unnamed count "Unnamed0", "Unnamed1", "Unnamed2", ... */ nonneg int mUnnamedCount{}; /** * TimerResults */ TimerResults* mTimerResults{}; }; /// @} //--------------------------------------------------------------------------- #endif // tokenizeH
19,032
C++
.h
539
29.615955
162
0.640532
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,477
json.h
danmar_cppcheck/lib/json.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef jsonH #define jsonH #include "config.h" SUPPRESS_WARNING_PUSH("-Wfloat-equal") SUPPRESS_WARNING_GCC_PUSH("-Wuseless-cast") SUPPRESS_WARNING_CLANG_PUSH("-Wtautological-type-limit-compare") SUPPRESS_WARNING_CLANG_PUSH("-Wextra-semi-stmt") SUPPRESS_WARNING_CLANG_PUSH("-Wzero-as-null-pointer-constant") SUPPRESS_WARNING_CLANG_PUSH("-Wformat") #define PICOJSON_USE_INT64 #include <picojson.h> SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_GCC_POP SUPPRESS_WARNING_POP #endif // jsonH
1,335
C++
.h
35
36.514286
72
0.775889
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,478
timer.h
danmar_cppcheck/lib/timer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef timerH #define timerH //--------------------------------------------------------------------------- #include "config.h" #include <cstdint> #include <ctime> #include <functional> #include <map> #include <mutex> #include <string> #include <utility> enum class SHOWTIME_MODES : std::uint8_t { SHOWTIME_NONE, SHOWTIME_FILE, SHOWTIME_FILE_TOTAL, SHOWTIME_SUMMARY, SHOWTIME_TOP5_SUMMARY, SHOWTIME_TOP5_FILE }; class CPPCHECKLIB TimerResultsIntf { public: virtual ~TimerResultsIntf() = default; virtual void addResults(const std::string& str, std::clock_t clocks) = 0; }; struct TimerResultsData { std::clock_t mClocks{}; long mNumberOfResults{}; double seconds() const { const double ret = (double)((unsigned long)mClocks) / (double)CLOCKS_PER_SEC; return ret; } }; class CPPCHECKLIB TimerResults : public TimerResultsIntf { public: TimerResults() = default; void showResults(SHOWTIME_MODES mode) const; void addResults(const std::string& str, std::clock_t clocks) override; void reset(); private: std::map<std::string, TimerResultsData> mResults; mutable std::mutex mResultsSync; }; class CPPCHECKLIB Timer { public: Timer(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults = nullptr); Timer(bool fileTotal, std::string filename); ~Timer(); Timer(const Timer&) = delete; Timer& operator=(const Timer&) = delete; void stop(); static void run(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults, const std::function<void()>& f) { Timer t(std::move(str), showtimeMode, timerResults); f(); } private: const std::string mStr; TimerResultsIntf* mTimerResults{}; std::clock_t mStart = std::clock(); const SHOWTIME_MODES mShowTimeMode = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL; bool mStopped{}; }; //--------------------------------------------------------------------------- #endif // timerH
2,847
C++
.h
81
31.82716
131
0.661818
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,479
reverseanalyzer.h
danmar_cppcheck/lib/reverseanalyzer.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef reverseanalyzerH #define reverseanalyzerH struct Analyzer; class ErrorLogger; class Settings; class Token; class TokenList; template<class T> class ValuePtr; void valueFlowGenericReverse(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings); #endif
1,110
C++
.h
28
37.928571
170
0.773655
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,480
preprocessor.h
danmar_cppcheck/lib/preprocessor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef preprocessorH #define preprocessorH //--------------------------------------------------------------------------- #include "config.h" #include <cstddef> #include <cstdint> #include <istream> #include <list> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include <simplecpp.h> class ErrorLogger; class Settings; class SuppressionList; /** * @brief A preprocessor directive * Each preprocessor directive (\#include, \#define, \#undef, \#if, \#ifdef, \#else, \#endif) * will be recorded as an instance of this class. * * file and linenr denote the location where the directive is defined. * */ struct CPPCHECKLIB Directive { /** name of (possibly included) file where directive is defined */ std::string file; /** line number in (possibly included) file where directive is defined */ unsigned int linenr; /** the actual directive text */ std::string str; struct DirectiveToken { explicit DirectiveToken(const simplecpp::Token & _tok); int line; int column; std::string tokStr; }; std::vector<DirectiveToken> strTokens; /** record a directive (possibly filtering src) */ Directive(const simplecpp::Location & _loc, std::string _str); Directive(std::string _file, int _linenr, std::string _str); }; class CPPCHECKLIB RemarkComment { public: RemarkComment(std::string file, unsigned int lineNumber, std::string str) : file(std::move(file)) , lineNumber(lineNumber) , str(std::move(str)) {} /** name of file */ std::string file; /** line number for the code that the remark comment is about */ unsigned int lineNumber; /** remark text */ std::string str; }; /// @addtogroup Core /// @{ /** * @brief The cppcheck preprocessor. * The preprocessor has special functionality for extracting the various ifdef * configurations that exist in a source file. */ class CPPCHECKLIB WARN_UNUSED Preprocessor { // TODO: get rid of this friend class PreprocessorHelper; friend class TestPreprocessor; friend class TestUnusedVar; public: /** character that is inserted in expanded macros */ static char macroChar; explicit Preprocessor(const Settings& settings, ErrorLogger &errorLogger); virtual ~Preprocessor(); void inlineSuppressions(const simplecpp::TokenList &tokens, SuppressionList &suppressions); std::list<Directive> createDirectives(const simplecpp::TokenList &tokens) const; std::set<std::string> getConfigs(const simplecpp::TokenList &tokens) const; std::vector<RemarkComment> getRemarkComments(const simplecpp::TokenList &tokens) const; bool loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files); void removeComments(simplecpp::TokenList &tokens); static void setPlatformInfo(simplecpp::TokenList &tokens, const Settings& settings); simplecpp::TokenList preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError = false); std::string getcode(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool writeLocations); /** * Calculate HASH. Using toolinfo, tokens1, filedata. * * @param tokens1 Sourcefile tokens * @param toolinfo Arbitrary extra toolinfo * @return HASH */ std::size_t calculateHash(const simplecpp::TokenList &tokens1, const std::string &toolinfo) const; void simplifyPragmaAsm(simplecpp::TokenList &tokenList) const; static void getErrorMessages(ErrorLogger &errorLogger, const Settings &settings); /** * dump all directives present in source file */ void dump(std::ostream &out) const; static bool hasErrors(const simplecpp::Output &output); private: void handleErrors(const simplecpp::OutputList &outputList, bool throwError); void reportOutput(const simplecpp::OutputList &outputList, bool showerror); static void simplifyPragmaAsmPrivate(simplecpp::TokenList &tokenList); /** * Include file types. */ enum HeaderTypes : std::uint8_t { UserHeader = 1, SystemHeader }; void missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType); void error(const std::string &filename, unsigned int linenr, const std::string &msg); static bool hasErrors(const simplecpp::OutputList &outputList); void addRemarkComments(const simplecpp::TokenList &tokens, std::vector<RemarkComment> &remarkComments) const; const Settings& mSettings; ErrorLogger &mErrorLogger; /** list of all directives met while preprocessing file */ std::map<std::string, simplecpp::TokenList *> mTokenLists; /** filename for cpp/c file - useful when reporting errors */ std::string mFile0; /** simplecpp tracking info */ std::list<simplecpp::MacroUsage> mMacroUsage; std::list<simplecpp::IfCond> mIfCond; }; /// @} //--------------------------------------------------------------------------- #endif // preprocessorH
5,999
C++
.h
144
37.548611
155
0.69697
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,481
vf_bitand.h
danmar_cppcheck/lib/vf_bitand.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef vfBitAndH #define vfBitAndH class TokenList; class Settings; namespace ValueFlow { void analyzeBitAnd(TokenList &tokenlist, const Settings& settings); } #endif // vfBitAndH
951
C++
.h
26
34.653846
72
0.757872
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,482
checkboost.h
danmar_cppcheck/lib/checkboost.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef checkboostH #define checkboostH //--------------------------------------------------------------------------- #include "check.h" #include "config.h" #include "tokenize.h" #include <string> class ErrorLogger; class Settings; class Token; /// @addtogroup Checks /// @{ /** @brief %Check Boost usage */ class CPPCHECKLIB CheckBoost : public Check { public: /** This constructor is used when registering the CheckClass */ CheckBoost() : Check(myName()) {} private: /** This constructor is used when running checks. */ CheckBoost(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) : Check(myName(), tokenizer, settings, errorLogger) {} /** @brief Run checks against the normal token list */ void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override { if (!tokenizer.isCPP()) return; CheckBoost checkBoost(&tokenizer, &tokenizer.getSettings(), errorLogger); checkBoost.checkBoostForeachModification(); } /** @brief %Check for container modification while using the BOOST_FOREACH macro */ void checkBoostForeachModification(); void boostForeachError(const Token *tok); void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override { CheckBoost c(nullptr, settings, errorLogger); c.boostForeachError(nullptr); } static std::string myName() { return "Boost usage"; } std::string classInfo() const override { return "Check for invalid usage of Boost:\n" "- container modification during BOOST_FOREACH\n"; } }; /// @} //--------------------------------------------------------------------------- #endif // checkboostH
2,602
C++
.h
64
36.734375
94
0.651864
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,483
symboldatabase.h
danmar_cppcheck/lib/symboldatabase.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #ifndef symboldatabaseH #define symboldatabaseH //--------------------------------------------------------------------------- #include "config.h" #include "errortypes.h" #include "library.h" #include "mathlib.h" #include "sourcelocation.h" #include "token.h" #include "utils.h" #include <algorithm> #include <cctype> #include <cstdint> #include <iosfwd> #include <list> #include <map> #include <set> #include <string> #include <utility> #include <vector> class Platform; class ErrorLogger; class Function; class Scope; class Settings; class SymbolDatabase; class Tokenizer; class ValueType; enum class Reference : std::uint8_t { None, LValue, RValue }; /** * @brief Access control enumerations. */ enum class AccessControl : std::uint8_t { Public, Protected, Private, Global, Namespace, Argument, Local, Throw }; /** * @brief Array dimension information. */ struct Dimension { const Token* tok{}; ///< size token MathLib::bigint num{}; ///< (assumed) dimension length when size is a number, 0 if not known bool known = true; ///< Known size }; /** @brief Information about a class type. */ class CPPCHECKLIB Type { public: const Token* classDef; ///< Points to "class" token const Scope* classScope; const Scope* enclosingScope; enum class NeedInitialization : std::uint8_t { Unknown, True, False } needInitialization = NeedInitialization::Unknown; struct BaseInfo { std::string name; const Type* type{}; const Token* nameTok{}; AccessControl access{}; // public/protected/private bool isVirtual{}; // allow ordering within containers bool operator<(const BaseInfo& rhs) const { return this->type < rhs.type; } }; struct FriendInfo { const Token* nameStart{}; const Token* nameEnd{}; const Type* type{}; }; std::vector<BaseInfo> derivedFrom; std::vector<FriendInfo> friendList; const Token* typeStart{}; const Token* typeEnd{}; MathLib::bigint sizeOf{}; explicit Type(const Token* classDef_ = nullptr, const Scope* classScope_ = nullptr, const Scope* enclosingScope_ = nullptr) : classDef(classDef_), classScope(classScope_), enclosingScope(enclosingScope_) { if (classDef_ && classDef_->str() == "enum") needInitialization = NeedInitialization::True; else if (classDef_ && classDef_->str() == "using") { typeStart = classDef->tokAt(3); typeEnd = typeStart; while (typeEnd->next() && typeEnd->strAt(1) != ";") { if (Token::simpleMatch(typeEnd, "decltype (")) typeEnd = typeEnd->linkAt(1); else typeEnd = typeEnd->next(); } } } std::string name() const; const std::string& type() const { return classDef ? classDef->str() : emptyString; } bool isClassType() const; bool isEnumType() const; bool isStructType() const; bool isUnionType() const; bool isTypeAlias() const { return classDef && classDef->str() == "using"; } const Token *initBaseInfo(const Token *tok, const Token *tok1); const Function* getFunction(const std::string& funcName) const; /** * Check for circulare dependencies, i.e. loops within the class hierarchy * @param ancestors list of ancestors. For internal usage only, clients should not supply this argument. * @return true if there is a circular dependency */ bool hasCircularDependencies(std::set<BaseInfo>* ancestors = nullptr) const; /** * Check for dependency * @param ancestor potential ancestor * @return true if there is a dependency */ bool findDependency(const Type* ancestor) const; bool isDerivedFrom(const std::string & ancestor) const; }; struct CPPCHECKLIB Enumerator { explicit Enumerator(const Scope * scope_) : scope(scope_) {} const Scope * scope; const Token* name{}; MathLib::bigint value{}; const Token* start{}; const Token* end{}; bool value_known{}; }; /** @brief Information about a member variable. */ class CPPCHECKLIB Variable { /** @brief flags mask used to access specific bit. */ enum { fIsMutable = (1 << 0), /** @brief mutable variable */ fIsStatic = (1 << 1), /** @brief static variable */ fIsConst = (1 << 2), /** @brief const variable */ fIsExtern = (1 << 3), /** @brief extern variable */ fIsClass = (1 << 4), /** @brief user defined type */ fIsArray = (1 << 5), /** @brief array variable */ fIsPointer = (1 << 6), /** @brief pointer variable */ fIsReference = (1 << 7), /** @brief reference variable */ fIsRValueRef = (1 << 8), /** @brief rvalue reference variable */ fHasDefault = (1 << 9), /** @brief function argument with default value */ fIsStlType = (1 << 10), /** @brief STL type ('std::') */ fIsStlString = (1 << 11), /** @brief std::string|wstring|basic_string&lt;T&gt;|u16string|u32string */ fIsFloatType = (1 << 12), /** @brief Floating point type */ fIsVolatile = (1 << 13), /** @brief volatile */ fIsSmartPointer = (1 << 14),/** @brief std::shared_ptr|unique_ptr */ fIsMaybeUnused = (1 << 15), /** @brief marked [[maybe_unused]] */ fIsInit = (1 << 16), /** @brief Is variable initialized in declaration */ }; /** * Get specified flag state. * @param flag_ flag to get state of * @return true if flag set or false in flag not set */ bool getFlag(unsigned int flag_) const { return ((mFlags & flag_) != 0); } /** * Set specified flag state. * @param flag_ flag to set state * @param state_ new state of flag */ void setFlag(unsigned int flag_, bool state_) { mFlags = state_ ? mFlags | flag_ : mFlags & ~flag_; } /** * @brief parse and save array dimension information * @param settings Platform settings and library * @param isContainer Is the array container-like? * @return true if array, false if not */ bool arrayDimensions(const Settings& settings, bool& isContainer); public: Variable(const Token *name_, const Token *start_, const Token *end_, nonneg int index_, AccessControl access_, const Type *type_, const Scope *scope_, const Settings& settings) : mNameToken(name_), mTypeStartToken(start_), mTypeEndToken(end_), mIndex(index_), mAccess(access_), mFlags(0), mType(type_), mScope(scope_) { evaluate(settings); } Variable(const Token *name_, const std::string &clangType, const Token *typeStart, const Token *typeEnd, nonneg int index_, AccessControl access_, const Type *type_, const Scope *scope_); Variable(const Variable &var, const Scope *scope); Variable(const Variable &var); ~Variable(); Variable &operator=(const Variable &var) &; /** * Get name token. * @return name token */ const Token *nameToken() const { return mNameToken; } /** * Get type start token. * The type start token doesn't account 'static' and 'const' qualifiers * E.g.: * static const int * const p = ...; * type start token ^ * @return type start token */ const Token *typeStartToken() const { return mTypeStartToken; } /** * Get type end token. * The type end token doesn't account the forward 'const' qualifier * E.g.: * static const int * const p = ...; * type end token ^ * @return type end token */ const Token *typeEndToken() const { return mTypeEndToken; } /** * Get end token of variable declaration * E.g. * int i[2][3] = ... * end token ^ * @return variable declaration end token */ const Token *declEndToken() const; /** * Get name string. * @return name string */ const std::string &name() const { // name may not exist for function arguments if (mNameToken) return mNameToken->str(); return emptyString; } /** * Get declaration ID (varId used for variable in its declaration). * @return declaration ID */ nonneg int declarationId() const { // name may not exist for function arguments if (mNameToken) return mNameToken->varId(); return 0; } /** * Get index of variable in declared order. * @return variable index */ nonneg int index() const { return mIndex; } /** * Is variable public. * @return true if public, false if not */ bool isPublic() const { return mAccess == AccessControl::Public; } /** * Is variable protected. * @return true if protected, false if not */ bool isProtected() const { return mAccess == AccessControl::Protected; } /** * Is variable private. * @return true if private, false if not */ bool isPrivate() const { return mAccess == AccessControl::Private; } /** * Is variable global. * @return true if global, false if not */ bool isGlobal() const { return mAccess == AccessControl::Global; } /** * Is variable in a namespace. * @return true if in a namespace, false if not */ // cppcheck-suppress unusedFunction bool isNamespace() const { return mAccess == AccessControl::Namespace; } /** * Is variable a function argument. * @return true if a function argument, false if not */ bool isArgument() const { return mAccess == AccessControl::Argument; } /** * Is variable local. * @return true if local, false if not */ bool isLocal() const { return (mAccess == AccessControl::Local) && !isExtern(); } /** * Is variable a member of a user-defined type. * @return true if member, false if not or unknown */ bool isMember() const; /** * Is variable mutable. * @return true if mutable, false if not */ bool isMutable() const { return getFlag(fIsMutable); } /** * Is variable volatile. * @return true if volatile, false if not */ bool isVolatile() const { return getFlag(fIsVolatile); } /** * Is variable static. * @return true if static, false if not */ bool isStatic() const { return getFlag(fIsStatic); } /** * Is variable extern. * @return true if extern, false if not */ bool isExtern() const { return getFlag(fIsExtern); } /** * Is variable const. * @return true if const, false if not */ bool isConst() const { return getFlag(fIsConst); } /** * Is variable a throw type. * @return true if throw type, false if not */ bool isThrow() const { return mAccess == AccessControl::Throw; } /** * Is variable a user defined (or unknown) type. * @return true if user defined type, false if not */ bool isClass() const { return getFlag(fIsClass); } /** * Is variable an array. * @return true if array, false if not */ bool isArray() const { return getFlag(fIsArray) && !getFlag(fIsPointer); } /** * Is pointer variable. * @return true if pointer, false otherwise */ bool isPointer() const { return getFlag(fIsPointer); } /** * Is variable a pointer to an array * @return true if pointer to array, false otherwise */ bool isPointerToArray() const { return isPointer() && getFlag(fIsArray); } /** * Is variable an array of pointers * @return true if array or pointers, false otherwise */ bool isPointerArray() const; /** * Is array or pointer variable. * @return true if pointer or array, false otherwise */ bool isArrayOrPointer() const { return getFlag(fIsArray) || getFlag(fIsPointer); } /** * Is reference variable. * @return true if reference, false otherwise */ bool isReference() const { return getFlag(fIsReference); } /** * Is reference variable. * @return true if reference, false otherwise */ bool isRValueReference() const { return getFlag(fIsRValueRef); } /** * Is variable unsigned. * @return true only if variable _is_ unsigned. if the sign is unknown, false is returned. */ bool isUnsigned() const; /** * Does variable have a default value. * @return true if has a default falue, false if not */ bool hasDefault() const { return getFlag(fHasDefault); } /** * Is variable initialized in its declaration * @return true if variable declaration contains initialization */ bool isInit() const { return getFlag(fIsInit); } /** * Get Type pointer of known type. * @return pointer to type if known, NULL if not known */ const Type *type() const { return mType; } /** * Get Scope pointer of known type. * @return pointer to type scope if known, NULL if not known */ const Scope *typeScope() const { return mType ? mType->classScope : nullptr; } /** * Get Scope pointer of enclosing scope. * @return pointer to enclosing scope */ const Scope *scope() const { return mScope; } /** * Get array dimensions. * @return array dimensions vector */ const std::vector<Dimension> &dimensions() const { return mDimensions; } /** * Get array dimension length. * @return length of dimension */ MathLib::bigint dimension(nonneg int index_) const { return mDimensions.at(index_).num; } /** * Get array dimension known. * @return length of dimension known */ bool dimensionKnown(nonneg int index_) const { return mDimensions.at(index_).known; } void setDimensions(const std::vector<Dimension> &dimensions_) { mDimensions = dimensions_; } /** * Checks if the variable is an STL type ('std::') * E.g.: * std::string s; * ... * sVar->isStlType() == true * @return true if it is an stl type and its type matches any of the types in 'stlTypes' */ bool isStlType() const { return getFlag(fIsStlType); } /** * Checks if the variable is an STL type ('std::') * E.g.: * std::string s; * ... * sVar->isStlType() == true * @return true if it is an stl type and its type matches any of the types in 'stlTypes' */ bool isStlStringType() const { return getFlag(fIsStlString); } bool isStlStringViewType() const; bool isSmartPointer() const { return getFlag(fIsSmartPointer); } const Type* smartPointerType() const; const Type* iteratorType() const; /** * Checks if the variable is of any of the STL types passed as arguments ('std::') * E.g.: * std::string s; * ... * const char *str[] = {"string", "wstring"}; * sVar->isStlType(str) == true * @param stlType stl type * @return true if it is an stl type and its type matches any of the types in 'stlTypes' */ bool isStlType(const std::string& stlType) const { return isStlType() && stlType==mTypeStartToken->strAt(2); } /** * Checks if the variable is of any of the STL types passed as arguments ('std::') * E.g.: * std::string s; * ... * const std::set<std::string> str = make_container< std::set<std::string> >() << "string" << "wstring"; * sVar->isStlType(str) == true * @param stlTypes set of stl types * @return true if it is an stl type and its type matches any of the types in 'stlTypes' */ bool isStlType(const std::set<std::string>& stlTypes) const { return isStlType() && stlTypes.find(mTypeStartToken->strAt(2))!=stlTypes.end(); } /** * Determine whether it's a floating number type * @return true if the type is known and it's a floating type (float, double and long double) or a pointer/array to it */ bool isFloatingType() const { return getFlag(fIsFloatType); } /** * Determine whether it's an enumeration type * @return true if the type is known and it's an enumeration type */ bool isEnumType() const { return type() && type()->isEnumType(); } bool isMaybeUnused() const { return getFlag(fIsMaybeUnused); } const ValueType *valueType() const { return mValueType; } void setValueType(const ValueType &valueType); AccessControl accessControl() const { return mAccess; } std::string getTypeName() const; private: // only symbol database can change the type friend class SymbolDatabase; /** * Set Type pointer to known type. * @param t type */ void type(const Type * t) { mType = t; } /** @brief variable name token */ const Token *mNameToken; /** @brief variable type start token */ const Token *mTypeStartToken; /** @brief variable type end token */ const Token *mTypeEndToken; /** @brief order declared */ nonneg int mIndex; /** @brief what section is this variable declared in? */ AccessControl mAccess; // public/protected/private /** @brief flags */ unsigned int mFlags; /** @brief pointer to user defined type info (for known types) */ const Type *mType; /** @brief pointer to scope this variable is in */ const Scope *mScope; const ValueType* mValueType{}; /** @brief array dimensions */ std::vector<Dimension> mDimensions; /** @brief fill in information, depending on Tokens given at instantiation */ void evaluate(const Settings& settings); }; class CPPCHECKLIB Function { // only symbol database can change this friend class SymbolDatabase; /** @brief flags mask used to access specific bit. */ enum { fHasBody = (1 << 0), ///< @brief has implementation fIsInline = (1 << 1), ///< @brief implementation in class definition fIsConst = (1 << 2), ///< @brief is const fHasVirtualSpecifier = (1 << 3), ///< @brief does declaration contain 'virtual' specifier fIsPure = (1 << 4), ///< @brief is pure virtual fIsStatic = (1 << 5), ///< @brief is static fIsStaticLocal = (1 << 6), ///< @brief is static local fIsExtern = (1 << 7), ///< @brief is extern fIsFriend = (1 << 8), ///< @brief is friend fIsExplicit = (1 << 9), ///< @brief is explicit fIsDefault = (1 << 10), ///< @brief is default fIsDelete = (1 << 11), ///< @brief is delete fHasOverrideSpecifier = (1 << 12), ///< @brief does declaration contain 'override' specifier? fHasFinalSpecifier = (1 << 13), ///< @brief does declaration contain 'final' specifier? fIsNoExcept = (1 << 14), ///< @brief is noexcept fIsThrow = (1 << 15), ///< @brief is throw fIsOperator = (1 << 16), ///< @brief is operator fHasLvalRefQual = (1 << 17), ///< @brief has & lvalue ref-qualifier fHasRvalRefQual = (1 << 18), ///< @brief has && rvalue ref-qualifier fIsVariadic = (1 << 19), ///< @brief is variadic fIsVolatile = (1 << 20), ///< @brief is volatile fHasTrailingReturnType = (1 << 21), ///< @brief has trailing return type fIsEscapeFunction = (1 << 22), ///< @brief Function throws or exits fIsInlineKeyword = (1 << 23), ///< @brief Function has "inline" keyword fIsConstexpr = (1 << 24), ///< @brief is constexpr }; /** * Get specified flag state. * @param flag flag to get state of * @return true if flag set or false in flag not set */ bool getFlag(unsigned int flag) const { return ((mFlags & flag) != 0); } /** * Set specified flag state. * @param flag flag to set state * @param state new state of flag */ void setFlag(unsigned int flag, bool state) { mFlags = state ? mFlags | flag : mFlags & ~flag; } public: enum Type : std::uint8_t { eConstructor, eCopyConstructor, eMoveConstructor, eOperatorEqual, eDestructor, eFunction, eLambda }; Function(const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef); Function(const Token *tokenDef, const std::string &clangType); const std::string &name() const { return tokenDef->str(); } std::string fullName() const; nonneg int argCount() const { return argumentList.size(); } nonneg int minArgCount() const { return argumentList.size() - initArgCount; } const Variable* getArgumentVar(nonneg int num) const; nonneg int initializedArgCount() const { return initArgCount; } void addArguments(const SymbolDatabase *symbolDatabase, const Scope *scope); /** @brief check if this function is virtual in the base classes */ bool isImplicitlyVirtual(bool defaultVal = false) const; std::vector<const Function*> getOverloadedFunctions() const; /** @brief get function in base class that is overridden */ const Function *getOverriddenFunction(bool *foundAllBaseClasses = nullptr) const; bool isLambda() const { return type==eLambda; } bool isConstructor() const { return type==eConstructor || type==eCopyConstructor || type==eMoveConstructor; } bool isDestructor() const { return type==eDestructor; } bool isAttributeConstructor() const { return tokenDef->isAttributeConstructor(); } bool isAttributeDestructor() const { return tokenDef->isAttributeDestructor(); } bool isAttributePure() const { return tokenDef->isAttributePure(); } bool isAttributeConst() const { return tokenDef->isAttributeConst(); } bool isAttributeNoreturn() const { return tokenDef->isAttributeNoreturn(); } bool isAttributeNothrow() const { return tokenDef->isAttributeNothrow(); } bool isAttributeNodiscard() const { return tokenDef->isAttributeNodiscard(); } bool hasBody() const { return getFlag(fHasBody); } bool isInline() const { return getFlag(fIsInline); } bool isConst() const { return getFlag(fIsConst); } bool hasVirtualSpecifier() const { return getFlag(fHasVirtualSpecifier); } bool isPure() const { return getFlag(fIsPure); } bool isStatic() const { return getFlag(fIsStatic); } bool isStaticLocal() const { return getFlag(fIsStaticLocal); } bool isExtern() const { return getFlag(fIsExtern); } bool isFriend() const { return getFlag(fIsFriend); } bool isExplicit() const { return getFlag(fIsExplicit); } bool isDefault() const { return getFlag(fIsDefault); } bool isDelete() const { return getFlag(fIsDelete); } bool isNoExcept() const { return getFlag(fIsNoExcept); } bool isThrow() const { return getFlag(fIsThrow); } bool hasOverrideSpecifier() const { return getFlag(fHasOverrideSpecifier); } bool hasFinalSpecifier() const { return getFlag(fHasFinalSpecifier); } bool isOperator() const { return getFlag(fIsOperator); } bool hasLvalRefQualifier() const { return getFlag(fHasLvalRefQual); } bool hasRvalRefQualifier() const { return getFlag(fHasRvalRefQual); } bool isVariadic() const { return getFlag(fIsVariadic); } bool isVolatile() const { return getFlag(fIsVolatile); } bool hasTrailingReturnType() const { return getFlag(fHasTrailingReturnType); } void hasBody(bool state) { setFlag(fHasBody, state); } bool isInlineKeyword() const { return getFlag(fIsInlineKeyword); } bool isEscapeFunction() const { return getFlag(fIsEscapeFunction); } void isEscapeFunction(bool state) { setFlag(fIsEscapeFunction, state); } bool isConstexpr() const { return getFlag(fIsConstexpr); } void isConstexpr(bool state) { setFlag(fIsConstexpr, state); } bool isSafe(const Settings &settings) const; const Token* tokenDef{}; ///< function name token in class definition const Token* argDef{}; ///< function argument start '(' in class definition const Token* token{}; ///< function name token in implementation const Token* arg{}; ///< function argument start '(' const Token* retDef{}; ///< function return type token const ::Type* retType{}; ///< function return type const Scope* functionScope{}; ///< scope of function body const Scope* nestedIn{}; ///< Scope the function is declared in std::list<Variable> argumentList; ///< argument list, must remain list due to clangimport usage! nonneg int initArgCount{}; ///< number of args with default values Type type = eFunction; ///< constructor, destructor, ... const Token* noexceptArg{}; ///< noexcept token const Token* throwArg{}; ///< throw token const Token* templateDef{}; ///< points to 'template <' before function const Token* functionPointerUsage{}; ///< function pointer usage AccessControl access{}; ///< public/protected/private bool argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, nonneg int path_length) const; static bool returnsConst(const Function* function, bool unknown = false); static bool returnsPointer(const Function* function, bool unknown = false); static bool returnsReference(const Function* function, bool unknown = false, bool includeRValueRef = false); static bool returnsStandardType(const Function* function, bool unknown = false); static bool returnsVoid(const Function* function, bool unknown = false); static std::vector<const Token*> findReturns(const Function* f); const Token* returnDefEnd() const { if (this->hasTrailingReturnType()) return Token::findmatch(retDef, "{|;"); return tokenDef; } /** * @return token to ":" if the function is a constructor * and it contains member initialization otherwise a nullptr is returned */ const Token * constructorMemberInitialization() const; private: /** Recursively determine if this function overrides a virtual function in a base class */ const Function * getOverriddenFunctionRecursive(const ::Type* baseType, bool *foundAllBaseClasses) const; unsigned int mFlags{}; void isInline(bool state) { setFlag(fIsInline, state); } void isConst(bool state) { setFlag(fIsConst, state); } void hasVirtualSpecifier(bool state) { setFlag(fHasVirtualSpecifier, state); } void isPure(bool state) { setFlag(fIsPure, state); } void isStatic(bool state) { setFlag(fIsStatic, state); } void isStaticLocal(bool state) { setFlag(fIsStaticLocal, state); } void isExtern(bool state) { setFlag(fIsExtern, state); } void isFriend(bool state) { setFlag(fIsFriend, state); } void isExplicit(bool state) { setFlag(fIsExplicit, state); } void isDefault(bool state) { setFlag(fIsDefault, state); } void isDelete(bool state) { setFlag(fIsDelete, state); } void isNoExcept(bool state) { setFlag(fIsNoExcept, state); } void isThrow(bool state) { setFlag(fIsThrow, state); } void isOperator(bool state) { setFlag(fIsOperator, state); } void hasLvalRefQualifier(bool state) { setFlag(fHasLvalRefQual, state); } void hasRvalRefQualifier(bool state) { setFlag(fHasRvalRefQual, state); } void isVariadic(bool state) { setFlag(fIsVariadic, state); } void isVolatile(bool state) { setFlag(fIsVolatile, state); } void hasTrailingReturnType(bool state) { setFlag(fHasTrailingReturnType, state); } void isInlineKeyword(bool state) { setFlag(fIsInlineKeyword, state); } const Token *setFlags(const Token *tok1, const Scope *scope); }; class CPPCHECKLIB Scope { // let tests access private function for testing friend class TestSymbolDatabase; public: struct UsingInfo { const Token *start; const Scope *scope; }; enum ScopeType : std::uint8_t { eGlobal, eClass, eStruct, eUnion, eNamespace, eFunction, eIf, eElse, eFor, eWhile, eDo, eSwitch, eUnconditional, eTry, eCatch, eLambda, eEnum }; Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_); Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_, ScopeType type_, const Token *start_); const SymbolDatabase* check{}; std::string className; const Token* classDef{}; ///< class/struct/union/namespace token const Token* bodyStart{}; ///< '{' token const Token* bodyEnd{}; ///< '}' token std::list<Function> functionList; std::multimap<std::string, const Function *> functionMap; std::list<Variable> varlist; const Scope* nestedIn{}; std::vector<Scope *> nestedList; nonneg int numConstructors{}; nonneg int numCopyOrMoveConstructors{}; std::vector<UsingInfo> usingList; ScopeType type{}; Type* definedType{}; std::map<std::string, Type*> definedTypesMap; std::vector<const Token *> bodyStartList; // function specific fields const Scope* functionOf{}; ///< scope this function belongs to Function* function{}; ///< function info for this function // enum specific fields const Token* enumType{}; bool enumClass{}; std::vector<Enumerator> enumeratorList; void setBodyStartEnd(const Token *start) { bodyStart = start; bodyEnd = start ? start->link() : nullptr; if (start) bodyStartList.push_back(start); } bool isAnonymous() const { // TODO: Check if class/struct is anonymous return className.size() > 9 && startsWith(className,"Anonymous") && std::isdigit(className[9]); } const Enumerator * findEnumerator(const std::string & name) const { auto it = std::find_if(enumeratorList.cbegin(), enumeratorList.cend(), [&](const Enumerator& i) { return i.name->str() == name; }); return it == enumeratorList.end() ? nullptr : &*it; } bool isNestedIn(const Scope * outer) const { if (!outer) return false; if (outer == this) return true; const Scope * parent = nestedIn; while (outer != parent && parent) parent = parent->nestedIn; return parent && parent == outer; } static Function* nestedInFunction(const Scope* scope) { while (scope) { if (scope->type == Scope::eFunction) break; scope = scope->nestedIn; } if (!scope) return nullptr; return scope->function; } bool isClassOrStruct() const { return (type == eClass || type == eStruct); } bool isClassOrStructOrUnion() const { return (type == eClass || type == eStruct || type == eUnion); } bool isExecutable() const { return type != eClass && type != eStruct && type != eUnion && type != eGlobal && type != eNamespace && type != eEnum; } bool isLoopScope() const { return type == Scope::ScopeType::eFor || type == Scope::ScopeType::eWhile || type == Scope::ScopeType::eDo; } bool isLocal() const { return (type == eIf || type == eElse || type == eFor || type == eWhile || type == eDo || type == eSwitch || type == eUnconditional || type == eTry || type == eCatch); } // Is there lambda/inline function(s) in this scope? bool hasInlineOrLambdaFunction(const Token** tokStart = nullptr) const; /** * @brief find a function * @param tok token of function call * @param requireConst if const refers to a const variable only const methods should be matched * @return pointer to function if found or NULL if not found */ const Function *findFunction(const Token *tok, bool requireConst=false, Reference ref=Reference::None) const; const Scope *findRecordInNestedList(const std::string & name, bool isC = false) const; Scope *findRecordInNestedList(const std::string & name, bool isC = false); const Type* findType(const std::string& name) const; Type* findType(const std::string& name); /** * @brief find if name is in nested list * @param name name of nested scope */ Scope *findInNestedListRecursive(const std::string & name); void addVariable(const Token *token_, const Token *start_, const Token *end_, AccessControl access_, const Type *type_, const Scope *scope_, const Settings& settings); /** @brief initialize varlist */ void getVariableList(const Settings& settings); const Function *getDestructor() const; void addFunction(Function func) { functionList.push_back(std::move(func)); const Function * back = &functionList.back(); functionMap.insert(make_pair(back->tokenDef->str(), back)); } AccessControl defaultAccess() const; /** * @brief check if statement is variable declaration and add it if it is * @param tok pointer to start of statement * @param varaccess access control of statement * @param settings Settings * @return pointer to last token */ const Token *checkVariable(const Token *tok, AccessControl varaccess, const Settings& settings); /** * @brief get variable from name * @param varname name of variable * @return pointer to variable */ const Variable *getVariable(const std::string &varname) const; const Token * addEnum(const Token * tok); const Scope *findRecordInBase(const std::string &name) const; std::vector<const Scope*> findAssociatedScopes() const; private: /** * @brief helper function for getVariableList() * @param tok pointer to token to check * @param vartok populated with pointer to the variable token, if found * @param typetok populated with pointer to the type token, if found * @return true if tok points to a variable declaration, false otherwise */ bool isVariableDeclaration(const Token* tok, const Token*& vartok, const Token*& typetok) const; void findFunctionInBase(const std::string & name, nonneg int args, std::vector<const Function *> & matches) const; /** @brief initialize varlist */ void getVariableList(const Settings& settings, const Token *start, const Token *end); }; /** Value type */ class CPPCHECKLIB ValueType { public: enum Sign : std::uint8_t { UNKNOWN_SIGN, SIGNED, UNSIGNED } sign = UNKNOWN_SIGN; enum Type : std::uint8_t { UNKNOWN_TYPE, POD, NONSTD, RECORD, SMART_POINTER, CONTAINER, ITERATOR, VOID, BOOL, CHAR, SHORT, WCHAR_T, INT, LONG, LONGLONG, UNKNOWN_INT, FLOAT, DOUBLE, LONGDOUBLE } type = UNKNOWN_TYPE; nonneg int bits{}; ///< bitfield bitcount nonneg int pointer{}; ///< 0=>not pointer, 1=>*, 2=>**, 3=>***, etc nonneg int constness{}; ///< bit 0=data, bit 1=*, bit 2=** nonneg int volatileness{}; ///< bit 0=data, bit 1=*, bit 2=** Reference reference = Reference::None; ///< Is the outermost indirection of this type a reference or rvalue ///< reference or not? pointer=2, Reference=LValue would be a T**& const Scope* typeScope{}; ///< if the type definition is seen this point out the type scope const ::Type* smartPointerType{}; ///< Smart pointer type const Token* smartPointerTypeToken{}; ///< Smart pointer type token const Library::SmartPointer* smartPointer{}; ///< Smart pointer const Library::Container* container{}; ///< If the type is a container defined in a cfg file, this is the used ///< container const Token* containerTypeToken{}; ///< The container type token. the template argument token that defines the ///< container element type. std::string originalTypeName; ///< original type name as written in the source code. eg. this might be "uint8_t" ///< when type is CHAR. ErrorPath debugPath; ///< debug path to the type ValueType() = default; ValueType(Sign s, Type t, nonneg int p) : sign(s), type(t), pointer(p) {} ValueType(Sign s, Type t, nonneg int p, nonneg int c) : sign(s), type(t), pointer(p), constness(c) {} ValueType(Sign s, Type t, nonneg int p, nonneg int c, nonneg int v) : sign(s), type(t), pointer(p), constness(c), volatileness(v) {} ValueType(Sign s, Type t, nonneg int p, nonneg int c, std::string otn) : sign(s), type(t), pointer(p), constness(c), originalTypeName(std::move(otn)) {} static ValueType parseDecl(const Token *type, const Settings &settings); static Type typeFromString(const std::string &typestr, bool longType); enum class MatchResult : std::uint8_t { UNKNOWN, SAME, FALLBACK1, FALLBACK2, NOMATCH }; static MatchResult matchParameter(const ValueType *call, const ValueType *func); static MatchResult matchParameter(const ValueType *call, const Variable *callVar, const Variable *funcVar); bool isPrimitive() const { return (type >= ValueType::Type::BOOL); } bool isIntegral() const { return (type >= ValueType::Type::BOOL && type <= ValueType::Type::UNKNOWN_INT); } bool isFloat() const { return (type >= ValueType::Type::FLOAT && type <= ValueType::Type::LONGDOUBLE); } bool fromLibraryType(const std::string &typestr, const Settings &settings); bool isEnum() const { return typeScope && typeScope->type == Scope::eEnum; } bool isConst(nonneg int indirect = 0) const; bool isVolatile(nonneg int indirect = 0) const; MathLib::bigint typeSize(const Platform &platform, bool p=false) const; /// Check if type is the same ignoring const and references bool isTypeEqual(const ValueType* that) const; std::string str() const; std::string dump() const; void setDebugPath(const Token* tok, SourceLocation ctx, const SourceLocation &local = SourceLocation::current()); }; class CPPCHECKLIB SymbolDatabase { friend class TestSymbolDatabase; public: SymbolDatabase(Tokenizer& tokenizer, const Settings& settings, ErrorLogger& errorLogger); ~SymbolDatabase(); /** @brief Information about all namespaces/classes/structures */ std::list<Scope> scopeList; /** @brief Fast access to function scopes */ std::vector<const Scope*> functionScopes; /** @brief Fast access to class and struct scopes */ std::vector<const Scope*> classAndStructScopes; /** @brief Fast access to types */ std::list<Type> typeList; /** * @brief find a variable type if it's a user defined type * @param start scope to start looking in * @param typeTok token containing variable type * @return pointer to type if found or NULL if not found */ const Type* findVariableType(const Scope* start, const Token* typeTok) const; /** * @brief find a function * @param tok token of function call * @return pointer to function if found or NULL if not found */ const Function* findFunction(const Token* tok) const; /** For unit testing only */ const Scope* findScopeByName(const std::string& name) const; const Type* findType(const Token* startTok, const Scope* startScope, bool lookOutside = false) const; Type* findType(const Token* startTok, Scope* startScope, bool lookOutside = false) { return const_cast<Type*>(this->findType(startTok, static_cast<const Scope*>(startScope), lookOutside)); } const Scope *findScope(const Token *tok, const Scope *startScope) const; Scope *findScope(const Token *tok, Scope *startScope) { return const_cast<Scope *>(this->findScope(tok, static_cast<const Scope *>(startScope))); } // cppcheck-suppress unusedFunction bool isVarId(nonneg int varid) const { return varid < mVariableList.size(); } const Variable *getVariableFromVarId(nonneg int varId) const { return mVariableList.at(varId); } const std::vector<const Variable *> & variableList() const { return mVariableList; } /** * @brief output a debug message */ void debugMessage(const Token *tok, const std::string &type, const std::string &msg) const; void returnImplicitIntError(const Token *tok) const; void printOut(const char * title = nullptr) const; void printVariable(const Variable *var, const char *indent) const; void printXml(std::ostream &out) const; /* * @brief Do a sanity check */ void validate() const; /** Set valuetype in provided tokenlist */ void setValueTypeInTokenList(bool reportDebugWarnings, Token *tokens=nullptr); /** * Calculates sizeof value for given type. * @param type Token which will contain e.g. "int", "*", or string. * @return sizeof for given type, or 0 if it can't be calculated. */ nonneg int sizeOfType(const Token *type) const; /** Set array dimensions when valueflow analysis is completed */ void setArrayDimensionsUsingValueFlow(); // cppcheck-suppress functionConst // has side effects void clangSetVariables(const std::vector<const Variable *> &variableList); void createSymbolDatabaseExprIds(); /* returns the opening { if tok points to enum */ static const Token* isEnumDefinition(const Token* tok); private: friend class Scope; friend class Function; // Create symboldatabase... void createSymbolDatabaseFindAllScopes(); void createSymbolDatabaseClassInfo(); void createSymbolDatabaseVariableInfo(); void createSymbolDatabaseCopyAndMoveConstructors(); void createSymbolDatabaseFunctionScopes(); void createSymbolDatabaseClassAndStructScopes(); void createSymbolDatabaseFunctionReturnTypes(); void createSymbolDatabaseNeedInitialization(); void createSymbolDatabaseVariableSymbolTable(); void createSymbolDatabaseSetScopePointers(); void createSymbolDatabaseSetFunctionPointers(bool firstPass); // cppcheck-suppress functionConst // has side effects void createSymbolDatabaseSetVariablePointers(); // cppcheck-suppress functionConst void createSymbolDatabaseSetTypePointers(); void createSymbolDatabaseSetSmartPointerType(); void createSymbolDatabaseEnums(); // cppcheck-suppress functionConst // has side effects void createSymbolDatabaseEscapeFunctions(); // cppcheck-suppress functionConst // has side effects // cppcheck-suppress functionConst void createSymbolDatabaseIncompleteVars(); void debugSymbolDatabase() const; void addClassFunction(Scope *&scope, const Token *&tok, const Token *argStart); static Function *addGlobalFunctionDecl(Scope*& scope, const Token* tok, const Token *argStart, const Token* funcStart); Function *addGlobalFunction(Scope*& scope, const Token*& tok, const Token *argStart, const Token* funcStart); void addNewFunction(Scope *&scope, const Token *&tok); bool isFunction(const Token *tok, const Scope* outerScope, const Token *&funcStart, const Token *&argStart, const Token*& declEnd) const; const Type *findTypeInNested(const Token *startTok, const Scope *startScope) const; const Scope *findNamespace(const Token * tok, const Scope * scope) const; static Function *findFunctionInScope(const Token *func, const Scope *ns, const std::string & path, nonneg int path_length); static const Type *findVariableTypeInBase(const Scope *scope, const Token *typeTok); using MemberIdMap = std::map<unsigned int, unsigned int>; using VarIdMap = std::map<unsigned int, MemberIdMap>; void fixVarId(VarIdMap & varIds, const Token * vartok, Token * membertok, const Variable * membervar); /** Whether the token is a keyword as defined in http://en.cppreference.com/w/c/keyword and http://en.cppreference.com/w/cpp/keyword*/ static bool isReservedName(const Token* tok); const Enumerator * findEnumerator(const Token * tok, std::set<std::string>& tokensThatAreNotEnumeratorValues) const; void setValueType(Token* tok, const ValueType& valuetype, const SourceLocation &loc = SourceLocation::current()); void setValueType(Token* tok, const Variable& var, const SourceLocation &loc = SourceLocation::current()); void setValueType(Token* tok, const Enumerator& enumerator, const SourceLocation &loc = SourceLocation::current()); void validateExecutableScopes() const; /** * @brief Check variable list, e.g. variables w/o scope */ void validateVariables() const; Tokenizer& mTokenizer; const Settings &mSettings; ErrorLogger &mErrorLogger; /** variable symbol table */ std::vector<const Variable *> mVariableList; /** list for missing types */ std::list<Type> mBlankTypes; ValueType::Sign mDefaultSignedness; }; //--------------------------------------------------------------------------- #endif // symboldatabaseH
47,699
C++
.h
1,264
31.537184
180
0.636977
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,484
config.h
danmar_cppcheck/lib/config.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef configH #define configH #ifdef MAXTIME #error "MAXTIME is no longer supported - please use command-line options --checks-max-time=, --template-max-time= and --typedef-max-time= instead" #endif #ifdef _WIN32 # ifdef CPPCHECKLIB_EXPORT # define CPPCHECKLIB __declspec(dllexport) # elif defined(CPPCHECKLIB_IMPORT) # define CPPCHECKLIB __declspec(dllimport) # else # define CPPCHECKLIB # endif #else # define CPPCHECKLIB #endif // MS Visual C++ memory leak debug tracing #if !defined(DISABLE_CRTDBG_MAP_ALLOC) && defined(_MSC_VER) && defined(_DEBUG) # define _CRTDBG_MAP_ALLOC # include <crtdbg.h> #endif // compatibility macros #ifndef __has_builtin #define __has_builtin(x) 0 #endif #ifndef __has_include #define __has_include(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef __has_feature #define __has_feature(x) 0 #endif // C++11 noexcept #if defined(__cpp_noexcept_function_type) || \ (defined(__GNUC__) && (__GNUC__ >= 5)) \ || defined(__clang__) \ || defined(__CPPCHECK__) # define NOEXCEPT noexcept #else # define NOEXCEPT #endif // C++11 noreturn #if __has_cpp_attribute (noreturn) \ || (defined(__GNUC__) && (__GNUC__ >= 5)) \ || defined(__clang__) \ || defined(__CPPCHECK__) # define NORETURN [[noreturn]] #elif defined(__GNUC__) # define NORETURN __attribute__((noreturn)) #else # define NORETURN #endif // fallthrough #if __cplusplus >= 201703L && __has_cpp_attribute (fallthrough) # define FALLTHROUGH [[fallthrough]] #elif defined(__clang__) # define FALLTHROUGH [[clang::fallthrough]] #elif (defined(__GNUC__) && (__GNUC__ >= 7)) # define FALLTHROUGH __attribute__((fallthrough)) #else # define FALLTHROUGH #endif // unused #if __cplusplus >= 201703L && __has_cpp_attribute (maybe_unused) # define UNUSED [[maybe_unused]] #elif defined(__GNUC__) \ || defined(__clang__) \ || defined(__CPPCHECK__) # define UNUSED __attribute__((unused)) #else # define UNUSED #endif // warn_unused #if __has_cpp_attribute (gnu::warn_unused) || \ (defined(__clang__) && (__clang_major__ >= 15)) # define WARN_UNUSED [[gnu::warn_unused]] #else # define WARN_UNUSED #endif // deprecated #if defined(__GNUC__) \ || defined(__clang__) \ || defined(__CPPCHECK__) # define DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) # define DEPRECATED __declspec(deprecated) #else # define DEPRECATED #endif // TODO: GCC apparently also supports this but there is no documentation on it // returns_nonnull #if __has_cpp_attribute (gnu::returns_nonnull) # define RET_NONNULL [[gnu::returns_nonnull]] #elif (defined(__clang__) && ((__clang_major__ > 3) || ((__clang_major__ == 3) && (__clang_minor__ >= 7)))) # define RET_NONNULL __attribute__((returns_nonnull)) #else # define RET_NONNULL #endif #define REQUIRES(msg, ...) class=typename std::enable_if<__VA_ARGS__::value>::type #include <string> static const std::string emptyString; // Use the nonneg macro when you want to assert that a variable/argument is not negative #ifdef __CPPCHECK__ #define nonneg __cppcheck_low__(0) #elif defined(NONNEG) // Enable non-negative values checking // TODO : investigate using annotations/contracts for stronger value checking #define nonneg unsigned #else // Disable non-negative values checking #define nonneg #endif #if __has_feature(address_sanitizer) #define ASAN 1 #endif #ifndef ASAN #ifdef __SANITIZE_ADDRESS__ #define ASAN 1 #else #define ASAN 0 #endif #endif #if defined(_WIN32) #define HAS_THREADING_MODEL_THREAD #define STDCALL __stdcall #elif ((defined(__GNUC__) || defined(__sun)) && !defined(__MINGW32__)) || defined(__CPPCHECK__) #define HAS_THREADING_MODEL_FORK #if !defined(DISALLOW_THREAD_EXECUTOR) #define HAS_THREADING_MODEL_THREAD #endif #define STDCALL #else #error "No threading model defined" #endif #define STRINGISIZE(...) #__VA_ARGS__ #ifdef __clang__ #define SUPPRESS_WARNING_PUSH(warning) _Pragma("clang diagnostic push") _Pragma(STRINGISIZE(clang diagnostic ignored warning)) #define SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") #define SUPPRESS_WARNING_GCC_PUSH(warning) #define SUPPRESS_WARNING_GCC_POP #define SUPPRESS_WARNING_CLANG_PUSH(warning) SUPPRESS_WARNING_PUSH(warning) #define SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_POP #elif defined(__GNUC__) #define SUPPRESS_WARNING_PUSH(warning) _Pragma("GCC diagnostic push") _Pragma(STRINGISIZE(GCC diagnostic ignored warning)) #define SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") #define SUPPRESS_WARNING_GCC_PUSH(warning) SUPPRESS_WARNING_PUSH(warning) #define SUPPRESS_WARNING_GCC_POP SUPPRESS_WARNING_POP #define SUPPRESS_WARNING_CLANG_PUSH(warning) #define SUPPRESS_WARNING_CLANG_POP #else #define SUPPRESS_WARNING_PUSH(warning) #define SUPPRESS_WARNING_POP #define SUPPRESS_WARNING_GCC_PUSH(warning) #define SUPPRESS_WARNING_GCC_POP #define SUPPRESS_WARNING_CLANG_PUSH(warning) #define SUPPRESS_WARNING_CLANG_POP #endif #if !defined(NO_WINDOWS_SEH) && defined(_WIN32) && defined(_MSC_VER) #define USE_WINDOWS_SEH #endif // TODO: __GLIBC__ is dependent on the features.h include and not a built-in compiler define, so it might be problematic to depend on it #if !defined(NO_UNIX_BACKTRACE_SUPPORT) && defined(__GNUC__) && defined(__GLIBC__) && !defined(__CYGWIN__) && !defined(__MINGW32__) && !defined(__NetBSD__) && !defined(__SVR4) && !defined(__QNX__) #define USE_UNIX_BACKTRACE_SUPPORT #endif #if !defined(NO_UNIX_SIGNAL_HANDLING) && defined(__GNUC__) && !defined(__MINGW32__) && !defined(__OS2__) #define USE_UNIX_SIGNAL_HANDLING #endif #endif // configH
6,371
C++
.h
187
32.604278
196
0.727952
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,485
programmemory.h
danmar_cppcheck/lib/programmemory.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GUARD_PROGRAMMEMORY_H #define GUARD_PROGRAMMEMORY_H #include "config.h" #include "mathlib.h" #include "vfvalue.h" // needed for alias #include <cstddef> #include <functional> #include <map> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> class Scope; class Token; class Settings; // Class used to handle heterogeneous lookup in unordered_map(since we can't use C++20 yet) struct ExprIdToken { const Token* tok = nullptr; nonneg int exprid = 0; ExprIdToken() = default; // cppcheck-suppress noExplicitConstructor // NOLINTNEXTLINE(google-explicit-constructor) ExprIdToken(const Token* tok); // TODO: Make this constructor only available from ProgramMemory // cppcheck-suppress noExplicitConstructor // NOLINTNEXTLINE(google-explicit-constructor) ExprIdToken(nonneg int exprid) : exprid(exprid) {} nonneg int getExpressionId() const; bool operator==(const ExprIdToken& rhs) const { return getExpressionId() == rhs.getExpressionId(); } bool operator<(const ExprIdToken& rhs) const { return getExpressionId() < rhs.getExpressionId(); } template<class T, class U> friend bool operator!=(const T& lhs, const U& rhs) { return !(lhs == rhs); } template<class T, class U> friend bool operator<=(const T& lhs, const U& rhs) { return !(lhs > rhs); } template<class T, class U> friend bool operator>(const T& lhs, const U& rhs) { return rhs < lhs; } template<class T, class U> friend bool operator>=(const T& lhs, const U& rhs) { return !(lhs < rhs); } const Token& operator*() const NOEXCEPT { return *tok; } const Token* operator->() const NOEXCEPT { return tok; } struct Hash { std::size_t operator()(ExprIdToken etok) const; }; }; struct CPPCHECKLIB ProgramMemory { using Map = std::unordered_map<ExprIdToken, ValueFlow::Value, ExprIdToken::Hash>; ProgramMemory() : mValues(new Map()) {} explicit ProgramMemory(Map values) : mValues(new Map(std::move(values))) {} void setValue(const Token* expr, const ValueFlow::Value& value); const ValueFlow::Value* getValue(nonneg int exprid, bool impossible = false) const; bool getIntValue(nonneg int exprid, MathLib::bigint& result) const; void setIntValue(const Token* expr, MathLib::bigint value, bool impossible = false); bool getContainerSizeValue(nonneg int exprid, MathLib::bigint& result) const; bool getContainerEmptyValue(nonneg int exprid, MathLib::bigint& result) const; void setContainerSizeValue(const Token* expr, MathLib::bigint value, bool isEqual = true); void setUnknown(const Token* expr); bool getTokValue(nonneg int exprid, const Token*& result) const; bool hasValue(nonneg int exprid); const ValueFlow::Value& at(nonneg int exprid) const; ValueFlow::Value& at(nonneg int exprid); void erase_if(const std::function<bool(const ExprIdToken&)>& pred); void swap(ProgramMemory &pm) NOEXCEPT; void clear(); bool empty() const; void replace(ProgramMemory pm); Map::const_iterator begin() const { return mValues->cbegin(); } Map::const_iterator end() const { return mValues->cend(); } friend bool operator==(const ProgramMemory& x, const ProgramMemory& y) { return x.mValues == y.mValues; } friend bool operator!=(const ProgramMemory& x, const ProgramMemory& y) { return x.mValues != y.mValues; } private: void copyOnWrite(); std::shared_ptr<Map> mValues; }; struct ProgramMemoryState { ProgramMemory state; std::map<nonneg int, const Token*> origins; const Settings& settings; explicit ProgramMemoryState(const Settings& s); void replace(ProgramMemory pm, const Token* origin = nullptr); void addState(const Token* tok, const ProgramMemory::Map& vars); void assume(const Token* tok, bool b, bool isEmpty = false); void removeModifiedVars(const Token* tok); ProgramMemory get(const Token* tok, const Token* ctx, const ProgramMemory::Map& vars) const; }; std::vector<ValueFlow::Value> execute(const Scope* scope, ProgramMemory& pm, const Settings& settings); void execute(const Token* expr, ProgramMemory& programMemory, MathLib::bigint* result, bool* error, const Settings& settings); /** * Is condition always false when variable has given value? * \param condition top ast token in condition * \param pm program memory */ bool conditionIsFalse(const Token* condition, ProgramMemory pm, const Settings& settings); /** * Is condition always true when variable has given value? * \param condition top ast token in condition * \param pm program memory */ bool conditionIsTrue(const Token* condition, ProgramMemory pm, const Settings& settings); /** * Get program memory by looking backwards from given token. */ ProgramMemory getProgramMemory(const Token* tok, const Token* expr, const ValueFlow::Value& value, const Settings& settings); ValueFlow::Value evaluateLibraryFunction(const std::unordered_map<nonneg int, ValueFlow::Value>& args, const std::string& returnValue, const Settings& settings, bool cpp); #endif
6,236
C++
.h
157
34.503185
125
0.698639
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,486
redirect.h
danmar_cppcheck/test/redirect.h
// Cppcheck - A tool for static C/C++ code analysis // Copyright (C) 2007-2024 Cppcheck team. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef REDIRECT_H #define REDIRECT_H #include <iostream> #include <sstream> #include <stdexcept> #include <string> /** * @brief Utility class for capturing cout and cerr to ostringstream buffers * for later use. Uses RAII to stop redirection when the object goes out of * scope. * NOTE: This is *not* thread-safe. */ class RedirectOutputError { public: /** Set up redirection, flushing anything in the pipes. */ RedirectOutputError() { // flush all old output std::cout.flush(); std::cerr.flush(); _oldCout = std::cout.rdbuf(); // back up cout's streambuf _oldCerr = std::cerr.rdbuf(); // back up cerr's streambuf std::cout.rdbuf(_out.rdbuf()); // assign streambuf to cout std::cerr.rdbuf(_err.rdbuf()); // assign streambuf to cerr } /** Revert cout and cerr behaviour */ ~RedirectOutputError() noexcept(false) { std::cout.rdbuf(_oldCout); // restore cout's original streambuf std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf { const std::string s = _out.str(); if (!s.empty()) throw std::runtime_error("unconsumed stdout: " + s); // cppcheck-suppress exceptThrowInDestructor - FP #11031 } { const std::string s = _err.str(); if (!s.empty()) throw std::runtime_error("consumed stderr: " + s); } } /** Return what would be printed to cout. */ std::string getOutput() { std::string s = _out.str(); _out.str(""); return s; } /** Return what would be printed to cerr. */ std::string getErrout() { std::string s = _err.str(); _err.str(""); return s; } private: std::ostringstream _out; std::ostringstream _err; std::streambuf *_oldCout; std::streambuf *_oldCerr; }; class SuppressOutput { public: /** Set up suppression, flushing anything in the pipes. */ SuppressOutput() { // flush all old output std::cout.flush(); std::cerr.flush(); _oldCout = std::cout.rdbuf(); // back up cout's streambuf _oldCerr = std::cerr.rdbuf(); // back up cerr's streambuf std::cout.rdbuf(nullptr); // disable cout std::cerr.rdbuf(nullptr); // disable cerr } /** Revert cout and cerr behaviour */ ~SuppressOutput() { std::cout.rdbuf(_oldCout); // restore cout's original streambuf std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf } private: std::streambuf *_oldCout; std::streambuf *_oldCerr; }; #define REDIRECT RedirectOutputError redir #define GET_REDIRECT_OUTPUT redir.getOutput() #define GET_REDIRECT_ERROUT redir.getErrout() #define SUPPRESS SuppressOutput supprout class RedirectInput { public: explicit RedirectInput(const std::string &input) : _in(input) { _oldCin = std::cin.rdbuf(); // back up cin's streambuf std::cin.rdbuf(_in.rdbuf()); // assign streambuf to cin } ~RedirectInput() noexcept { std::cin.rdbuf(_oldCin); // restore cin's original streambuf } private: std::istringstream _in; std::streambuf* _oldCin; }; #endif
3,963
C++
.h
111
30.432432
125
0.651788
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,487
precompiled.h
danmar_cppcheck/test/precompiled.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // IWYU pragma: begin_keep #include "check.h" #include "config.h" #include "importproject.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "timer.h" #include "token.h" #include "tokenlist.h" #include "tokenize.h" // IWYU pragma: end_keep
1,042
C++
.h
30
33.133333
72
0.744554
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,488
helpers.h
danmar_cppcheck/test/helpers.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef helpersH #define helpersH #include "config.h" #include "library.h" #include "preprocessor.h" #include "settings.h" #include "standards.h" #include "tokenize.h" #include "tokenlist.h" #include <cstddef> #include <map> #include <set> #include <stdexcept> #include <sstream> #include <string> #include <vector> class Token; class SuppressionList; class ErrorLogger; namespace simplecpp { struct DUI; } namespace tinyxml2 { class XMLDocument; } // TODO: make Tokenizer private class SimpleTokenizer : public Tokenizer { public: template<size_t size> SimpleTokenizer(ErrorLogger& errorlogger, const char (&code)[size], bool cpp = true) : Tokenizer{s_settings, errorlogger} { if (!tokenize(code, cpp)) throw std::runtime_error("creating tokens failed"); } SimpleTokenizer(const Settings& settings, ErrorLogger& errorlogger) : Tokenizer{settings, errorlogger} {} /* Token* tokens() { return Tokenizer::tokens(); } const Token* tokens() const { return Tokenizer::tokens(); } */ /** * Tokenize code * @param code The code * @param cpp Indicates if the code is C++ * @param configuration E.g. "A" for code where "#ifdef A" is true * @return false if source code contains syntax errors */ template<size_t size> bool tokenize(const char (&code)[size], bool cpp = true, const std::string &configuration = emptyString) { std::istringstream istr(code); if (!list.createTokens(istr, cpp ? "test.cpp" : "test.c")) return false; return simplifyTokens1(configuration); } // TODO: get rid of this bool tokenize(const std::string& code, bool cpp = true, const std::string &configuration = emptyString) { std::istringstream istr(code); if (!list.createTokens(istr, cpp ? "test.cpp" : "test.c")) return false; return simplifyTokens1(configuration); } private: // TODO. find a better solution static const Settings s_settings; }; class SimpleTokenList { public: template<size_t size> explicit SimpleTokenList(const char (&code)[size], Standards::Language lang = Standards::Language::CPP) { std::istringstream iss(code); if (!list.createTokens(iss, lang)) throw std::runtime_error("creating tokens failed"); } Token* front() { return list.front(); } const Token* front() const { return list.front(); } private: const Settings settings; TokenList list{&settings}; }; class ScopedFile { public: ScopedFile(std::string name, const std::string &content, std::string path = ""); ~ScopedFile(); const std::string& path() const { return mFullPath; } const std::string& name() const { return mName; } ScopedFile(const ScopedFile&) = delete; ScopedFile(ScopedFile&&) = delete; ScopedFile& operator=(const ScopedFile&) = delete; ScopedFile& operator=(ScopedFile&&) = delete; private: const std::string mName; const std::string mPath; const std::string mFullPath; }; class PreprocessorHelper { public: /** * Get preprocessed code for a given configuration * * Note: for testing only. * * @param filedata file data including preprocessing 'if', 'define', etc * @param cfg configuration to read out * @param filename name of source file * @param inlineSuppression the inline suppressions */ static std::string getcode(const Settings& settings, ErrorLogger& errorlogger, const std::string &filedata, const std::string &cfg, const std::string &filename, SuppressionList *inlineSuppression = nullptr); static std::map<std::string, std::string> getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], const std::string &filename = "file.c", SuppressionList *inlineSuppression = nullptr); static void preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger); static void preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger, const simplecpp::DUI& dui); /** get remark comments */ static std::vector<RemarkComment> getRemarkComments(const char code[], ErrorLogger& errorLogger); private: static std::map<std::string, std::string> getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], std::set<std::string> cfgs, const std::string &filename = "file.c", SuppressionList *inlineSuppression = nullptr); }; namespace cppcheck { template<typename T> std::size_t count_all_of(const std::string& str, T sub) { std::size_t n = 0; std::string::size_type pos = 0; while ((pos = str.find(sub, pos)) != std::string::npos) { ++pos; ++n; } return n; } } /* designated initialization helper Usage: struct S { int i; }; const auto s = dinit(S, $.i = 1 ); */ #define dinit(T, ...) \ ([&] { T ${}; __VA_ARGS__; return $; }()) // Default construct object to avoid bug in clang // error: default member initializer for 'y' needed within definition of enclosing class 'X' outside of member functions // see https://stackoverflow.com/questions/53408962 struct make_default_obj { template<class T> operator T() const // NOLINT { return T{}; } }; inline std::string filter_valueflow(const std::string& s) { bool filtered = false; std::istringstream istr(s); std::string ostr; std::string errline; while (std::getline(istr, errline)) { if (errline.find("valueflow.cpp") != std::string::npos) { filtered = true; continue; } ostr += errline; ostr += '\n'; // TODO: last line might not contain a newline } if (!filtered) throw std::runtime_error("no valueflow.cpp messages were filtered"); return ostr; } struct LibraryHelper { static bool loadxmldata(Library &lib, const char xmldata[], std::size_t len); static bool loadxmldata(Library &lib, Library::Error& liberr, const char xmldata[], std::size_t len); static Library::Error loadxmldoc(Library &lib, const tinyxml2::XMLDocument& doc); }; #endif // helpersH
7,239
C++
.h
216
28.407407
239
0.666476
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,489
fixture.h
danmar_cppcheck/test/fixture.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef fixtureH #define fixtureH #include "check.h" #include "color.h" #include "config.h" #include "errorlogger.h" #include "platform.h" #include "settings.h" #include "standards.h" #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <type_traits> #include <utility> class options; class Tokenizer; enum class Certainty : std::uint8_t; enum class Severity : std::uint8_t; class TestFixture : public ErrorLogger { private: static std::ostringstream errmsg; static unsigned int countTests; static std::size_t fails_counter; static std::size_t todos_counter; static std::size_t succeeded_todos_counter; bool mVerbose{}; std::string mTemplateFormat; std::string mTemplateLocation; std::string mTestname; protected: std::string exename; std::string testToRun; bool quiet_tests{}; bool dry_run{}; virtual void run() = 0; bool prepareTest(const char testname[]); virtual void prepareTestInternal() {} void teardownTest(); virtual void teardownTestInternal() {} std::string getLocationStr(const char * filename, unsigned int linenr) const; void assert_(const char * filename, unsigned int linenr, bool condition) const; template<typename T> void assertEquals(const char* const filename, const unsigned int linenr, const T& expected, const T& actual, const std::string& msg = emptyString) const { if (expected != actual) { std::ostringstream expectedStr; expectedStr << expected; std::ostringstream actualStr; actualStr << actual; assertFailure(filename, linenr, expectedStr.str(), actualStr.str(), msg); } } template<typename T> void assertEqualsEnum(const char* const filename, const unsigned int linenr, const T& expected, const T& actual, const std::string& msg = emptyString) const { if (std::is_unsigned<T>()) assertEquals(filename, linenr, static_cast<std::uint64_t>(expected), static_cast<std::uint64_t>(actual), msg); else assertEquals(filename, linenr, static_cast<std::int64_t>(expected), static_cast<std::int64_t>(actual), msg); } template<typename T> void todoAssertEqualsEnum(const char* const filename, const unsigned int linenr, const T& wanted, const T& current, const T& actual) const { if (std::is_unsigned<T>()) todoAssertEquals(filename, linenr, static_cast<std::uint64_t>(wanted), static_cast<std::uint64_t>(current), static_cast<std::uint64_t>(actual)); else todoAssertEquals(filename, linenr, static_cast<std::int64_t>(wanted), static_cast<std::int64_t>(current), static_cast<std::int64_t>(actual)); } void assertEquals(const char * filename, unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg = emptyString) const; void assertEqualsWithoutLineNumbers(const char * filename, unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg = emptyString) const; void assertEquals(const char * filename, unsigned int linenr, const char expected[], const std::string& actual, const std::string &msg = emptyString) const; void assertEquals(const char * filename, unsigned int linenr, const char expected[], const char actual[], const std::string &msg = emptyString) const; void assertEquals(const char * filename, unsigned int linenr, const std::string& expected, const char actual[], const std::string &msg = emptyString) const; void assertEquals(const char * filename, unsigned int linenr, long long expected, long long actual, const std::string &msg = emptyString) const; void assertEqualsDouble(const char * filename, unsigned int linenr, double expected, double actual, double tolerance, const std::string &msg = emptyString) const; void todoAssertEquals(const char * filename, unsigned int linenr, const std::string &wanted, const std::string &current, const std::string &actual) const; void todoAssertEquals(const char * filename, unsigned int linenr, const char wanted[], const char current[], const std::string &actual) const; void todoAssertEquals(const char * filename, unsigned int linenr, long long wanted, long long current, long long actual) const; void assertThrow(const char * filename, unsigned int linenr) const; void assertThrowFail(const char * filename, unsigned int linenr) const; void assertNoThrowFail(const char * filename, unsigned int linenr) const; static std::string deleteLineNumber(const std::string &message); void setVerbose(bool v) { mVerbose = v; } void setTemplateFormat(const std::string &templateFormat); void setMultiline() { setTemplateFormat("multiline"); } void processOptions(const options& args); template<typename T> static T& getCheck() { for (Check *check : Check::instances()) { //cppcheck-suppress useStlAlgorithm if (T* c = dynamic_cast<T*>(check)) return *c; } throw std::runtime_error("instance not found"); } template<typename T> static void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) { Check& check = getCheck<T>(); check.runChecks(tokenizer, errorLogger); } class SettingsBuilder { public: explicit SettingsBuilder(const TestFixture &fixture) : fixture(fixture) {} SettingsBuilder(const TestFixture &fixture, Settings settings) : fixture(fixture), settings(std::move(settings)) {} SettingsBuilder& severity(Severity sev, bool b = true) { if (REDUNDANT_CHECK && settings.severity.isEnabled(sev) == b) throw std::runtime_error("redundant setting: severity"); settings.severity.setEnabled(sev, b); return *this; } SettingsBuilder& certainty(Certainty cert, bool b = true) { if (REDUNDANT_CHECK && settings.certainty.isEnabled(cert) == b) throw std::runtime_error("redundant setting: certainty"); settings.certainty.setEnabled(cert, b); return *this; } SettingsBuilder& clang() { if (REDUNDANT_CHECK && settings.clang) throw std::runtime_error("redundant setting: clang"); settings.clang = true; return *this; } SettingsBuilder& checkLibrary() { if (REDUNDANT_CHECK && settings.checkLibrary) throw std::runtime_error("redundant setting: checkLibrary"); settings.checkLibrary = true; return *this; } SettingsBuilder& checkUnusedTemplates(bool b = true) { if (REDUNDANT_CHECK && settings.checkUnusedTemplates == b) throw std::runtime_error("redundant setting: checkUnusedTemplates"); settings.checkUnusedTemplates = b; return *this; } SettingsBuilder& debugwarnings(bool b = true) { if (REDUNDANT_CHECK && settings.debugwarnings == b) throw std::runtime_error("redundant setting: debugwarnings"); settings.debugwarnings = b; return *this; } SettingsBuilder& c(Standards::cstd_t std) { // TODO: CLatest and C23 are the same - handle differently? //if (REDUNDANT_CHECK && settings.standards.c == std) // throw std::runtime_error("redundant setting: standards.c"); settings.standards.c = std; return *this; } SettingsBuilder& cpp(Standards::cppstd_t std) { // TODO: CPPLatest and CPP26 are the same - handle differently? //if (REDUNDANT_CHECK && settings.standards.cpp == std) // throw std::runtime_error("redundant setting: standards.cpp"); settings.standards.cpp = std; return *this; } SettingsBuilder& checkLevel(Settings::CheckLevel level); SettingsBuilder& library(const char lib[]); SettingsBuilder& libraryxml(const char xmldata[], std::size_t len); SettingsBuilder& platform(Platform::Type type); SettingsBuilder& checkConfiguration() { if (REDUNDANT_CHECK && settings.checkConfiguration) throw std::runtime_error("redundant setting: checkConfiguration"); settings.checkConfiguration = true; return *this; } SettingsBuilder& checkHeaders(bool b = true) { if (REDUNDANT_CHECK && settings.checkHeaders == b) throw std::runtime_error("redundant setting: checkHeaders"); settings.checkHeaders = b; return *this; } Settings build() { return std::move(settings); } private: const TestFixture &fixture; Settings settings; const bool REDUNDANT_CHECK = false; }; SettingsBuilder settingsBuilder() const { return SettingsBuilder(*this); } SettingsBuilder settingsBuilder(Settings settings) const { return SettingsBuilder(*this, std::move(settings)); } std::string output_str() { std::string s = mOutput.str(); mOutput.str(""); return s; } std::string errout_str() { std::string s = mErrout.str(); mErrout.str(""); return s; } void ignore_errout() { if (errout_str().empty()) throw std::runtime_error("no errout to ignore"); } const Settings settingsDefault; private: //Helper function to be called when an assertEquals assertion fails. //Writes the appropriate failure message to errmsg and increments fails_counter void assertFailure(const char* filename, unsigned int linenr, const std::string& expected, const std::string& actual, const std::string& msg) const; std::ostringstream mOutput; std::ostringstream mErrout; void reportOut(const std::string &outmsg, Color c = Color::Reset) override; void reportErr(const ErrorMessage &msg) override; void run(const std::string &str); public: static void printHelp(); const std::string classname; explicit TestFixture(const char * _name); static std::size_t runTests(const options& args); }; class TestInstance { public: explicit TestInstance(const char * _name); virtual ~TestInstance() = default; virtual TestFixture* create() = 0; const std::string classname; protected: std::unique_ptr<TestFixture> impl; }; #define TEST_CASE( NAME ) do { if (prepareTest(#NAME)) { setVerbose(false); try { NAME(); teardownTest(); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } } while (false) // TODO: the asserts do not actually assert i.e. do stop executing the test #define ASSERT( CONDITION ) assert_(__FILE__, __LINE__, (CONDITION)) #define ASSERT_LOC( CONDITION, FILE_, LINE_ ) assert_(FILE_, LINE_, (CONDITION)) // *INDENT-OFF* #define ASSERT_EQUALS( EXPECTED, ACTUAL ) do { try { assertEquals(__FILE__, __LINE__, (EXPECTED), (ACTUAL)); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } while (false) // *INDENT-ON* #define ASSERT_EQUALS_WITHOUT_LINENUMBERS( EXPECTED, ACTUAL ) assertEqualsWithoutLineNumbers(__FILE__, __LINE__, EXPECTED, ACTUAL) #define ASSERT_EQUALS_DOUBLE( EXPECTED, ACTUAL, TOLERANCE ) assertEqualsDouble(__FILE__, __LINE__, EXPECTED, ACTUAL, TOLERANCE) #define ASSERT_EQUALS_LOC_MSG( EXPECTED, ACTUAL, MSG, FILE_, LINE_ ) assertEquals(FILE_, LINE_, EXPECTED, ACTUAL, MSG) #define ASSERT_EQUALS_MSG( EXPECTED, ACTUAL, MSG ) assertEquals(__FILE__, __LINE__, EXPECTED, ACTUAL, MSG) #define ASSERT_EQUALS_ENUM( EXPECTED, ACTUAL ) assertEqualsEnum(__FILE__, __LINE__, (EXPECTED), (ACTUAL)) #define TODO_ASSERT_EQUALS_ENUM( WANTED, CURRENT, ACTUAL ) todoAssertEqualsEnum(__FILE__, __LINE__, WANTED, CURRENT, ACTUAL) #define ASSERT_THROW_EQUALS( CMD, EXCEPTION, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const EXCEPTION&e) { assertEquals(__FILE__, __LINE__, EXPECTED, e.errorMessage); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false) #define ASSERT_THROW_EQUALS_2( CMD, EXCEPTION, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const EXCEPTION&e) { assertEquals(__FILE__, __LINE__, EXPECTED, e.what()); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false) #define ASSERT_THROW_INTERNAL( CMD, TYPE ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const InternalError& e) { assertEqualsEnum(__FILE__, __LINE__, InternalError::TYPE, e.type); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false) #define ASSERT_THROW_INTERNAL_EQUALS( CMD, TYPE, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const InternalError& e) { assertEqualsEnum(__FILE__, __LINE__, InternalError::TYPE, e.type); assertEquals(__FILE__, __LINE__, EXPECTED, e.errorMessage); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false) #define ASSERT_NO_THROW( CMD ) do { try { (void)(CMD); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } while (false) #define TODO_ASSERT_THROW( CMD, EXCEPTION ) do { try { (void)(CMD); } catch (const EXCEPTION&) {} catch (...) { assertThrow(__FILE__, __LINE__); } } while (false) #define TODO_ASSERT( CONDITION ) do { const bool condition=(CONDITION); todoAssertEquals(__FILE__, __LINE__, true, false, condition); } while (false) #define TODO_ASSERT_EQUALS( WANTED, CURRENT, ACTUAL ) todoAssertEquals(__FILE__, __LINE__, WANTED, CURRENT, ACTUAL) #define REGISTER_TEST( CLASSNAME ) namespace { class CLASSNAME ## Instance : public TestInstance { public: CLASSNAME ## Instance() : TestInstance(#CLASSNAME) {} TestFixture* create() override { impl.reset(new CLASSNAME); return impl.get(); } }; CLASSNAME ## Instance instance_ ## CLASSNAME; } #define PLATFORM( P, T ) do { std::string errstr; assertEquals(__FILE__, __LINE__, true, P.set(Platform::toString(T), errstr, {exename}), errstr); } while (false) #endif // fixtureH
15,057
C++
.h
275
47.770909
353
0.669972
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,490
options.h
danmar_cppcheck/test/options.h
// Cppcheck - A tool for static C/C++ code analysis // Copyright (C) 2007-2024 Cppcheck team. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef OPTIONS_H #define OPTIONS_H #include <set> #include <string> /** * @brief Class to parse command-line parameters for ./testrunner . * Has getters for available switches and parameters. * See test/testoptions.cpp for sample usage. */ class options { public: /** Call from main() to populate object */ options(int argc, const char* const argv[]); /** Don't print the name of each method being tested. */ bool quiet() const; /** Print help. */ bool help() const; /** Print summary. */ bool summary() const; /** Perform dry run. */ bool dry_run() const; /** Which test should be run. Empty string means 'all tests' */ const std::set<std::string>& which_test() const; const std::string& exe() const; options() = delete; options(const options&) = delete; options& operator =(const options&) = delete; private: std::set<std::string> mWhichTests; const bool mQuiet; const bool mHelp; const bool mSummary; const bool mDryRun; std::string mExe; }; #endif
1,795
C++
.h
51
32.254902
72
0.705239
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,491
TestClass.h
danmar_cppcheck/test/cli/shared-items-project/Shared/TestClass.h
#pragma once namespace Shared { class TestClass { public: explicit TestClass(); virtual ~TestClass(); }; } // namespace Shared
160
C++
.h
10
11.7
29
0.624161
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,493
1.h
danmar_cppcheck/test/cli/proj-inline-suppress/1.h
// cppcheck-suppress zerodiv const int x = 10000 / 0;
57
C++
.h
2
26
28
0.730769
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,494
odr.h
danmar_cppcheck/test/cli/whole-program/odr.h
class Base { public: virtual void f() = 0; }; extern Base *c1_create(); extern Base *c2_create();
102
C++
.h
6
15.333333
25
0.666667
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,495
mainwindow.h
danmar_cppcheck/tools/triage/mainwindow.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QFileSystemModel> #include <QMainWindow> #include <QObject> #include <QRegularExpression> #include <QString> #include <QStringList> class QListWidgetItem; class QTextStream; class QPoint; class QWidget; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); MainWindow(const MainWindow &) = delete; MainWindow &operator=(const MainWindow &) = delete; ~MainWindow() override; public slots: void loadFile(); void loadFromClipboard(); void filter(const QString& filter); void showResult(QListWidgetItem *item); void refreshResults(); void fileTreeFilter(const QString &str); void findInFilesClicked(); void directorytreeDoubleClick(); void searchResultsDoubleClick(); void resultsContextMenu(const QPoint& pos); private: Ui::MainWindow *ui; void load(QTextStream &textStream); bool runProcess(const QString &programName, const QStringList & arguments); bool wget(const QString &url); bool unpackArchive(const QString &archiveName); void showSrcFile(const QString &fileName, const QString &url, int lineNumber); QStringList mAllErrors; QFileSystemModel mFSmodel; const QRegularExpression mVersionRe; const QStringList hFiles; const QStringList srcFiles; }; #endif // MAINWINDOW_H
2,194
C++
.h
64
31.171875
82
0.756489
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,496
type2.h
danmar_cppcheck/oss-fuzz/type2.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <cstdint> #include <string> std::string generateCode2(const uint8_t *data, size_t dataSize);
881
C++
.h
21
40
72
0.747664
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,497
cppcheckexecutorseh.h
danmar_cppcheck/cli/cppcheckexecutorseh.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CPPCHECKEXECUTORSEH_H #define CPPCHECKEXECUTORSEH_H #include "config.h" // IWYU pragma: keep #ifdef USE_WINDOWS_SEH class CppCheckExecutor; class Settings; int check_wrapper_seh(CppCheckExecutor& executor, int (CppCheckExecutor::*f)(const Settings&) const, const Settings& settings); #endif #endif // CPPCHECKEXECUTORSEH_H
1,100
C++
.h
26
40.423077
127
0.764761
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,498
threadexecutor.h
danmar_cppcheck/cli/threadexecutor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef THREADEXECUTOR_H #define THREADEXECUTOR_H #include "cppcheck.h" #include "executor.h" #include <list> class Settings; class ErrorLogger; class SuppressionList; struct FileSettings; class FileWithDetails; /// @addtogroup CLI /// @{ /** * This class will take a list of filenames and settings and check then * all files using threads. */ class ThreadExecutor : public Executor { friend class SyncLogForwarder; public: ThreadExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand); ThreadExecutor(const ThreadExecutor &) = delete; ThreadExecutor& operator=(const ThreadExecutor &) = delete; unsigned int check() override; CppCheck::ExecuteCmdFn mExecuteCommand; }; /// @} #endif // THREADEXECUTOR_H
1,665
C++
.h
44
35.613636
227
0.764596
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,499
cppcheckexecutor.h
danmar_cppcheck/cli/cppcheckexecutor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CPPCHECKEXECUTOR_H #define CPPCHECKEXECUTOR_H #include "filesettings.h" #include <list> #include <string> #include <vector> class Settings; class ErrorLogger; class SuppressionList; /** * This class works as an example of how CppCheck can be used in external * programs without very little knowledge of the internal parts of the * program itself. If you wish to use cppcheck e.g. as a part of IDE, * just rewrite this class for your needs and possibly use other methods * from CppCheck class instead the ones used here. */ class CppCheckExecutor { public: friend class TestSuppressions; /** * Constructor */ CppCheckExecutor() = default; CppCheckExecutor(const CppCheckExecutor &) = delete; CppCheckExecutor& operator=(const CppCheckExecutor&) = delete; /** * Starts the checking. * * @param argc from main() * @param argv from main() * @return EXIT_FAILURE if arguments are invalid or no input files * were found. * If errors are found and --error-exitcode is used, * given value is returned instead of default 0. * If no errors are found, 0 is returned. */ int check(int argc, const char* const argv[]); private: /** * Execute a shell command and read the output from it. Returns exitcode of the executed command,. */ static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output_); protected: static bool reportSuppressions(const Settings &settings, const SuppressionList& suppressions, bool unusedFunctionCheckEnabled, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, ErrorLogger& errorLogger); /** * Wrapper around check_internal * - installs optional platform dependent signal handling * * @param settings the settings **/ int check_wrapper(const Settings& settings); /** * Starts the checking. * * @param settings the settings * @return EXIT_FAILURE if arguments are invalid or no input files * were found. * If errors are found and --error-exitcode is used, * given value is returned instead of default 0. * If no errors are found, 0 is returned. */ int check_internal(const Settings& settings) const; /** * Filename associated with size of file */ std::list<FileWithDetails> mFiles; std::list<FileSettings> mFileSettings; }; #endif // CPPCHECKEXECUTOR_H
3,330
C++
.h
86
34.744186
243
0.704461
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,500
cmdlineparser.h
danmar_cppcheck/cli/cmdlineparser.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CMDLINE_PARSER_H #define CMDLINE_PARSER_H #include <cstddef> #include <cstdint> #include <list> #include <string> #include <vector> #include "cmdlinelogger.h" #include "filesettings.h" #include "utils.h" class Settings; struct Suppressions; class Library; /// @addtogroup CLI /// @{ /** * @brief The command line parser. * The command line parser parses options and parameters user gives to * cppcheck command line. * * The parser takes a pointer to Settings instance which it will update * based on options user has given. Couple of options are handled as * class internal options. */ class CmdLineParser { public: /** * The constructor. * @param logger The logger instance to log messages through * @param settings Settings instance that will be modified according to * options user has given. * @param suppressions Suppressions instance that keeps the suppressions */ CmdLineParser(CmdLineLogger &logger, Settings &settings, Suppressions &suppressions); enum class Result : std::uint8_t { Success, Exit, Fail }; /** * @brief Parse command line args and fill settings and file lists * from there. * * @param argc argc from main() * @param argv argv from main() * @return false when errors are found in the input */ bool fillSettingsFromArgs(int argc, const char* const argv[]); /** * Parse given command line. * @return true if command line was ok, false if there was an error. */ Result parseFromArgs(int argc, const char* const argv[]); /** * Return the path names user gave to command line. */ const std::vector<std::string>& getPathNames() const { return mPathNames; } /** * Return the files user gave to command line. */ const std::list<FileWithDetails>& getFiles() const { return mFiles; } /** * Return the file settings read from command line. */ const std::list<FileSettings>& getFileSettings() const { return mFileSettings; } /** * Return a list of paths user wants to ignore. */ const std::vector<std::string>& getIgnoredPaths() const { return mIgnoredPaths; } /** * Get Cppcheck version */ std::string getVersion() const; protected: /** * Print help text to the console. */ void printHelp() const; private: bool isCppcheckPremium() const; template<typename T> bool parseNumberArg(const char* const arg, std::size_t offset, T& num, bool mustBePositive = false) { T tmp; std::string err; if (!strToInt(arg + offset, tmp, &err)) { mLogger.printError("argument to '" + std::string(arg, offset) + "' is not valid - " + err + "."); return false; } if (mustBePositive && tmp < 0) { mLogger.printError("argument to '" + std::string(arg, offset) + "' needs to be a positive integer."); return false; } num = tmp; return true; } /** * Tries to load a library and prints warning/error messages * @return false, if an error occurred (except unknown XML elements) */ bool tryLoadLibrary(Library& destination, const std::string& basepath, const char* filename, bool debug); /** * @brief Load libraries * @param settings Settings * @return Returns true if successful */ bool loadLibraries(Settings& settings); /** * @brief Load addons * @param settings Settings * @return Returns true if successful */ bool loadAddons(Settings& settings); bool loadCppcheckCfg(); CmdLineLogger &mLogger; std::vector<std::string> mPathNames; std::list<FileWithDetails> mFiles; std::list<FileSettings> mFileSettings; std::vector<std::string> mIgnoredPaths; Settings &mSettings; Suppressions &mSuppressions; std::string mVSConfig; }; /// @} #endif // CMDLINE_PARSER_H
4,761
C++
.h
146
27.767123
113
0.672478
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,501
stacktrace.h
danmar_cppcheck/cli/stacktrace.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef STACKTRACE_H #define STACKTRACE_H #include "config.h" #ifdef USE_UNIX_BACKTRACE_SUPPORT #include <cstdio> /* * Try to print the callstack. * That is very sensitive to the operating system, hardware, compiler and runtime. * The code is not meant for production environment! * One reason is named first: it's using functions not whitelisted for usage in a signal handler function. * * @param output the descriptor to write the trace to * @param start_idx the frame index to start with * @param demangling controls demangling of symbols * @param maxdepth the maximum number of frames to list (32 at most or if -1) * @param omit_above_own omit top frames which are above our own code (i.e. libc symbols) */ void print_stacktrace(FILE* output, int start_idx, bool demangling, int maxdepth, bool omit_above_own); #endif #endif // STACKTRACE_H
1,625
C++
.h
37
42
106
0.757748
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,502
cmdlinelogger.h
danmar_cppcheck/cli/cmdlinelogger.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CMD_LINE_LOGGER_H #define CMD_LINE_LOGGER_H #include <string> class CmdLineLogger { public: virtual ~CmdLineLogger() = default; /** print a regular message */ virtual void printMessage(const std::string &message) = 0; /** print an error message */ virtual void printError(const std::string &message) = 0; /** print to the output */ virtual void printRaw(const std::string &message) = 0; }; #endif // CMD_LINE_LOGGER_H
1,221
C++
.h
32
35.625
72
0.726351
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,503
precompiled.h
danmar_cppcheck/cli/precompiled.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // IWYU pragma: begin_keep #include "config.h" #include "cppcheck.h" #include "settings.h" // IWYU pragma: end_keep
893
C++
.h
23
37.043478
72
0.743088
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,504
singleexecutor.h
danmar_cppcheck/cli/singleexecutor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SINGLEEXECUTOR_H #define SINGLEEXECUTOR_H #include "executor.h" #include <list> class ErrorLogger; class Settings; class CppCheck; class SuppressionList; struct FileSettings; class FileWithDetails; class SingleExecutor : public Executor { public: SingleExecutor(CppCheck &cppcheck, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger); SingleExecutor(const SingleExecutor &) = delete; SingleExecutor& operator=(const SingleExecutor &) = delete; unsigned int check() override; private: CppCheck &mCppcheck; }; #endif // SINGLEEXECUTOR_H
1,450
C++
.h
38
36
208
0.771368
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,505
executor.h
danmar_cppcheck/cli/executor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef EXECUTOR_H #define EXECUTOR_H #include <cstddef> #include <list> #include <mutex> #include <string> #include <unordered_set> class Settings; class ErrorLogger; class ErrorMessage; class SuppressionList; struct FileSettings; class FileWithDetails; /// @addtogroup CLI /// @{ /** * This class will take a list of filenames and settings and check then * all files using threads. */ class Executor { public: Executor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger); virtual ~Executor() = default; Executor(const Executor &) = delete; Executor& operator=(const Executor &) = delete; virtual unsigned int check() = 0; /** * Information about how many files have been checked * * @param fileindex This many files have been checked. * @param filecount This many files there are in total. * @param sizedone The sum of sizes of the files checked. * @param sizetotal The total sizes of the files. */ void reportStatus(std::size_t fileindex, std::size_t filecount, std::size_t sizedone, std::size_t sizetotal); protected: /** * @brief Check if message is being suppressed and unique. * @param msg the message to check * @return true if message is not suppressed and unique */ bool hasToLog(const ErrorMessage &msg); const std::list<FileWithDetails> &mFiles; const std::list<FileSettings>& mFileSettings; const Settings &mSettings; SuppressionList &mSuppressions; ErrorLogger &mErrorLogger; private: std::mutex mErrorListSync; // TODO: store hashes instead of the full messages std::unordered_set<std::string> mErrorList; }; /// @} #endif // EXECUTOR_H
2,570
C++
.h
71
33.014085
182
0.732502
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,506
processexecutor.h
danmar_cppcheck/cli/processexecutor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PROCESSEXECUTOR_H #define PROCESSEXECUTOR_H #include "cppcheck.h" #include "executor.h" #include <cstddef> #include <list> #include <string> class Settings; class ErrorLogger; class SuppressionList; struct FileSettings; class FileWithDetails; /// @addtogroup CLI /// @{ /** * This class will take a list of filenames and settings and check then * all files using threads. */ class ProcessExecutor : public Executor { public: ProcessExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand); ProcessExecutor(const ProcessExecutor &) = delete; ProcessExecutor& operator=(const ProcessExecutor &) = delete; unsigned int check() override; private: /** * Read from the pipe, parse and handle what ever is in there. * @return False in case of an recoverable error - will exit process on others */ bool handleRead(int rpipe, unsigned int &result, const std::string& filename); /** * @brief Check load average condition * @param nchildren - count of currently ran children * @return true - if new process can be started */ bool checkLoadAverage(size_t nchildren); /** * @brief Reports internal errors related to child processes * @param msg The error message */ void reportInternalChildErr(const std::string &childname, const std::string &msg); CppCheck::ExecuteCmdFn mExecuteCommand; }; /// @} #endif // PROCESSEXECUTOR_H
2,354
C++
.h
62
34.935484
228
0.741992
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,507
signalhandler.h
danmar_cppcheck/cli/signalhandler.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SIGNALHANDLER_H #define SIGNALHANDLER_H #include "config.h" #if defined(USE_UNIX_SIGNAL_HANDLING) #include <cstdio> void register_signal_handler(FILE* output); #endif // USE_UNIX_SIGNAL_HANDLING #endif // SIGNALHANDLER_H
998
C++
.h
25
38
72
0.755694
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,508
filelister.h
danmar_cppcheck/cli/filelister.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef filelisterH #define filelisterH #include <list> #include <set> #include <string> class PathMatch; class FileWithDetails; /// @addtogroup CLI /// @{ /** @brief Cross-platform FileLister */ class FileLister { public: /** * @brief Recursively add source files to a map. * Add source files from given directory and all subdirectries to the * given map. Only files with accepted extensions * (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added. * @param files output list that associates the size of each file with its name * @param path root path * @param ignored ignored paths * @return On success, an empty string is returned. On error, a error message is returned. */ static std::string recursiveAddFiles(std::list<FileWithDetails> &files, const std::string &path, const PathMatch& ignored) { const std::set<std::string> extra; return recursiveAddFiles(files, path, extra, ignored); } /** * @brief Recursively add source files to a map. * Add source files from given directory and all subdirectries to the * given map. Only files with accepted extensions * (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added. * @param files output list that associates the size of each file with its name * @param path root path * @param extra Extra file extensions * @param ignored ignored paths * @return On success, an empty string is returned. On error, a error message is returned. */ static std::string recursiveAddFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, const PathMatch& ignored); /** * @brief (Recursively) add source files to a map. * Add source files from given directory and all subdirectries to the * given map. Only files with accepted extensions * (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added. * @param files output list that associates the size of each file with its name * @param path root path * @param extra Extra file extensions * @param recursive Enable recursion * @param ignored ignored paths * @return On success, an empty string is returned. On error, a error message is returned. */ static std::string addFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, bool recursive, const PathMatch& ignored); }; /// @} #endif // #ifndef filelisterH
3,219
C++
.h
71
41.253521
170
0.704683
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,510
simplecpp.h
danmar_cppcheck/externals/simplecpp/simplecpp.h
/* -*- C++ -*- * simplecpp - A simple and high-fidelity C/C++ preprocessor library * Copyright (C) 2016-2023 simplecpp team */ #ifndef simplecppH #define simplecppH #include <cctype> #include <cstring> #include <iosfwd> #include <list> #include <map> #include <set> #include <string> #include <vector> #ifdef _WIN32 # ifdef SIMPLECPP_EXPORT # define SIMPLECPP_LIB __declspec(dllexport) # elif defined(SIMPLECPP_IMPORT) # define SIMPLECPP_LIB __declspec(dllimport) # else # define SIMPLECPP_LIB # endif #else # define SIMPLECPP_LIB #endif #if (__cplusplus < 201103L) && !defined(__APPLE__) #define nullptr NULL #endif #if defined(_MSC_VER) # pragma warning(push) // suppress warnings about "conversion from 'type1' to 'type2', possible loss of data" # pragma warning(disable : 4267) # pragma warning(disable : 4244) #endif namespace simplecpp { /** C code standard */ enum cstd_t { CUnknown=-1, C89, C99, C11, C17, C23 }; /** C++ code standard */ enum cppstd_t { CPPUnknown=-1, CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPP26 }; typedef std::string TokenString; class Macro; /** * Location in source code */ class SIMPLECPP_LIB Location { public: explicit Location(const std::vector<std::string> &f) : files(f), fileIndex(0), line(1U), col(0U) {} Location(const Location &loc) : files(loc.files), fileIndex(loc.fileIndex), line(loc.line), col(loc.col) {} Location &operator=(const Location &other) { if (this != &other) { fileIndex = other.fileIndex; line = other.line; col = other.col; } return *this; } /** increment this location by string */ void adjust(const std::string &str); bool operator<(const Location &rhs) const { if (fileIndex != rhs.fileIndex) return fileIndex < rhs.fileIndex; if (line != rhs.line) return line < rhs.line; return col < rhs.col; } bool sameline(const Location &other) const { return fileIndex == other.fileIndex && line == other.line; } const std::string& file() const { return fileIndex < files.size() ? files[fileIndex] : emptyFileName; } const std::vector<std::string> &files; unsigned int fileIndex; unsigned int line; unsigned int col; private: static const std::string emptyFileName; }; /** * token class. * @todo don't use std::string representation - for both memory and performance reasons */ class SIMPLECPP_LIB Token { public: Token(const TokenString &s, const Location &loc) : location(loc), previous(nullptr), next(nullptr), string(s) { flags(); } Token(const Token &tok) : macro(tok.macro), op(tok.op), comment(tok.comment), name(tok.name), number(tok.number), location(tok.location), previous(nullptr), next(nullptr), string(tok.string), mExpandedFrom(tok.mExpandedFrom) { } void flags() { name = (std::isalpha(static_cast<unsigned char>(string[0])) || string[0] == '_' || string[0] == '$') && (std::memchr(string.c_str(), '\'', string.size()) == nullptr); comment = string.size() > 1U && string[0] == '/' && (string[1] == '/' || string[1] == '*'); number = isNumberLike(string); op = (string.size() == 1U && !name && !comment && !number) ? string[0] : '\0'; } const TokenString& str() const { return string; } void setstr(const std::string &s) { string = s; flags(); } bool isOneOf(const char ops[]) const; bool startsWithOneOf(const char c[]) const; bool endsWithOneOf(const char c[]) const; static bool isNumberLike(const std::string& str) { return std::isdigit(static_cast<unsigned char>(str[0])) || (str.size() > 1U && (str[0] == '-' || str[0] == '+') && std::isdigit(static_cast<unsigned char>(str[1]))); } TokenString macro; char op; bool comment; bool name; bool number; Location location; Token *previous; Token *next; const Token *previousSkipComments() const { const Token *tok = this->previous; while (tok && tok->comment) tok = tok->previous; return tok; } const Token *nextSkipComments() const { const Token *tok = this->next; while (tok && tok->comment) tok = tok->next; return tok; } void setExpandedFrom(const Token *tok, const Macro* m) { mExpandedFrom = tok->mExpandedFrom; mExpandedFrom.insert(m); } bool isExpandedFrom(const Macro* m) const { return mExpandedFrom.find(m) != mExpandedFrom.end(); } void printAll() const; void printOut() const; private: TokenString string; std::set<const Macro*> mExpandedFrom; // Not implemented - prevent assignment Token &operator=(const Token &tok); }; /** Output from preprocessor */ struct SIMPLECPP_LIB Output { explicit Output(const std::vector<std::string> &files) : type(ERROR), location(files) {} enum Type { ERROR, /* #error */ WARNING, /* #warning */ MISSING_HEADER, INCLUDE_NESTED_TOO_DEEPLY, SYNTAX_ERROR, PORTABILITY_BACKSLASH, UNHANDLED_CHAR_ERROR, EXPLICIT_INCLUDE_NOT_FOUND, FILE_NOT_FOUND, DUI_ERROR } type; explicit Output(const std::vector<std::string>& files, Type type, const std::string& msg) : type(type), location(files), msg(msg) {} Location location; std::string msg; }; typedef std::list<Output> OutputList; /** List of tokens. */ class SIMPLECPP_LIB TokenList { public: class Stream; explicit TokenList(std::vector<std::string> &filenames); /** generates a token list from the given std::istream parameter */ TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr); /** generates a token list from the given buffer */ TokenList(const unsigned char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr); /** generates a token list from the given buffer */ TokenList(const char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr); /** generates a token list from the given filename parameter */ TokenList(const std::string &filename, std::vector<std::string> &filenames, OutputList *outputList = nullptr); TokenList(const TokenList &other); #if __cplusplus >= 201103L TokenList(TokenList &&other); #endif ~TokenList(); TokenList &operator=(const TokenList &other); #if __cplusplus >= 201103L TokenList &operator=(TokenList &&other); #endif void clear(); bool empty() const { return !frontToken; } void push_back(Token *tok); void dump() const; std::string stringify() const; void readfile(Stream &stream, const std::string &filename=std::string(), OutputList *outputList = nullptr); void constFold(); void removeComments(); Token *front() { return frontToken; } const Token *cfront() const { return frontToken; } Token *back() { return backToken; } const Token *cback() const { return backToken; } void deleteToken(Token *tok) { if (!tok) return; Token * const prev = tok->previous; Token * const next = tok->next; if (prev) prev->next = next; if (next) next->previous = prev; if (frontToken == tok) frontToken = next; if (backToken == tok) backToken = prev; delete tok; } void takeTokens(TokenList &other) { if (!other.frontToken) return; if (!frontToken) { frontToken = other.frontToken; } else { backToken->next = other.frontToken; other.frontToken->previous = backToken; } backToken = other.backToken; other.frontToken = other.backToken = nullptr; } /** sizeof(T) */ std::map<std::string, std::size_t> sizeOfType; const std::vector<std::string>& getFiles() const { return files; } private: void combineOperators(); void constFoldUnaryNotPosNeg(Token *tok); void constFoldMulDivRem(Token *tok); void constFoldAddSub(Token *tok); void constFoldShift(Token *tok); void constFoldComparison(Token *tok); void constFoldBitwise(Token *tok); void constFoldLogicalOp(Token *tok); void constFoldQuestionOp(Token **tok1); std::string readUntil(Stream &stream, const Location &location, char start, char end, OutputList *outputList); void lineDirective(unsigned int fileIndex, unsigned int line, Location *location); std::string lastLine(int maxsize=1000) const; const Token* lastLineTok(int maxsize=1000) const; bool isLastLinePreprocessor(int maxsize=1000) const; unsigned int fileIndex(const std::string &filename); Token *frontToken; Token *backToken; std::vector<std::string> &files; }; /** Tracking how macros are used */ struct SIMPLECPP_LIB MacroUsage { explicit MacroUsage(const std::vector<std::string> &f, bool macroValueKnown_) : macroLocation(f), useLocation(f), macroValueKnown(macroValueKnown_) {} std::string macroName; Location macroLocation; Location useLocation; bool macroValueKnown; }; /** Tracking #if/#elif expressions */ struct SIMPLECPP_LIB IfCond { explicit IfCond(const Location& location, const std::string &E, long long result) : location(location), E(E), result(result) {} Location location; // location of #if/#elif std::string E; // preprocessed condition long long result; // condition result }; /** * Command line preprocessor settings. * On the command line these are configured by -D, -U, -I, --include, -std */ struct SIMPLECPP_LIB DUI { DUI() : clearIncludeCache(false), removeComments(false) {} std::list<std::string> defines; std::set<std::string> undefined; std::list<std::string> includePaths; std::list<std::string> includes; std::string std; bool clearIncludeCache; bool removeComments; /** remove comment tokens from included files */ }; SIMPLECPP_LIB long long characterLiteralToLL(const std::string& str); SIMPLECPP_LIB std::map<std::string, TokenList*> load(const TokenList &rawtokens, std::vector<std::string> &filenames, const DUI &dui, OutputList *outputList = nullptr); /** * Preprocess * @todo simplify interface * @param output TokenList that receives the preprocessing output * @param rawtokens Raw tokenlist for top sourcefile * @param files internal data of simplecpp * @param filedata output from simplecpp::load() * @param dui defines, undefs, and include paths * @param outputList output: list that will receive output messages * @param macroUsage output: macro usage * @param ifCond output: #if/#elif expressions */ SIMPLECPP_LIB void preprocess(TokenList &output, const TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, TokenList*> &filedata, const DUI &dui, OutputList *outputList = nullptr, std::list<MacroUsage> *macroUsage = nullptr, std::list<IfCond> *ifCond = nullptr); /** * Deallocate data */ SIMPLECPP_LIB void cleanup(std::map<std::string, TokenList*> &filedata); /** Simplify path */ SIMPLECPP_LIB std::string simplifyPath(std::string path); /** Convert Cygwin path to Windows path */ SIMPLECPP_LIB std::string convertCygwinToWindowsPath(const std::string &cygwinPath); /** Returns the C version a given standard */ SIMPLECPP_LIB cstd_t getCStd(const std::string &std); /** Returns the C++ version a given standard */ SIMPLECPP_LIB cppstd_t getCppStd(const std::string &std); /** Returns the __STDC_VERSION__ value for a given standard */ SIMPLECPP_LIB std::string getCStdString(const std::string &std); SIMPLECPP_LIB std::string getCStdString(cstd_t std); /** Returns the __cplusplus value for a given standard */ SIMPLECPP_LIB std::string getCppStdString(const std::string &std); SIMPLECPP_LIB std::string getCppStdString(cppstd_t std); } #if defined(_MSC_VER) # pragma warning(pop) #endif #if (__cplusplus < 201103L) && !defined(__APPLE__) #undef nullptr #endif #endif
13,545
C++
.h
333
32.288288
291
0.611441
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,512
applicationlist.h
danmar_cppcheck/gui/applicationlist.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef APPLICATIONLIST_H #define APPLICATIONLIST_H #include "application.h" #include <QList> #include <QObject> #include <QString> /// @addtogroup GUI /// @{ /** * @brief List of applications user has specified to open errors with. */ class ApplicationList : public QObject { Q_OBJECT public: explicit ApplicationList(QObject *parent = nullptr); ~ApplicationList() override; /** * @brief Load all applications * * @return true if loading succeeded, false if there is problem with * application list. Most probably because of older version settings need * to be upgraded. */ bool loadSettings(); /** * @brief Save all applications */ void saveSettings() const; /** * @brief Get the amount of applications in the list * @return The count of applications */ int getApplicationCount() const; /** * @brief Get specific application's name * * @param index Index of the application whose name to get * @return Name of the application */ const Application& getApplication(int index) const; Application& getApplication(int index); /** * @brief Return the default application. * @return Index of the default application. */ int getDefaultApplication() const { return mDefaultApplicationIndex; } /** * @brief Add a new application * * @param app Application to add. */ void addApplication(const Application &app); /** * @brief Remove an application from the list * * @param index Index of the application to remove. */ void removeApplication(int index); /** * @brief Set application as default application. * @param index Index of the application to make the default one */ void setDefault(int index); /** * @brief Remove all applications from this list and copy all applications from * list given as a parameter. * @param list Copying source */ void copy(const ApplicationList *list); protected: /** * @brief Clear the list * */ void clear(); #ifdef _WIN32 /** * @brief Find editor used by default in Windows. * Check if Notepad++ is installed and use it. If not, use Notepad. */ bool findDefaultWindowsEditor(); #endif private: bool checkAndAddApplication(const QString& appPath, const QString& name, const QString& parameters); /** * @brief List of applications * */ QList<Application> mApplications; /** * @brief Index of the default application. * */ int mDefaultApplicationIndex = -1; }; /// @} #endif // APPLICATIONLIST_H
3,474
C++
.h
116
25.439655
104
0.68036
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,513
compliancereportdialog.h
danmar_cppcheck/gui/compliancereportdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COMPLIANCEREPORTDIALOG_H #define COMPLIANCEREPORTDIALOG_H #include <QDialog> #include <QObject> #include <QString> namespace Ui { class ComplianceReportDialog; } class ProjectFile; class QAbstractButton; class ComplianceReportDialog final : public QDialog { Q_OBJECT public: explicit ComplianceReportDialog(ProjectFile* projectFile, QString resultsFile, QString checkersReport); ~ComplianceReportDialog() final; private slots: void buttonClicked(QAbstractButton* button); private: void save(); Ui::ComplianceReportDialog *mUI; ProjectFile* mProjectFile; const QString mResultsFile; const QString mCheckersReport; }; #endif // COMPLIANCEREPORTDIALOG_H
1,471
C++
.h
43
31.674419
107
0.773625
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,514
newsuppressiondialog.h
danmar_cppcheck/gui/newsuppressiondialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NEWSUPPRESSIONDIALOG_H #define NEWSUPPRESSIONDIALOG_H #include "suppressions.h" #include <QDialog> #include <QObject> class QWidget; namespace Ui { class NewSuppressionDialog; } class NewSuppressionDialog : public QDialog { Q_OBJECT public: explicit NewSuppressionDialog(QWidget *parent = nullptr); NewSuppressionDialog(const NewSuppressionDialog &) = delete; ~NewSuppressionDialog() override; NewSuppressionDialog &operator=(const NewSuppressionDialog &) = delete; /** * @brief Translate the user input in the GUI into a suppression * @return Cppcheck suppression */ SuppressionList::Suppression getSuppression() const; /** * @brief Update the GUI so it corresponds with the given * Cppcheck suppression * @param suppression Cppcheck suppression */ void setSuppression(const SuppressionList::Suppression &suppression); private: Ui::NewSuppressionDialog *mUI; }; #endif // NEWSUPPRESSIONDIALOG_H
1,755
C++
.h
48
33.375
75
0.751915
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,515
erroritem.h
danmar_cppcheck/gui/erroritem.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ERRORITEM_H #define ERRORITEM_H #include "errorlogger.h" #include "errortypes.h" #include <QList> #include <QMetaType> #include <QString> /// @addtogroup GUI /// @{ /** * @brief GUI versions of severity conversions. * GUI needs wrappers for conversion functions since GUI uses Qt's QString * instead of the std::string used by lib/cli. */ class GuiSeverity { public: static QString toString(Severity severity) { return QString::fromStdString(severityToString(severity)); } static Severity fromString(const QString &severity) { return severityFromString(severity.toStdString()); } }; /** * @brief A class containing data for one error path item */ class QErrorPathItem { public: QErrorPathItem() : line(0), column(-1) {} explicit QErrorPathItem(const ErrorMessage::FileLocation &loc); QString file; int line; int column; QString info; }; bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2); /** * @brief A class containing error data for one error. * * The paths are stored with internal ("/") separators. Only when we show the * path or copy if for user (to clipboard) we convert to native separators. * 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 { public: ErrorItem(); explicit ErrorItem(const ErrorMessage &errmsg); /** * @brief Convert error item to string. * @return Error item as string. */ QString toString() const; QString tool() const; QString file0; QString errorId; Severity severity; bool inconclusive; QString summary; QString message; int cwe; unsigned long long hash; QList<QErrorPathItem> errorPath; QString symbolNames; QString remark; QString classification; // misra/cert/etc: classification/level QString guideline; // misra/cert/etc: guideline/rule // Special GUI properties QString sinceDate; QString tags; /** * Compare "CID" */ static bool sameCID(const ErrorItem &errorItem1, const ErrorItem &errorItem2); }; // NOLINTNEXTLINE(performance-no-int-to-ptr) Q_DECLARE_METATYPE(ErrorItem) /** * @brief A class containing error data for one shown error line. */ class ErrorLine { public: QString file; int line; QString file0; QString errorId; int cwe; unsigned long long hash; bool inconclusive; Severity severity; QString summary; QString message; QString sinceDate; QString tags; QString remark; }; /// @} #endif // ERRORITEM_H
3,396
C++
.h
115
26.156522
82
0.72212
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,517
codeeditor.h
danmar_cppcheck/gui/codeeditor.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CODEEDITOR_H #define CODEEDITOR_H #include <cstdint> #include <QObject> #include <QPlainTextEdit> #include <QRegularExpression> #include <QSize> #include <QString> #include <QStringList> #include <QSyntaxHighlighter> #include <QTextCharFormat> #include <QVector> #include <QWidget> class CodeEditorStyle; class QPaintEvent; class QRect; class QResizeEvent; class QTextDocument; class Highlighter : public QSyntaxHighlighter { Q_OBJECT public: explicit Highlighter(QTextDocument *parent, CodeEditorStyle *widgetStyle); void setSymbols(const QStringList &symbols); void setStyle(const CodeEditorStyle &newStyle); protected: void highlightBlock(const QString &text) override; private: enum RuleRole : std::uint8_t { Keyword = 1, Class = 2, Comment = 3, Quote = 4, Symbol = 5 }; struct HighlightingRule { QRegularExpression pattern; QTextCharFormat format; RuleRole ruleRole; }; void applyFormat(HighlightingRule &rule); QVector<HighlightingRule> mHighlightingRules; QVector<HighlightingRule> mHighlightingRulesWithSymbols; QRegularExpression mCommentStartExpression; QRegularExpression mCommentEndExpression; QTextCharFormat mKeywordFormat; QTextCharFormat mClassFormat; QTextCharFormat mSingleLineCommentFormat; QTextCharFormat mMultiLineCommentFormat; QTextCharFormat mQuotationFormat; QTextCharFormat mSymbolFormat; CodeEditorStyle *mWidgetStyle; }; class CodeEditor : public QPlainTextEdit { Q_OBJECT public: explicit CodeEditor(QWidget *parent); CodeEditor(const CodeEditor &) = delete; CodeEditor &operator=(const CodeEditor &) = delete; ~CodeEditor() override; void lineNumberAreaPaintEvent(const QPaintEvent *event); int lineNumberAreaWidth(); void setStyle(const CodeEditorStyle& newStyle); /** * Set source code to show, goto error line and highlight that line. * \param code The source code. * \param errorLine line number * \param symbols the related symbols, these are marked */ void setError(const QString &code, int errorLine, const QStringList &symbols); /** * Goto another error in existing source file * \param errorLine line number * \param symbols the related symbols, these are marked */ void setError(int errorLine, const QStringList &symbols); void setFileName(const QString &fileName) { mFileName = fileName; } const QString& getFileName() const { return mFileName; } void clear() { mFileName.clear(); setPlainText(QString()); } protected: void resizeEvent(QResizeEvent *event) override; private slots: void updateLineNumberAreaWidth(int newBlockCount); void highlightErrorLine(); void updateLineNumberArea(const QRect & /*rect*/, int /*dy*/); private: QString generateStyleString(); private: QWidget *mLineNumberArea; Highlighter *mHighlighter; CodeEditorStyle *mWidgetStyle; int mErrorPosition; QString mFileName; }; class LineNumberArea : public QWidget { public: explicit LineNumberArea(CodeEditor *editor) : QWidget(editor) { mCodeEditor = editor; } QSize sizeHint() const override { return QSize(mCodeEditor->lineNumberAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event) override { mCodeEditor->lineNumberAreaPaintEvent(event); } private: CodeEditor *mCodeEditor; }; #endif // CODEEDITOR_H
4,377
C++
.h
134
28.208955
82
0.729216
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,518
codeeditorstyle.h
danmar_cppcheck/gui/codeeditorstyle.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CODEEDITORSTYLE_H #define CODEEDITORSTYLE_H #include <QColor> #include <QFont> #include <QString> #include <Qt> const QString SETTINGS_STYLE_GROUP("EditorStyle"); const QString SETTINGS_STYLE_TYPE("StyleType"); const QString SETTINGS_STYLE_TYPE_LIGHT("DefaultLight"); const QString SETTINGS_STYLE_TYPE_DARK("DefaultDark"); const QString SETTINGS_STYLE_TYPE_CUSTOM("Custom"); const QString SETTINGS_STYLE_WIDGETFG("StyleWidgetFG"); const QString SETTINGS_STYLE_WIDGETBG("StyleWidgetBG"); const QString SETTINGS_STYLE_HILIFG("StyleHighlightFG"); const QString SETTINGS_STYLE_LINENUMFG("StyleLineNumFG"); const QString SETTINGS_STYLE_LINENUMBG("StyleLineNumBG"); const QString SETTINGS_STYLE_KEYWORDFG("StyleKeywordFG"); const QString SETTINGS_STYLE_KEYWORDWT("StyleKeywordWeight"); const QString SETTINGS_STYLE_CLASSFG("StyleClassFG"); const QString SETTINGS_STYLE_CLASSWT("StyleClassWeight"); const QString SETTINGS_STYLE_QUOTEFG("StyleQuoteFG"); const QString SETTINGS_STYLE_QUOTEWT("StyleQuoteWeight"); const QString SETTINGS_STYLE_COMMENTFG("StyleCommentFG"); const QString SETTINGS_STYLE_COMMENTWT("StyleCommentWeight"); const QString SETTINGS_STYLE_SYMBOLFG("StyleSymbolFG"); const QString SETTINGS_STYLE_SYMBOLBG("StyleSymbolBG"); const QString SETTINGS_STYLE_SYMBOLWT("StyleSymbolWeight"); class QSettings; class CodeEditorStyle { public: explicit CodeEditorStyle( // cppcheck-suppress naming-varname - TODO: fix this QColor CtrlFGColor, QColor CtrlBGColor, // cppcheck-suppress naming-varname - TODO: fix this QColor HiLiBGColor, // cppcheck-suppress naming-varname - TODO: fix this QColor LnNumFGColor, QColor LnNumBGColor, // cppcheck-suppress naming-varname - TODO: fix this QColor KeyWdFGColor, QFont::Weight KeyWdWeight, // cppcheck-suppress naming-varname - TODO: fix this QColor ClsFGColor, QFont::Weight ClsWeight, // cppcheck-suppress naming-varname - TODO: fix this QColor QteFGColor, QFont::Weight QteWeight, // cppcheck-suppress naming-varname - TODO: fix this QColor CmtFGColor, QFont::Weight CmtWeight, // cppcheck-suppress naming-varname - TODO: fix this QColor SymbFGColor, QColor SymbBGColor, // cppcheck-suppress naming-varname - TODO: fix this QFont::Weight SymbWeight); bool operator==(const CodeEditorStyle& rhs) const; bool operator!=(const CodeEditorStyle& rhs) const; bool isSystemTheme() const { return mSystemTheme; } static CodeEditorStyle getSystemTheme(); static CodeEditorStyle loadSettings(QSettings *settings); static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle); public: bool mSystemTheme{}; QColor widgetFGColor; QColor widgetBGColor; QColor highlightBGColor; QColor lineNumFGColor; QColor lineNumBGColor; QColor keywordColor; QFont::Weight keywordWeight; QColor classColor; QFont::Weight classWeight; QColor quoteColor; QFont::Weight quoteWeight; QColor commentColor; QFont::Weight commentWeight; QColor symbolFGColor; QColor symbolBGColor; QFont::Weight symbolWeight; }; static const CodeEditorStyle defaultStyleLight( /* editor FG/BG */ Qt::black, QColor(240, 240, 240), /* highlight BG */ QColor(255, 220, 220), /* line number FG/BG */ Qt::black, QColor(240, 240, 240), /* keyword FG/Weight */ Qt::darkBlue, QFont::Bold, /* class FG/Weight */ Qt::darkMagenta, QFont::Bold, /* quote FG/Weight */ Qt::darkGreen, QFont::Normal, /* comment FG/Weight */ Qt::gray, QFont::Normal, /* Symbol FG/BG/Weight */ Qt::red, QColor(220, 220, 255), QFont::Normal ); // Styling derived from Eclipse Color Theme - 'RecognEyes' // http://www.eclipsecolorthemes.org/?view=theme&id=30 static const CodeEditorStyle defaultStyleDark( /* editor FG/BG */ QColor(218, 218, 218), QColor(16, 16, 32), /* highlight BG */ QColor(64, 64, 64), /* line number FG/BG */ QColor(43, 145, 175), QColor(16, 16, 32), /* keyword FG/Weight */ QColor(0, 204, 204), QFont::Bold, /* class FG/Weight */ QColor(218, 0, 218), QFont::Bold, /* quote FG/Weight */ QColor(0, 204, 0), QFont::Normal, /* comment FG/Weight */ QColor(180, 180, 180), QFont::Normal, /* Symbol FG/BG/Weight */ QColor(218, 32, 32), QColor(32, 32, 108), QFont::Normal ); #endif /* CODEEDITORSTYLE_H */
5,203
C++
.h
116
40.818966
85
0.731823
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,519
cppchecklibrarydata.h
danmar_cppcheck/gui/cppchecklibrarydata.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CPPCHECKLIBRARYDATA_H #define CPPCHECKLIBRARYDATA_H #include "config.h" #include <cstdint> #include <QList> #include <QMap> #include <QPair> #include <QString> #include <QStringList> class QIODevice; class CppcheckLibraryData { public: CppcheckLibraryData() = default; struct Container { QString id; QString inherits; QString startPattern; QString endPattern; QString opLessAllowed; QString itEndPattern; bool access_arrayLike{}; int size_templateParameter = -1; struct { QString templateParameter; QString string; } type; struct RangeItemRecordType { QString name; QString templateParameter; }; struct Function { QString name; QString yields; QString action; }; QList<Function> accessFunctions; QList<Function> otherFunctions; QList<Function> sizeFunctions; QList<RangeItemRecordType> rangeItemRecordTypeList; }; struct Define { QString name; QString value; }; struct Function { QString comments; QString name; enum TrueFalseUnknown : std::uint8_t { False, True, Unknown } noreturn = Unknown; bool gccPure{}; bool gccConst{}; bool leakignore{}; bool useretval{}; struct ReturnValue { QString type; QString value; int container = -1; bool empty() const { return type.isNull() && value.isNull() && container < 0; } } returnValue; struct { QString scan; QString secure; } formatstr; struct Arg { QString name; unsigned int nr{}; static const unsigned int ANY; static const unsigned int VARIADIC; QString defaultValue; bool notbool{}; bool notnull{}; bool notuninit{}; bool formatstr{}; bool strz{}; QString valid; struct MinSize { QString type; QString arg; QString arg2; }; QList<MinSize> minsizes; struct Iterator { int container = -1; QString type; } iterator; }; QList<Arg> args; struct { QString severity; QString cstd; QString reason; QString alternatives; QString msg; bool isEmpty() const { return cstd.isEmpty() && severity.isEmpty() && reason.isEmpty() && alternatives.isEmpty() && msg.isEmpty(); } } warn; QMap<QString, QString> notOverlappingDataArgs; QMap<QString, QString> containerAttributes; }; struct MemoryResource { QString type; // "memory" or "resource" struct Alloc { bool isRealloc{}; bool init{}; int arg = -1; // -1: Has no optional "realloc-arg" attribute int reallocArg = -1; // -1: Has no optional "arg" attribute QString bufferSize; QString name; }; struct Dealloc { int arg = -1; // -1: Has no optional "arg" attribute QString name; }; QList<Alloc> alloc; QList<Dealloc> dealloc; QStringList use; }; struct PodType { QString name; QString stdtype; QString size; QString sign; }; struct PlatformType { QString name; QString value; QStringList types; // Keeps element names w/o attribute (e.g. unsigned) QStringList platforms; // Keeps "type" attribute of each "platform" element }; using TypeChecks = QList<QPair<QString, QString>>; struct Reflection { struct Call { int arg = -1; // -1: Mandatory "arg" attribute not available QString name; }; QList<Call> calls; }; struct Markup { struct CodeBlocks { QStringList blocks; int offset = -1; QString start; QString end; }; struct Exporter { QString prefix; QStringList prefixList; QStringList suffixList; }; QString ext; bool afterCode{}; bool reportErrors{}; QStringList keywords; QStringList importer; QList<CodeBlocks> codeBlocks; QList<Exporter> exporter; }; struct SmartPointer { QString name; bool unique{}; }; struct Entrypoint { QString name; }; void clear() { containers.clear(); defines.clear(); undefines.clear(); functions.clear(); memoryresource.clear(); podtypes.clear(); smartPointers.clear(); typeChecks.clear(); platformTypes.clear(); reflections.clear(); markups.clear(); entrypoints.clear(); } void swap(CppcheckLibraryData &other) NOEXCEPT { containers.swap(other.containers); defines.swap(other.defines); undefines.swap(other.undefines); functions.swap(other.functions); memoryresource.swap(other.memoryresource); podtypes.swap(other.podtypes); smartPointers.swap(other.smartPointers); typeChecks.swap(other.typeChecks); platformTypes.swap(other.platformTypes); reflections.swap(other.reflections); markups.swap(other.markups); entrypoints.swap(other.entrypoints); } QString open(QIODevice &file); QString toString() const; QList<Container> containers; QList<Define> defines; QList<Function> functions; QList<MemoryResource> memoryresource; QList<PodType> podtypes; QList<TypeChecks> typeChecks; QList<PlatformType> platformTypes; QStringList undefines; QList<SmartPointer> smartPointers; QList<Reflection> reflections; QList<Markup> markups; QList<Entrypoint> entrypoints; }; #endif // CPPCHECKLIBRARYDATA_H
7,086
C++
.h
231
21.792208
89
0.588097
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,522
txtreport.h
danmar_cppcheck/gui/txtreport.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TXT_REPORT_H #define TXT_REPORT_H #include "report.h" #include <QString> #include <QObject> #include <QTextStream> class ErrorItem; /// @addtogroup GUI /// @{ /** * @brief Text file report. * This report mimics the output of the command line cppcheck. */ class TxtReport : public Report { Q_OBJECT public: explicit TxtReport(const QString &filename); /** * @brief Create the report (file). * @return true if succeeded, false if file could not be created. */ bool create() override; /** * @brief Write report header. */ void writeHeader() override; /** * @brief Write report footer. */ void writeFooter() override; /** * @brief Write error to report. * @param error Error data. */ void writeError(const ErrorItem &error) override; private: /** * @brief Text stream writer for writing the report in text format. */ QTextStream mTxtWriter; }; /// @} #endif // TXT_REPORT_H
1,765
C++
.h
60
26.066667
72
0.694855
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,523
resultsview.h
danmar_cppcheck/gui/resultsview.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef RESULTSVIEW_H #define RESULTSVIEW_H #include "report.h" #include "showtypes.h" #include <cstdint> #include <QObject> #include <QString> #include <QStringList> #include <QWidget> class ErrorItem; class Settings; class ApplicationList; class ThreadHandler; class QModelIndex; class QPrinter; class QSettings; class CheckStatistics; class QPoint; enum class ReportType : std::uint8_t; namespace Ui { class ResultsView; } /// @addtogroup GUI /// @{ /** * @brief Widget to show cppcheck progressbar and result * */ class ResultsView : public QWidget { Q_OBJECT public: explicit ResultsView(QWidget * parent = nullptr); void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler); ResultsView(const ResultsView &) = delete; ~ResultsView() override; ResultsView &operator=(const ResultsView &) = delete; /** * @brief Clear results and statistics and reset progressinfo. * @param results Remove all the results from view? */ void clear(bool results); /** * @brief Remove a file from the results. */ void clear(const QString &filename); /** * @brief Remove a recheck file from the results. */ void clearRecheckFile(const QString &filename); /** * @brief Write statistics in file * * @param filename Filename to save statistics to */ void saveStatistics(const QString &filename) const; /** * @brief Save results to a file * * @param filename Filename to save results to * @param type Type of the report. * @param productName Custom product name */ void save(const QString &filename, Report::Type type, const QString& productName) const; /** * @brief Update results from old report (tag, sinceDate) */ void updateFromOldReport(const QString &filename) const; /** * @brief Update tree settings * * @param showFullPath Show full path of files in the tree * @param saveFullPath Save full path of files in reports * @param saveAllErrors Save all visible errors * @param showNoErrorsMessage Show "no errors"? * @param showErrorId Show error id? * @param showInconclusive Show inconclusive? */ void updateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors, bool showNoErrorsMessage, bool showErrorId, bool showInconclusive); /** * @brief Update Code Editor Style * * Function will read updated Code Editor styling from * stored program settings. * * @param settings Pointer to QSettings Object */ void updateStyleSetting(QSettings *settings); /** * @brief Set the directory we are checking * * This is used to split error file path to relative if necessary * @param dir Directory we are checking */ void setCheckDirectory(const QString &dir); /** * @brief Get the directory we are checking * * @return Directory containing source files */ QString getCheckDirectory(); /** * Set settings used in checking */ void setCheckSettings(const Settings& settings); /** * @brief Inform the view that checking has started * * @param count Count of files to be checked. */ void checkingStarted(int count); /** * @brief Inform the view that checking finished. * */ void checkingFinished(); /** * @brief Do we have visible results to show? * * @return true if there is at least one warning/error to show. */ bool hasVisibleResults() const; /** * @brief Do we have results from check? * * @return true if there is at least one warning/error, hidden or visible. */ bool hasResults() const; /** * @brief Save View's settings * * @param settings program settings. */ void saveSettings(QSettings *settings); /** * @brief Translate this view * */ void translate(); /** * @brief This function should be called when analysis is stopped */ void stopAnalysis(); /** * @brief Are there successful results? * @return true if analysis finished without critical errors etc */ bool isSuccess() const; void disableProgressbar(); /** * @brief Read errors from report XML file. * @param filename Report file to read. * */ void readErrorsXml(const QString &filename); /** * @brief Return checking statistics. * @return Pointer to checking statistics. */ const CheckStatistics *getStatistics() const { return mStatistics; } /** * @brief Return Showtypes. * @return Pointer to Showtypes. */ const ShowTypes & getShowTypes() const; void setReportType(ReportType reportType); signals: /** * @brief Signal to be emitted when we have results * */ void gotResults(); /** * @brief Signal that results have been hidden or shown * * @param hidden true if there are some hidden results, or false if there are not */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void resultsHidden(bool hidden); /** * @brief Signal to perform recheck of selected files * * @param selectedFilesList list of selected files */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void checkSelected(QStringList selectedFilesList); /** Suppress Ids */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void suppressIds(QStringList ids); /** * @brief Show/hide certain type of errors * Refreshes the tree. * * @param type Type of error to show/hide * @param show Should specified errors be shown (true) or hidden (false) */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void showResults(ShowTypes::ShowType type, bool show); /** * @brief Show/hide cppcheck errors. * Refreshes the tree. * * @param show Should specified errors be shown (true) or hidden (false) */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void showCppcheckResults(bool show); /** * @brief Show/hide clang-tidy/clang-analyzer errors. * Refreshes the tree. * * @param show Should specified errors be shown (true) or hidden (false) */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void showClangResults(bool show); /** * @brief Collapse all results in the result list. */ void collapseAllResults(); /** * @brief Expand all results in the result list. */ void expandAllResults(); /** * @brief Show hidden results in the result list. */ void showHiddenResults(); public slots: /** * @brief Slot for updating the checking progress * * @param value Current progress value * @param description Description to accompany the progress */ void progress(int value, const QString& description); /** * @brief Slot for new error to be displayed * * @param item Error data */ void error(const ErrorItem &item); /** * @brief Filters the results in the result list. */ void filterResults(const QString& filter); /** * @brief Update detailed message when selected item is changed. * * @param index Position of new selected item. */ void updateDetails(const QModelIndex &index); /** * @brief Slot opening a print dialog to print the current report */ void print(); /** * @brief Slot printing the current report to the printer. * @param printer The printer used for printing the report. */ void print(QPrinter* printer); /** * @brief Slot opening a print preview dialog */ void printPreview(); /** * \brief Log message */ void log(const QString &str); /** * \brief debug message */ void debugError(const ErrorItem &item); /** * \brief Clear log messages */ void logClear(); /** * \brief Copy selected log message entry */ void logCopyEntry(); /** * \brief Copy all log messages */ void logCopyComplete(); private: /** * If provided ErrorItem is a critical error then display warning message * in the resultsview */ void handleCriticalError(const ErrorItem& item); /** * @brief Should we show a "No errors found dialog" every time no errors were found? */ bool mShowNoErrorsMessage = true; Ui::ResultsView *mUI; CheckStatistics *mStatistics; Settings* mCheckSettings = nullptr; /** * Set to true when checking finish successfully. Set to false whenever analysis starts. */ bool mSuccess = false; /** Critical error ids */ QString mCriticalErrors; private slots: /** * @brief Custom context menu for Analysis Log * @param pos Mouse click position */ void on_mListLog_customContextMenuRequested(const QPoint &pos); }; /// @} #endif // RESULTSVIEW_H
10,313
C++
.h
334
25.47006
105
0.666969
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,524
applicationdialog.h
danmar_cppcheck/gui/applicationdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef APPLICATIONDIALOG_H #define APPLICATIONDIALOG_H #include <QDialog> #include <QObject> #include <QString> class QWidget; class Application; namespace Ui { class ApplicationDialog; } /// @addtogroup GUI /// @{ /** * @brief Dialog to edit a startable application. * User can open errors with user specified applications. This is a dialog * to modify/add an application to open errors with. * */ class ApplicationDialog : public QDialog { Q_OBJECT public: /** * @brief Constructor. * @param title Title for the dialog. * @param app Application definition. * @param parent Parent widget. */ ApplicationDialog(const QString &title, Application &app, QWidget *parent = nullptr); ~ApplicationDialog() override; protected slots: void ok(); /** * @brief Slot to browse for an application * */ void browse(); protected: /** * @brief UI from the Qt designer * */ Ui::ApplicationDialog* mUI; private: /** * @brief Underlying Application */ Application& mApplication; }; /// @} #endif // APPLICATIONDIALOG_H
1,939
C++
.h
69
24.333333
74
0.693053
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,525
scratchpad.h
danmar_cppcheck/gui/scratchpad.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SCRATCHPAD_H #define SCRATCHPAD_H #include <QDialog> #include <QObject> class MainWindow; namespace Ui { class ScratchPad; } /// @addtogroup GUI /// @{ /** * @brief A window with a text field that . */ class ScratchPad : public QDialog { Q_OBJECT public: explicit ScratchPad(MainWindow& mainWindow); ~ScratchPad() override; /** * @brief Translate dialog */ void translate(); private slots: /** * @brief Called when check button is clicked. */ void checkButtonClicked(); private: Ui::ScratchPad *mUI; MainWindow& mMainWindow; }; /// @} #endif // SCRATCHPAD_H
1,400
C++
.h
50
25.24
72
0.714179
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,526
printablereport.h
danmar_cppcheck/gui/printablereport.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PRINTABLE_REPORT_H #define PRINTABLE_REPORT_H #include "report.h" #include <QString> class ErrorItem; /// @addtogroup GUI /// @{ /** * @brief Printable (in-memory) report. * This report formats results and exposes them for printing. */ class PrintableReport : public Report { public: PrintableReport(); /** * @brief Create the report (file). * @return true if succeeded, false if file could not be created. */ bool create() override; /** * @brief Write report header. */ void writeHeader() override; /** * @brief Write report footer. */ void writeFooter() override; /** * @brief Write error to report. * @param error Error data. */ void writeError(const ErrorItem &error) override; /** * @brief Returns the formatted report. */ const QString& getFormattedReportText() const; private: /** * @brief Stores the formatted report contents. */ QString mFormattedReport; }; /// @} #endif // PRINTABLE_REPORT_H
1,812
C++
.h
61
26.163934
72
0.692573
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,527
xmlreportv2.h
danmar_cppcheck/gui/xmlreportv2.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XML_REPORTV2_H #define XML_REPORTV2_H #include "erroritem.h" #include "xmlreport.h" #include <QList> #include <QString> class QXmlStreamReader; class QXmlStreamWriter; /// @addtogroup GUI /// @{ /** * @brief XML file report version 2. * This report outputs XML-formatted report. The XML format must match command * line version's XML output. */ class XmlReportV2 : public XmlReport { public: explicit XmlReportV2(const QString &filename, QString productName); ~XmlReportV2() override; /** * @brief Create the report (file). * @return true if succeeded, false if file could not be created. */ bool create() override; /** * @brief Open existing report file. */ bool open() override; /** * @brief Write report header. */ void writeHeader() override; /** * @brief Write report footer. */ void writeFooter() override; /** * @brief Write error to report. * @param error Error data. */ void writeError(const ErrorItem &error) override; /** * @brief Read contents of the report file. */ QList<ErrorItem> read() override; protected: /** * @brief Read and parse error item from XML stream. * @param reader XML stream reader to use. */ ErrorItem readError(const QXmlStreamReader *reader); private: /** Product name read from cppcheck.cfg */ const QString mProductName; /** * @brief XML stream reader for reading the report in XML format. */ QXmlStreamReader *mXmlReader; /** * @brief XML stream writer for writing the report in XML format. */ QXmlStreamWriter *mXmlWriter; }; /// @} #endif // XML_REPORTV2_H
2,481
C++
.h
82
26.45122
78
0.691016
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,528
threadresult.h
danmar_cppcheck/gui/threadresult.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef THREADRESULT_H #define THREADRESULT_H #include "color.h" #include "errorlogger.h" #include "filesettings.h" #include <list> #include <mutex> #include <string> #include <QObject> #include <QString> #include <QStringList> #include <QtGlobal> class ErrorItem; class ImportProject; /// @addtogroup GUI /// @{ /** * @brief Threads use this class to obtain new files to process and to publish results * */ class ThreadResult : public QObject, public ErrorLogger { Q_OBJECT public: ThreadResult() = default; /** * @brief Get next unprocessed file * @return File path */ QString getNextFile(); void getNextFileSettings(const FileSettings*& fs); /** * @brief Set list of files to check * @param files List of files to check */ void setFiles(const QStringList &files); void setProject(const ImportProject &prj); /** * @brief Clear files to check * */ void clearFiles(); /** * @brief Get the number of files to check * */ int getFileCount() const; /** * ErrorLogger methods */ void reportOut(const std::string &outmsg, Color c = Color::Reset) override; void reportErr(const ErrorMessage &msg) override; public slots: /** * @brief Slot threads use to signal this class that a specific file is checked * @param file File that is checked */ void fileChecked(const QString &file); signals: /** * @brief Progress signal * @param value Current progress * @param description Description of the current stage */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void progress(int value, const QString& description); /** * @brief Signal of a new error * * @param item Error data */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void error(const ErrorItem &item); /** * @brief Signal of a new log message * * @param logline Log line */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void log(const QString &logline); /** * @brief Signal of a debug error * * @param item Error data */ // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void debugError(const ErrorItem &item); protected: /** * @brief Mutex * */ mutable std::mutex mutex; /** * @brief List of files to check * */ QStringList mFiles; std::list<FileSettings> mFileSettings; std::list<FileSettings>::const_iterator mItNextFileSettings; /** * @brief Max progress * */ quint64 mMaxProgress{}; /** * @brief Current progress * */ quint64 mProgress{}; /** * @brief Current number of files checked * */ unsigned long mFilesChecked{}; /** * @brief Total number of files * */ unsigned long mTotalFiles{}; }; /// @} #endif // THREADRESULT_H
3,914
C++
.h
139
23.748201
105
0.676007
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,529
helpdialog.h
danmar_cppcheck/gui/helpdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef HELPDIALOG_H #define HELPDIALOG_H #include <QDialog> #include <QObject> #include <QTextBrowser> #include <QVariant> class QHelpEngine; class QUrl; class QWidget; namespace Ui { class HelpDialog; } class HelpBrowser : public QTextBrowser { public: explicit HelpBrowser(QWidget* parent = nullptr) : QTextBrowser(parent) {} HelpBrowser(const HelpBrowser&) = delete; HelpBrowser(HelpBrowser&&) = delete; HelpBrowser& operator=(const HelpBrowser&) = delete; HelpBrowser& operator=(HelpBrowser&&) = delete; void setHelpEngine(QHelpEngine *helpEngine); QVariant loadResource(int type, const QUrl& name) override; private: QHelpEngine* mHelpEngine{}; }; class HelpDialog : public QDialog { Q_OBJECT public: explicit HelpDialog(QWidget *parent = nullptr); ~HelpDialog() override; private: Ui::HelpDialog *mUi; QHelpEngine* mHelpEngine; }; #endif // HELPDIALOG_H
1,687
C++
.h
51
30.509804
77
0.748771
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,530
aboutdialog.h
danmar_cppcheck/gui/aboutdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ABOUT_DIALOG_H #define ABOUT_DIALOG_H #include <QDialog> #include <QObject> #include <QString> class QWidget; namespace Ui { class About; } /// @addtogroup GUI /// @{ /** * @brief About dialog * */ class AboutDialog : public QDialog { Q_OBJECT public: AboutDialog(const QString &version, const QString &extraVersion, QWidget *parent = nullptr); ~AboutDialog() override; private: Ui::About* mUI; }; /// @} #endif // ABOUT_DIALOG_H
1,262
C++
.h
44
25.909091
72
0.711808
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,531
precompiled_qmake.h
danmar_cppcheck/gui/precompiled_qmake.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "precompiled.h" #include <QDialog> #include <QObject> #include <QWidget>
858
C++
.h
22
37.227273
72
0.747305
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,532
libraryeditargdialog.h
danmar_cppcheck/gui/libraryeditargdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBRARYEDITARGDIALOG_H #define LIBRARYEDITARGDIALOG_H #include "cppchecklibrarydata.h" #include <QDialog> #include <QList> #include <QObject> class QWidget; namespace Ui { class LibraryEditArgDialog; } class LibraryEditArgDialog : public QDialog { Q_OBJECT public: LibraryEditArgDialog(QWidget *parent, const CppcheckLibraryData::Function::Arg &arg); LibraryEditArgDialog(const LibraryEditArgDialog &) = delete; ~LibraryEditArgDialog() override; LibraryEditArgDialog &operator=(const LibraryEditArgDialog &) = delete; CppcheckLibraryData::Function::Arg getArg() const; private slots: void minsizeChanged(); private: Ui::LibraryEditArgDialog *mUi; QList<CppcheckLibraryData::Function::Arg::MinSize> mMinSizes; }; #endif // LIBRARYEDITARGDIALOG_H
1,566
C++
.h
42
34.690476
89
0.768011
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,533
checkstatistics.h
danmar_cppcheck/gui/checkstatistics.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CHECKSTATISTICS_H #define CHECKSTATISTICS_H #include "showtypes.h" #include <QMap> #include <QObject> #include <QString> #include <QStringList> #include <set> #include <string> #include <utility> /// @addtogroup GUI /// @{ /** * A class for check statistics. */ class CheckStatistics : public QObject { public: explicit CheckStatistics(QObject *parent = nullptr); /** * @brief Add new checked item to statistics. * * @param tool Tool. * @param type Type of the item to add. */ void addItem(const QString &tool, ShowTypes::ShowType type); /** * @brief Add checker to statistics */ void addChecker(const QString& checker); /** * @brief Clear the statistics. * */ void clear(); /** * @brief Return statistics for given type. * * @param tool Tool. * @param type Type for which the statistics are returned. * @return Number of items of given type. */ unsigned getCount(const QString &tool, ShowTypes::ShowType type) const; const std::set<std::string>& getActiveCheckers() const { return mActiveCheckers; } int getNumberOfActiveCheckers() const { return mActiveCheckers.size(); } /** Get tools with results */ QStringList getTools() const; void setCheckersReport(QString report) { mCheckersReport = std::move(report); } const QString& getCheckersReport() const { return mCheckersReport; } private: QMap<QString, unsigned> mStyle; QMap<QString, unsigned> mWarning; QMap<QString, unsigned> mPerformance; QMap<QString, unsigned> mPortability; QMap<QString, unsigned> mInformation; QMap<QString, unsigned> mError; std::set<std::string> mActiveCheckers; QString mCheckersReport; }; /// @} #endif // CHECKSTATISTICS_H
2,615
C++
.h
85
26.764706
75
0.696777
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,534
report.h
danmar_cppcheck/gui/report.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef REPORT_H #define REPORT_H #include <cstdint> #include <QFile> #include <QObject> #include <QString> class ErrorItem; /// @addtogroup GUI /// @{ /** * @brief A base class for reports. */ class Report : public QObject { public: enum Type : std::uint8_t { TXT, XMLV2, CSV, }; explicit Report(QString filename); ~Report() override; /** * @brief Create the report (file). * @return true if succeeded, false if file could not be created. */ virtual bool create(); /** * @brief Open the existing report (file). * @return true if succeeded, false if file could not be created. */ virtual bool open(); /** * @brief Close the report (file). */ void close(); /** * @brief Write report header. */ virtual void writeHeader() = 0; /** * @brief Write report footer. */ virtual void writeFooter() = 0; /** * @brief Write error to report. * @param error Error data. */ virtual void writeError(const ErrorItem &error) = 0; protected: /** * @brief Get the file object where the report is written to. */ QFile* getFile(); private: /** * @brief Filename of the report. */ QString mFilename; /** * @brief Fileobject for the report file. */ QFile mFile; }; /// @} #endif // REPORT_H
2,167
C++
.h
82
22.341463
72
0.64925
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,535
codeeditstyledialog.h
danmar_cppcheck/gui/codeeditstyledialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CODEEDITSTYLEDIALOG_H #define CODEEDITSTYLEDIALOG_H #include "codeeditorstyle.h" #include <QColor> #include <QDialog> #include <QFont> #include <QObject> class CodeEditor; class SelectColorButton; class SelectFontWeightCombo; class QPushButton; class QWidget; class QString; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) class QStringList; #endif class StyleEditDialog : public QDialog { Q_OBJECT public: explicit StyleEditDialog(const CodeEditorStyle& newStyle, QWidget *parent = nullptr); CodeEditorStyle getStyle(); private: void updateControls(); void updateStyle(); public slots: void resetStyle(); void setStyleDefaultLight(); void setStyleDefaultDark(); void colorChangedWidgetFG(const QColor& newColor); void colorChangedWidgetBG(const QColor& newColor); void colorChangedHighlightBG(const QColor& newColor); void colorChangedLineNumFG(const QColor& newColor); void colorChangedLineNumBG(const QColor& newColor); void colorChangedKeywordFG(const QColor& newColor); void weightChangedKeyword(QFont::Weight newWeight); void colorChangedClassFG(const QColor& newColor); void weightChangedClass(QFont::Weight newWeight); void colorChangedQuoteFG(const QColor& newColor); void weightChangedQuote(QFont::Weight newWeight); void colorChangedCommentFG(const QColor& newColor); void weightChangedComment(QFont::Weight newWeight); void colorChangedSymbolFG(const QColor& newColor); void colorChangedSymbolBG(const QColor& newColor); void weightChangedSymbol(QFont::Weight newWeight); private: CodeEditorStyle mStyleIncoming; CodeEditorStyle mStyleOutgoing; CodeEditor *mSampleEditor; SelectColorButton *mBtnWidgetColorFG; SelectColorButton *mBtnWidgetColorBG; SelectColorButton *mBtnHighlightBG; SelectColorButton *mBtnLineNumFG; SelectColorButton *mBtnLineNumBG; SelectColorButton *mBtnKeywordFG; SelectFontWeightCombo *mCBKeywordWeight; SelectColorButton *mBtnClassFG; SelectFontWeightCombo *mCBClassWeight; SelectColorButton *mBtnQuoteFG; SelectFontWeightCombo *mCBQuoteWeight; SelectColorButton *mBtnCommentFG; SelectFontWeightCombo *mCBCommentWeight; SelectColorButton *mBtnSymbolFG; SelectColorButton *mBtnSymbolBG; SelectFontWeightCombo *mCBSymbolWeight; QPushButton *mBtnDefaultLight; QPushButton *mBtnDefaultDark; static const QString mSampleDocument; static const QStringList mErrSymbolsList; static const int mErrLineNum; }; #endif //CODEEDITSTYLEDIALOG_H
3,485
C++
.h
89
35.314607
72
0.755325
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,536
precompiled.h
danmar_cppcheck/gui/precompiled.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // IWYU pragma: begin_keep #include "checkthread.h" #include "codeeditor.h" #include "codeeditorstyle.h" #include "config.h" #include "cppcheck.h" #include "cppchecklibrarydata.h" #include "report.h" #include "showtypes.h" #include <QFile> #include <QVariant> // IWYU pragma: end_keep
1,063
C++
.h
30
33.8
72
0.751456
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,537
libraryaddfunctiondialog.h
danmar_cppcheck/gui/libraryaddfunctiondialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBRARYADDFUNCTIONDIALOG_H #define LIBRARYADDFUNCTIONDIALOG_H #include <QDialog> #include <QObject> #include <QString> class QWidget; namespace Ui { class LibraryAddFunctionDialog; } #define SIMPLENAME "[_a-zA-Z][_a-zA-Z0-9]*" // just a name #define SCOPENAME SIMPLENAME "(::" SIMPLENAME ")*" // names with optional scope #define NAMES SCOPENAME "(," SCOPENAME ")*" // names can be separated by comma class LibraryAddFunctionDialog : public QDialog { Q_OBJECT public: explicit LibraryAddFunctionDialog(QWidget *parent = nullptr); LibraryAddFunctionDialog(const LibraryAddFunctionDialog &) = delete; ~LibraryAddFunctionDialog() override; LibraryAddFunctionDialog &operator=(const LibraryAddFunctionDialog &) = delete; QString functionName() const; int numberOfArguments() const; private: Ui::LibraryAddFunctionDialog *mUi; }; #endif // LIBRARYADDFUNCTIONDIALOG_H
1,719
C++
.h
42
38.47619
93
0.741007
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,538
fileviewdialog.h
danmar_cppcheck/gui/fileviewdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FILEVIEW_DIALOG_H #define FILEVIEW_DIALOG_H #include <QDialog> #include <QObject> #include <QString> class QWidget; class QTextEdit; namespace Ui { class Fileview; } /// @addtogroup GUI /// @{ /** * @brief File view -dialog. * This dialog shows text files. It is used for showing the license file and * the authors list. * */ class FileViewDialog : public QDialog { Q_OBJECT public: FileViewDialog(const QString &file, const QString &title, QWidget *parent = nullptr); ~FileViewDialog() override; protected: /** * @brief Load text file contents to edit control. * * @param filename File to load. * @param edit Control where to load the file contents. */ void loadTextFile(const QString &filename, QTextEdit *edit); Ui::Fileview* mUI; }; /// @} #endif // FILEVIEW_DIALOG_H
1,648
C++
.h
54
27.259259
76
0.707071
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,539
checkthread.h
danmar_cppcheck/gui/checkthread.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CHECKTHREAD_H #define CHECKTHREAD_H #include "cppcheck.h" #include "suppressions.h" #include <atomic> #include <cstdint> #include <string> #include <vector> #include <QList> #include <QObject> #include <QString> #include <QStringList> #include <QThread> class Settings; class ThreadResult; struct FileSettings; /// @addtogroup GUI /// @{ /** * @brief Thread to run cppcheck * */ class CheckThread : public QThread { Q_OBJECT public: explicit CheckThread(ThreadResult &result); /** * @brief Set settings for cppcheck * * @param settings settings for cppcheck */ void check(const Settings &settings); /** * @brief Run whole program analysis * @param files All files * @param ctuInfo Ctu info for addons */ void analyseWholeProgram(const QStringList &files, const std::string& ctuInfo); void setAddonsAndTools(const QStringList &addonsAndTools) { mAddonsAndTools = addonsAndTools; } void setClangIncludePaths(const QStringList &s) { mClangIncludePaths = s; } void setSuppressions(const QList<SuppressionList::Suppression> &s) { mSuppressions = s; } /** * @brief method that is run in a thread * */ void run() override; void stop(); /** * Determine command to run clang * \return Command to run clang, empty if it is not found */ static QString clangCmd(); /** * Determine command to run clang-tidy * \return Command to run clang-tidy, empty if it is not found */ static QString clangTidyCmd(); static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output); signals: /** * @brief cpp checking is done * */ void done(); // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void fileChecked(const QString &file); protected: /** * @brief States for the check thread. * Whole purpose of these states is to allow stopping of the checking. When * stopping we say for the thread (Stopping) that stop when current check * has been completed. Thread must be stopped cleanly, just terminating thread * likely causes unpredictable side-effects. */ enum State : std::uint8_t { Running, /**< The thread is checking. */ Stopping, /**< The thread will stop after current work. */ Stopped, /**< The thread has been stopped. */ Ready, /**< The thread is ready. */ }; /** * @brief Thread's current execution state. Can be changed from outside */ std::atomic<State> mState{Ready}; ThreadResult &mResult; /** * @brief Cppcheck itself */ CppCheck mCppcheck; private: void runAddonsAndTools(const FileSettings *fileSettings, const QString &fileName); void parseClangErrors(const QString &tool, const QString &file0, QString err); bool isSuppressed(const SuppressionList::ErrorMessage &errorMessage) const; QStringList mFiles; bool mAnalyseWholeProgram{}; std::string mCtuInfo; QStringList mAddonsAndTools; QStringList mClangIncludePaths; QList<SuppressionList::Suppression> mSuppressions; }; /// @} #endif // CHECKTHREAD_H
4,076
C++
.h
125
28.272
121
0.69819
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,540
platforms.h
danmar_cppcheck/gui/platforms.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PLATFORMS_H #define PLATFORMS_H #include "platform.h" #include <QList> #include <QObject> #include <QString> class QAction; /// @addtogroup GUI /// @{ /** * @brief Checked platform GUI-data. */ struct PlatformData { QString mTitle; /**< Text visible in the GUI. */ Platform::Type mType; /**< Type in the core. */ QAction *mActMainWindow; /**< Pointer to main window action item. */ }; /** * @brief List of checked platforms. */ class Platforms : public QObject { Q_OBJECT public: explicit Platforms(QObject *parent = nullptr); void add(const QString &title, Platform::Type platform); int getCount() const; void init(); PlatformData& get(Platform::Type platform); QList<PlatformData> mPlatforms; }; /// @} #endif // PLATFORMS_H
1,552
C++
.h
49
29.244898
72
0.718017
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false