ClangTidyCheck.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. //===--- ClangTidyCheck.h - clang-tidy --------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H
  9. #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H
  10. #include "ClangTidyDiagnosticConsumer.h"
  11. #include "ClangTidyOptions.h"
  12. #include "clang/ASTMatchers/ASTMatchFinder.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include <optional>
  15. #include <type_traits>
  16. #include <utility>
  17. #include <vector>
  18. namespace clang {
  19. class SourceManager;
  20. namespace tidy {
  21. /// This class should be specialized by any enum type that needs to be converted
  22. /// to and from an \ref llvm::StringRef.
  23. template <class T> struct OptionEnumMapping {
  24. // Specializations of this struct must implement this function.
  25. static ArrayRef<std::pair<T, StringRef>> getEnumMapping() = delete;
  26. };
  27. /// Base class for all clang-tidy checks.
  28. ///
  29. /// To implement a ``ClangTidyCheck``, write a subclass and override some of the
  30. /// base class's methods. E.g. to implement a check that validates namespace
  31. /// declarations, override ``registerMatchers``:
  32. ///
  33. /// ~~~{.cpp}
  34. /// void registerMatchers(ast_matchers::MatchFinder *Finder) override {
  35. /// Finder->addMatcher(namespaceDecl().bind("namespace"), this);
  36. /// }
  37. /// ~~~
  38. ///
  39. /// and then override ``check(const MatchResult &Result)`` to do the actual
  40. /// check for each match.
  41. ///
  42. /// A new ``ClangTidyCheck`` instance is created per translation unit.
  43. ///
  44. /// FIXME: Figure out whether carrying information from one TU to another is
  45. /// useful/necessary.
  46. class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
  47. public:
  48. /// Initializes the check with \p CheckName and \p Context.
  49. ///
  50. /// Derived classes must implement the constructor with this signature or
  51. /// delegate it. If a check needs to read options, it can do this in the
  52. /// constructor using the Options.get() methods below.
  53. ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context);
  54. /// Override this to disable registering matchers and PP callbacks if an
  55. /// invalid language version is being used.
  56. ///
  57. /// For example if a check is examining overloaded functions then this should
  58. /// be overridden to return false when the CPlusPlus flag is not set in
  59. /// \p LangOpts.
  60. virtual bool isLanguageVersionSupported(const LangOptions &LangOpts) const {
  61. return true;
  62. }
  63. /// Override this to register ``PPCallbacks`` in the preprocessor.
  64. ///
  65. /// This should be used for clang-tidy checks that analyze preprocessor-
  66. /// dependent properties, e.g. include directives and macro definitions.
  67. ///
  68. /// This will only be executed if the function isLanguageVersionSupported
  69. /// returns true.
  70. ///
  71. /// There are two Preprocessors to choose from that differ in how they handle
  72. /// modular #includes:
  73. /// - PP is the real Preprocessor. It doesn't walk into modular #includes and
  74. /// thus doesn't generate PPCallbacks for their contents.
  75. /// - ModuleExpanderPP preprocesses the whole translation unit in the
  76. /// non-modular mode, which allows it to generate PPCallbacks not only for
  77. /// the main file and textual headers, but also for all transitively
  78. /// included modular headers when the analysis runs with modules enabled.
  79. /// When modules are not enabled ModuleExpanderPP just points to the real
  80. /// preprocessor.
  81. virtual void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
  82. Preprocessor *ModuleExpanderPP) {}
  83. /// Override this to register AST matchers with \p Finder.
  84. ///
  85. /// This should be used by clang-tidy checks that analyze code properties that
  86. /// dependent on AST knowledge.
  87. ///
  88. /// You can register as many matchers as necessary with \p Finder. Usually,
  89. /// "this" will be used as callback, but you can also specify other callback
  90. /// classes. Thereby, different matchers can trigger different callbacks.
  91. ///
  92. /// This will only be executed if the function isLanguageVersionSupported
  93. /// returns true.
  94. ///
  95. /// If you need to merge information between the different matchers, you can
  96. /// store these as members of the derived class. However, note that all
  97. /// matches occur in the order of the AST traversal.
  98. virtual void registerMatchers(ast_matchers::MatchFinder *Finder) {}
  99. /// ``ClangTidyChecks`` that register ASTMatchers should do the actual
  100. /// work in here.
  101. virtual void check(const ast_matchers::MatchFinder::MatchResult &Result) {}
  102. /// Add a diagnostic with the check's name.
  103. DiagnosticBuilder diag(SourceLocation Loc, StringRef Description,
  104. DiagnosticIDs::Level Level = DiagnosticIDs::Warning);
  105. /// Add a diagnostic with the check's name.
  106. DiagnosticBuilder diag(StringRef Description,
  107. DiagnosticIDs::Level Level = DiagnosticIDs::Warning);
  108. /// Adds a diagnostic to report errors in the check's configuration.
  109. DiagnosticBuilder
  110. configurationDiag(StringRef Description,
  111. DiagnosticIDs::Level Level = DiagnosticIDs::Warning) const;
  112. /// Should store all options supported by this check with their
  113. /// current values or default values for options that haven't been overridden.
  114. ///
  115. /// The check should use ``Options.store()`` to store each option it supports
  116. /// whether it has the default value or it has been overridden.
  117. virtual void storeOptions(ClangTidyOptions::OptionMap &Options) {}
  118. /// Provides access to the ``ClangTidyCheck`` options via check-local
  119. /// names.
  120. ///
  121. /// Methods of this class prepend ``CheckName + "."`` to translate check-local
  122. /// option names to global option names.
  123. class OptionsView {
  124. void diagnoseBadIntegerOption(const Twine &Lookup,
  125. StringRef Unparsed) const;
  126. void diagnoseBadBooleanOption(const Twine &Lookup,
  127. StringRef Unparsed) const;
  128. void diagnoseBadEnumOption(const Twine &Lookup, StringRef Unparsed,
  129. StringRef Suggestion = StringRef()) const;
  130. public:
  131. /// Initializes the instance using \p CheckName + "." as a prefix.
  132. OptionsView(StringRef CheckName,
  133. const ClangTidyOptions::OptionMap &CheckOptions,
  134. ClangTidyContext *Context);
  135. /// Read a named option from the ``Context``.
  136. ///
  137. /// Reads the option with the check-local name \p LocalName from the
  138. /// ``CheckOptions``. If the corresponding key is not present, return
  139. /// ``std::nullopt``.
  140. std::optional<StringRef> get(StringRef LocalName) const;
  141. /// Read a named option from the ``Context``.
  142. ///
  143. /// Reads the option with the check-local name \p LocalName from the
  144. /// ``CheckOptions``. If the corresponding key is not present, returns
  145. /// \p Default.
  146. StringRef get(StringRef LocalName, StringRef Default) const;
  147. /// Read a named option from the ``Context``.
  148. ///
  149. /// Reads the option with the check-local name \p LocalName from local or
  150. /// global ``CheckOptions``. Gets local option first. If local is not
  151. /// present, falls back to get global option. If global option is not
  152. /// present either, return ``std::nullopt``.
  153. std::optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
  154. /// Read a named option from the ``Context``.
  155. ///
  156. /// Reads the option with the check-local name \p LocalName from local or
  157. /// global ``CheckOptions``. Gets local option first. If local is not
  158. /// present, falls back to get global option. If global option is not
  159. /// present either, returns \p Default.
  160. StringRef getLocalOrGlobal(StringRef LocalName, StringRef Default) const;
  161. /// Read a named option from the ``Context`` and parse it as an
  162. /// integral type ``T``.
  163. ///
  164. /// Reads the option with the check-local name \p LocalName from the
  165. /// ``CheckOptions``. If the corresponding key is not present, return
  166. /// ``std::nullopt``.
  167. ///
  168. /// If the corresponding key can't be parsed as a ``T``, emit a
  169. /// diagnostic and return ``std::nullopt``.
  170. template <typename T>
  171. std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
  172. get(StringRef LocalName) const {
  173. if (std::optional<StringRef> Value = get(LocalName)) {
  174. T Result{};
  175. if (!StringRef(*Value).getAsInteger(10, Result))
  176. return Result;
  177. diagnoseBadIntegerOption(NamePrefix + LocalName, *Value);
  178. }
  179. return std::nullopt;
  180. }
  181. /// Read a named option from the ``Context`` and parse it as an
  182. /// integral type ``T``.
  183. ///
  184. /// Reads the option with the check-local name \p LocalName from the
  185. /// ``CheckOptions``. If the corresponding key is not present, return
  186. /// \p Default.
  187. ///
  188. /// If the corresponding key can't be parsed as a ``T``, emit a
  189. /// diagnostic and return \p Default.
  190. template <typename T>
  191. std::enable_if_t<std::is_integral<T>::value, T> get(StringRef LocalName,
  192. T Default) const {
  193. return get<T>(LocalName).value_or(Default);
  194. }
  195. /// Read a named option from the ``Context`` and parse it as an
  196. /// integral type ``T``.
  197. ///
  198. /// Reads the option with the check-local name \p LocalName from local or
  199. /// global ``CheckOptions``. Gets local option first. If local is not
  200. /// present, falls back to get global option. If global option is not
  201. /// present either, return ``std::nullopt``.
  202. ///
  203. /// If the corresponding key can't be parsed as a ``T``, emit a
  204. /// diagnostic and return ``std::nullopt``.
  205. template <typename T>
  206. std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
  207. getLocalOrGlobal(StringRef LocalName) const {
  208. std::optional<StringRef> ValueOr = get(LocalName);
  209. bool IsGlobal = false;
  210. if (!ValueOr) {
  211. IsGlobal = true;
  212. ValueOr = getLocalOrGlobal(LocalName);
  213. if (!ValueOr)
  214. return std::nullopt;
  215. }
  216. T Result{};
  217. if (!StringRef(*ValueOr).getAsInteger(10, Result))
  218. return Result;
  219. diagnoseBadIntegerOption(
  220. IsGlobal ? Twine(LocalName) : NamePrefix + LocalName, *ValueOr);
  221. return std::nullopt;
  222. }
  223. /// Read a named option from the ``Context`` and parse it as an
  224. /// integral type ``T``.
  225. ///
  226. /// Reads the option with the check-local name \p LocalName from local or
  227. /// global ``CheckOptions``. Gets local option first. If local is not
  228. /// present, falls back to get global option. If global option is not
  229. /// present either, return \p Default.
  230. ///
  231. /// If the corresponding key can't be parsed as a ``T``, emit a
  232. /// diagnostic and return \p Default.
  233. template <typename T>
  234. std::enable_if_t<std::is_integral<T>::value, T>
  235. getLocalOrGlobal(StringRef LocalName, T Default) const {
  236. return getLocalOrGlobal<T>(LocalName).value_or(Default);
  237. }
  238. /// Read a named option from the ``Context`` and parse it as an
  239. /// enum type ``T``.
  240. ///
  241. /// Reads the option with the check-local name \p LocalName from the
  242. /// ``CheckOptions``. If the corresponding key is not present, return
  243. /// ``std::nullopt``.
  244. ///
  245. /// If the corresponding key can't be parsed as a ``T``, emit a
  246. /// diagnostic and return ``std::nullopt``.
  247. ///
  248. /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
  249. /// supply the mapping required to convert between ``T`` and a string.
  250. template <typename T>
  251. std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
  252. get(StringRef LocalName, bool IgnoreCase = false) const {
  253. if (std::optional<int64_t> ValueOr =
  254. getEnumInt(LocalName, typeEraseMapping<T>(), false, IgnoreCase))
  255. return static_cast<T>(*ValueOr);
  256. return std::nullopt;
  257. }
  258. /// Read a named option from the ``Context`` and parse it as an
  259. /// enum type ``T``.
  260. ///
  261. /// Reads the option with the check-local name \p LocalName from the
  262. /// ``CheckOptions``. If the corresponding key is not present, return
  263. /// \p Default.
  264. ///
  265. /// If the corresponding key can't be parsed as a ``T``, emit a
  266. /// diagnostic and return \p Default.
  267. ///
  268. /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
  269. /// supply the mapping required to convert between ``T`` and a string.
  270. template <typename T>
  271. std::enable_if_t<std::is_enum<T>::value, T>
  272. get(StringRef LocalName, T Default, bool IgnoreCase = false) const {
  273. return get<T>(LocalName, IgnoreCase).value_or(Default);
  274. }
  275. /// Read a named option from the ``Context`` and parse it as an
  276. /// enum type ``T``.
  277. ///
  278. /// Reads the option with the check-local name \p LocalName from local or
  279. /// global ``CheckOptions``. Gets local option first. If local is not
  280. /// present, falls back to get global option. If global option is not
  281. /// present either, returns ``std::nullopt``.
  282. ///
  283. /// If the corresponding key can't be parsed as a ``T``, emit a
  284. /// diagnostic and return ``std::nullopt``.
  285. ///
  286. /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
  287. /// supply the mapping required to convert between ``T`` and a string.
  288. template <typename T>
  289. std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
  290. getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
  291. if (std::optional<int64_t> ValueOr =
  292. getEnumInt(LocalName, typeEraseMapping<T>(), true, IgnoreCase))
  293. return static_cast<T>(*ValueOr);
  294. return std::nullopt;
  295. }
  296. /// Read a named option from the ``Context`` and parse it as an
  297. /// enum type ``T``.
  298. ///
  299. /// Reads the option with the check-local name \p LocalName from local or
  300. /// global ``CheckOptions``. Gets local option first. If local is not
  301. /// present, falls back to get global option. If global option is not
  302. /// present either return \p Default.
  303. ///
  304. /// If the corresponding key can't be parsed as a ``T``, emit a
  305. /// diagnostic and return \p Default.
  306. ///
  307. /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
  308. /// supply the mapping required to convert between ``T`` and a string.
  309. template <typename T>
  310. std::enable_if_t<std::is_enum<T>::value, T>
  311. getLocalOrGlobal(StringRef LocalName, T Default,
  312. bool IgnoreCase = false) const {
  313. return getLocalOrGlobal<T>(LocalName, IgnoreCase).value_or(Default);
  314. }
  315. /// Stores an option with the check-local name \p LocalName with
  316. /// string value \p Value to \p Options.
  317. void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
  318. StringRef Value) const;
  319. /// Stores an option with the check-local name \p LocalName with
  320. /// integer value \p Value to \p Options.
  321. template <typename T>
  322. std::enable_if_t<std::is_integral<T>::value>
  323. store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
  324. T Value) const {
  325. storeInt(Options, LocalName, Value);
  326. }
  327. /// Stores an option with the check-local name \p LocalName as the string
  328. /// representation of the Enum \p Value to \p Options.
  329. ///
  330. /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
  331. /// supply the mapping required to convert between ``T`` and a string.
  332. template <typename T>
  333. std::enable_if_t<std::is_enum<T>::value>
  334. store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
  335. T Value) const {
  336. ArrayRef<std::pair<T, StringRef>> Mapping =
  337. OptionEnumMapping<T>::getEnumMapping();
  338. auto Iter = llvm::find_if(
  339. Mapping, [&](const std::pair<T, StringRef> &NameAndEnum) {
  340. return NameAndEnum.first == Value;
  341. });
  342. assert(Iter != Mapping.end() && "Unknown Case Value");
  343. store(Options, LocalName, Iter->second);
  344. }
  345. private:
  346. using NameAndValue = std::pair<int64_t, StringRef>;
  347. std::optional<int64_t> getEnumInt(StringRef LocalName,
  348. ArrayRef<NameAndValue> Mapping,
  349. bool CheckGlobal, bool IgnoreCase) const;
  350. template <typename T>
  351. std::enable_if_t<std::is_enum<T>::value, std::vector<NameAndValue>>
  352. typeEraseMapping() const {
  353. ArrayRef<std::pair<T, StringRef>> Mapping =
  354. OptionEnumMapping<T>::getEnumMapping();
  355. std::vector<NameAndValue> Result;
  356. Result.reserve(Mapping.size());
  357. for (auto &MappedItem : Mapping) {
  358. Result.emplace_back(static_cast<int64_t>(MappedItem.first),
  359. MappedItem.second);
  360. }
  361. return Result;
  362. }
  363. void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
  364. int64_t Value) const;
  365. std::string NamePrefix;
  366. const ClangTidyOptions::OptionMap &CheckOptions;
  367. ClangTidyContext *Context;
  368. };
  369. private:
  370. void run(const ast_matchers::MatchFinder::MatchResult &Result) override;
  371. StringRef getID() const override { return CheckName; }
  372. std::string CheckName;
  373. ClangTidyContext *Context;
  374. protected:
  375. OptionsView Options;
  376. /// Returns the main file name of the current translation unit.
  377. StringRef getCurrentMainFile() const { return Context->getCurrentFile(); }
  378. /// Returns the language options from the context.
  379. const LangOptions &getLangOpts() const { return Context->getLangOpts(); }
  380. /// Returns true when the check is run in a use case when only 1 fix will be
  381. /// applied at a time.
  382. bool areDiagsSelfContained() const {
  383. return Context->areDiagsSelfContained();
  384. }
  385. };
  386. /// Read a named option from the ``Context`` and parse it as a bool.
  387. ///
  388. /// Reads the option with the check-local name \p LocalName from the
  389. /// ``CheckOptions``. If the corresponding key is not present, return
  390. /// ``std::nullopt``.
  391. ///
  392. /// If the corresponding key can't be parsed as a bool, emit a
  393. /// diagnostic and return ``std::nullopt``.
  394. template <>
  395. std::optional<bool>
  396. ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
  397. /// Read a named option from the ``Context`` and parse it as a bool.
  398. ///
  399. /// Reads the option with the check-local name \p LocalName from the
  400. /// ``CheckOptions``. If the corresponding key is not present, return
  401. /// \p Default.
  402. ///
  403. /// If the corresponding key can't be parsed as a bool, emit a
  404. /// diagnostic and return \p Default.
  405. template <>
  406. std::optional<bool>
  407. ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const;
  408. /// Stores an option with the check-local name \p LocalName with
  409. /// bool value \p Value to \p Options.
  410. template <>
  411. void ClangTidyCheck::OptionsView::store<bool>(
  412. ClangTidyOptions::OptionMap &Options, StringRef LocalName,
  413. bool Value) const;
  414. } // namespace tidy
  415. } // namespace clang
  416. #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H