Cppcheck
cppcheck.h
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2023 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 //---------------------------------------------------------------------------
20 #ifndef cppcheckH
21 #define cppcheckH
22 //---------------------------------------------------------------------------
23 
24 #include "analyzerinfo.h"
25 #include "check.h"
26 #include "color.h"
27 #include "config.h"
28 #include "errorlogger.h"
29 #include "settings.h"
30 
31 #include <cstddef>
32 #include <fstream>
33 #include <functional>
34 #include <list>
35 #include <map>
36 #include <memory>
37 #include <set>
38 #include <string>
39 #include <unordered_set>
40 #include <vector>
41 
42 class Tokenizer;
43 enum class SHOWTIME_MODES;
44 struct FileSettings;
46 
47 /// @addtogroup Core
48 /// @{
49 
50 /**
51  * @brief This is the base class which will use other classes to do
52  * static code analysis for C and C++ code to find possible
53  * errors or places that could be improved.
54  * Usage: See check() for more info.
55  */
57 public:
58  using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>;
59 
60  /**
61  * @brief Constructor.
62  */
63  CppCheck(ErrorLogger &errorLogger,
64  bool useGlobalSuppressions,
65  ExecuteCmdFn executeCommand);
66 
67  /**
68  * @brief Destructor.
69  */
70  ~CppCheck() override;
71 
72  /**
73  * @brief This starts the actual checking. Note that you must call
74  * parseFromArgs() or settings() and addFile() before calling this.
75  * @return amount of errors found or 0 if none were found.
76  */
77 
78  /**
79  * @brief Check the file.
80  * This function checks one given file for errors.
81  * @param path Path to the file to check.
82  * @return amount of errors found or 0 if none were found.
83  * @note You must set settings before calling this function (by calling
84  * settings()).
85  */
86  unsigned int check(const std::string &path);
87  unsigned int check(const FileSettings &fs);
88 
89  /**
90  * @brief Check the file.
91  * This function checks one "virtual" file. The file is not read from
92  * the disk but the content is given in @p content. In errors the @p path
93  * is used as a filename.
94  * @param path Path to the file to check.
95  * @param content File content as a string.
96  * @return amount of errors found or 0 if none were found.
97  * @note You must set settings before calling this function (by calling
98  * settings()).
99  */
100  unsigned int check(const std::string &path, const std::string &content);
101 
102  /**
103  * @brief Get reference to current settings.
104  * @return a reference to current settings
105  */
106  Settings &settings();
107 
108  /**
109  * @brief Returns current version number as a string.
110  * @return version, e.g. "1.38"
111  */
112  static const char * version();
113 
114  /**
115  * @brief Returns extra version info as a string.
116  * This is for returning extra version info, like Git commit id, build
117  * time/date etc.
118  * @return extra version info, e.g. "04d42151" (Git commit id).
119  */
120  static const char * extraVersion();
121 
122  /**
123  * @brief Call all "getErrorMessages" in all registered Check classes.
124  * Also print out XML header and footer.
125  */
126  static void getErrorMessages(ErrorLogger &errorlogger);
127 
128  void tooManyConfigsError(const std::string &file, const int numberOfConfigurations);
129  void purgedConfigurationMessage(const std::string &file, const std::string& configuration);
130 
131  /** Analyse whole program, run this after all TUs has been scanned.
132  * This is deprecated and the plan is to remove this when
133  * .analyzeinfo is good enough.
134  * Return true if an error is reported.
135  */
136  bool analyseWholeProgram();
137 
138  /** Analyze all files using clang-tidy */
139  void analyseClangTidy(const FileSettings &fileSettings);
140 
141  /** analyse whole program use .analyzeinfo files */
142  void analyseWholeProgram(const std::string &buildDir, const std::list<std::pair<std::string, std::size_t>> &files, const std::list<FileSettings>& fileSettings);
143 
144  /** Remove *.ctu-info files */
145  void removeCtuInfoFiles(const std::list<std::pair<std::string, std::size_t>>& files, const std::list<FileSettings>& fileSettings); // cppcheck-suppress functionConst // has side effects
146 
147  static void resetTimerResults();
148  static void printTimerResults(SHOWTIME_MODES mode);
149 
150  bool isPremiumCodingStandardId(const std::string& id) const;
151 
152  std::string getAddonMessage(const std::string& id, const std::string& text) const;
153 
154 private:
155 #ifdef HAVE_RULES
156  /** Are there "simple" rules */
157  bool hasRule(const std::string &tokenlist) const;
158 #endif
159 
160  /** @brief There has been an internal error => Report information message */
161  void internalError(const std::string &filename, const std::string &msg);
162 
163  /**
164  * @brief Check a file using stream
165  * @param filename file name
166  * @param cfgname cfg name
167  * @param fileStream stream the file content can be read from
168  * @return number of errors found
169  */
170  unsigned int checkFile(const std::string& filename, const std::string &cfgname, std::istream* fileStream = nullptr);
171 
172  /**
173  * @brief Check raw tokens
174  * @param tokenizer tokenizer instance
175  */
176  void checkRawTokens(const Tokenizer &tokenizer);
177 
178  /**
179  * @brief Check normal tokens
180  * @param tokenizer tokenizer instance
181  */
182  void checkNormalTokens(const Tokenizer &tokenizer);
183 
184  /**
185  * Execute addons
186  */
187  void executeAddons(const std::vector<std::string>& files, const std::string& file0);
188  void executeAddons(const std::string &dumpFile, const std::string& file0);
189 
190  /**
191  * Execute addons
192  */
193  void executeAddonsWholeProgram(const std::list<std::pair<std::string, std::size_t>> &files);
194 
195 #ifdef HAVE_RULES
196  /**
197  * @brief Execute rules, if any
198  * @param tokenlist token list to use (normal / simple)
199  * @param tokenizer tokenizer
200  */
201  void executeRules(const std::string &tokenlist, const Tokenizer &tokenizer);
202 #endif
203 
204  unsigned int checkClang(const std::string &path);
205 
206  /**
207  * @brief Errors and warnings are directed here.
208  *
209  * @param msg Errors messages are normally in format
210  * "[filepath:line number] Message", e.g.
211  * "[main.cpp:4] Uninitialized member variable"
212  */
213  void reportErr(const ErrorMessage &msg) override;
214 
215  /**
216  * @brief Information about progress is directed here.
217  *
218  * @param outmsg Message to show, e.g. "Checking main.cpp..."
219  */
220  void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
221 
222  // TODO: store hashes instead of the full messages
223  std::unordered_set<std::string> mErrorList;
225 
226  void reportProgress(const std::string &filename, const char stage[], const std::size_t value) override;
227 
229 
230  /** @brief Current preprocessor configuration */
231  std::string mCurrentConfig;
232 
233  using Location = std::pair<std::string, int>;
234  std::map<Location, std::set<std::string>> mLocationMacros; // What macros are used on a location?
235 
236  unsigned int mExitCode{};
237 
239 
240  /** Are there too many configs? */
241  bool mTooManyConfigs{};
242 
243  /** File info used for whole program analysis */
244  std::list<Check::FileInfo*> mFileInfo;
245 
247 
248  /** Callback for executing a shell command (exe, args, output) */
250 
251  std::ofstream mPlistFile;
252 
253  std::unique_ptr<CheckUnusedFunctions> mUnusedFunctionsCheck;
254 };
255 
256 /// @}
257 //---------------------------------------------------------------------------
258 #endif // cppcheckH
Analyzer information.
Definition: analyzerinfo.h:50
Check for functions never called.
This is the base class which will use other classes to do static code analysis for C and C++ code to ...
Definition: cppcheck.h:56
ErrorLogger & mErrorLogger
Definition: cppcheck.h:228
std::unordered_set< std::string > mErrorList
Definition: cppcheck.h:223
std::unique_ptr< CheckUnusedFunctions > mUnusedFunctionsCheck
Definition: cppcheck.h:253
AnalyzerInformation mAnalyzerInformation
Definition: cppcheck.h:246
Settings mSettings
Definition: cppcheck.h:224
std::string getAddonMessage(const std::string &id, const std::string &text) const
std::list< Check::FileInfo * > mFileInfo
File info used for whole program analysis.
Definition: cppcheck.h:244
std::function< int(std::string, std::vector< std::string >, std::string, std::string &)> ExecuteCmdFn
Definition: cppcheck.h:58
std::pair< std::string, int > Location
Definition: cppcheck.h:233
bool mUseGlobalSuppressions
Definition: cppcheck.h:238
std::string mCurrentConfig
Current preprocessor configuration.
Definition: cppcheck.h:231
std::ofstream mPlistFile
Definition: cppcheck.h:251
std::map< Location, std::set< std::string > > mLocationMacros
Definition: cppcheck.h:234
ExecuteCmdFn mExecuteCommand
Callback for executing a shell command (exe, args, output)
Definition: cppcheck.h:249
This is an interface, which the class responsible of error logging should implement.
Definition: errorlogger.h:217
virtual void reportErr(const ErrorMessage &msg)=0
Information about found errors and warnings is directed here.
virtual void reportOut(const std::string &outmsg, Color c=Color::Reset)=0
Information about progress is directed here.
virtual void reportProgress(const std::string &filename, const char stage[], const std::size_t value)
Report progress to client.
Definition: errorlogger.h:244
Wrapper for error messages, provided by reportErr()
Definition: errorlogger.h:48
This is just a container for general settings so that we don't need to pass individual values to func...
Definition: settings.h:96
The main purpose is to tokenize the source code.
Definition: tokenize.h:46
Color
Definition: color.h:27
#define CPPCHECKLIB
Definition: config.h:35
File settings.
Definition: filesettings.h:30
SHOWTIME_MODES
Definition: timer.h:30