[Workflow] Try to fix code-formatter failing to find changes in some cases.
[llvm-project.git] / clang-tools-extra / clang-tidy / bugprone / MultiLevelImplicitPointerConversionCheck.cpp
blob4dd3cb57e6dd12d83faef394caad692420cb4842
1 //===--- MultiLevelImplicitPointerConversionCheck.cpp - clang-tidy --------===//
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 //===----------------------------------------------------------------------===//
9 #include "MultiLevelImplicitPointerConversionCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers;
15 namespace clang::tidy::bugprone {
17 static unsigned getPointerLevel(const QualType &PtrType) {
18 if (!PtrType->isPointerType())
19 return 0U;
21 return 1U + getPointerLevel(PtrType->castAs<PointerType>()->getPointeeType());
24 namespace {
26 AST_MATCHER(ImplicitCastExpr, isMultiLevelPointerConversion) {
27 const QualType TargetType = Node.getType()
28 .getCanonicalType()
29 .getNonReferenceType()
30 .getUnqualifiedType();
31 const QualType SourceType = Node.getSubExpr()
32 ->getType()
33 .getCanonicalType()
34 .getNonReferenceType()
35 .getUnqualifiedType();
37 if (TargetType == SourceType)
38 return false;
40 const unsigned TargetPtrLevel = getPointerLevel(TargetType);
41 if (0U == TargetPtrLevel)
42 return false;
44 const unsigned SourcePtrLevel = getPointerLevel(SourceType);
45 if (0U == SourcePtrLevel)
46 return false;
48 return SourcePtrLevel != TargetPtrLevel;
51 } // namespace
53 void MultiLevelImplicitPointerConversionCheck::registerMatchers(
54 MatchFinder *Finder) {
55 Finder->addMatcher(
56 implicitCastExpr(hasCastKind(CK_BitCast), isMultiLevelPointerConversion())
57 .bind("expr"),
58 this);
61 std::optional<TraversalKind>
62 MultiLevelImplicitPointerConversionCheck::getCheckTraversalKind() const {
63 return TK_AsIs;
66 void MultiLevelImplicitPointerConversionCheck::check(
67 const MatchFinder::MatchResult &Result) {
68 const auto *MatchedExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("expr");
69 QualType Target = MatchedExpr->getType().getDesugaredType(*Result.Context);
70 QualType Source =
71 MatchedExpr->getSubExpr()->getType().getDesugaredType(*Result.Context);
73 diag(MatchedExpr->getExprLoc(), "multilevel pointer conversion from %0 to "
74 "%1, please use explicit cast")
75 << Source << Target;
78 } // namespace clang::tidy::bugprone