1 //===--- PreferIsaOrDynCastInConditionalsCheck.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 9 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_LLVM_PREFERISAORDYNCASTINCONDITIONALSCHECK_H 10 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_LLVM_PREFERISAORDYNCASTINCONDITIONALSCHECK_H 11 12 #include "../ClangTidyCheck.h" 13 14 namespace clang { 15 namespace tidy { 16 namespace llvm_check { 17 18 /// Looks at conditionals and finds and replaces cases of ``cast<>``, which will 19 /// assert rather than return a null pointer, and ``dyn_cast<>`` where 20 /// the return value is not captured. Additionally, finds and replaces cases that match the 21 /// pattern ``var && isa<X>(var)``, where ``var`` is evaluated twice. 22 /// 23 /// Finds cases like these: 24 /// \code 25 /// if (auto x = cast<X>(y)) {} 26 /// // is replaced by: 27 /// if (auto x = dyn_cast<X>(y)) {} 28 /// 29 /// if (cast<X>(y)) {} 30 /// // is replaced by: 31 /// if (isa<X>(y)) {} 32 /// 33 /// if (dyn_cast<X>(y)) {} 34 /// // is replaced by: 35 /// if (isa<X>(y)) {} 36 /// 37 /// if (var && isa<T>(var)) {} 38 /// // is replaced by: 39 /// if (isa_and_nonnull<T>(var.foo())) {} 40 /// \endcode 41 /// 42 /// // Other cases are ignored, e.g.: 43 /// \code 44 /// if (auto f = cast<Z>(y)->foo()) {} 45 /// if (cast<Z>(y)->foo()) {} 46 /// if (X.cast(y)) {} 47 /// \endcode 48 /// 49 /// For the user-facing documentation see: 50 /// http://clang.llvm.org/extra/clang-tidy/checks/llvm-prefer-isa-or-dyn-cast-in-conditionals.html 51 class PreferIsaOrDynCastInConditionalsCheck : public ClangTidyCheck { 52 public: PreferIsaOrDynCastInConditionalsCheck(StringRef Name,ClangTidyContext * Context)53 PreferIsaOrDynCastInConditionalsCheck(StringRef Name, 54 ClangTidyContext *Context) 55 : ClangTidyCheck(Name, Context) {} isLanguageVersionSupported(const LangOptions & LangOpts)56 bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { 57 return LangOpts.CPlusPlus; 58 } 59 void registerMatchers(ast_matchers::MatchFinder *Finder) override; 60 void check(const ast_matchers::MatchFinder::MatchResult &Result) override; 61 }; 62 63 } // namespace llvm_check 64 } // namespace tidy 65 } // namespace clang 66 67 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_LLVM_PREFERISAORDYNCASTINCONDITIONALSCHECK_H 68