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