1 //===--- MultiLevelImplicitPointerConversionCheck.cpp - clang-tidy --------===//
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
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())
21 return 1U + getPointerLevel(PtrType
->castAs
<PointerType
>()->getPointeeType());
26 AST_MATCHER(ImplicitCastExpr
, isMultiLevelPointerConversion
) {
27 const QualType TargetType
= Node
.getType()
29 .getNonReferenceType()
30 .getUnqualifiedType();
31 const QualType SourceType
= Node
.getSubExpr()
34 .getNonReferenceType()
35 .getUnqualifiedType();
37 if (TargetType
== SourceType
)
40 const unsigned TargetPtrLevel
= getPointerLevel(TargetType
);
41 if (0U == TargetPtrLevel
)
44 const unsigned SourcePtrLevel
= getPointerLevel(SourceType
);
45 if (0U == SourcePtrLevel
)
48 return SourcePtrLevel
!= TargetPtrLevel
;
51 AST_MATCHER(QualType
, isPointerType
) {
53 Node
.getCanonicalType().getNonReferenceType().getUnqualifiedType();
55 return !Type
.isNull() && Type
->isPointerType();
60 void MultiLevelImplicitPointerConversionCheck::registerMatchers(
61 MatchFinder
*Finder
) {
63 implicitCastExpr(hasCastKind(CK_BitCast
), isMultiLevelPointerConversion(),
64 unless(hasParent(explicitCastExpr(
65 hasDestinationType(isPointerType())))))
70 std::optional
<TraversalKind
>
71 MultiLevelImplicitPointerConversionCheck::getCheckTraversalKind() const {
75 void MultiLevelImplicitPointerConversionCheck::check(
76 const MatchFinder::MatchResult
&Result
) {
77 const auto *MatchedExpr
= Result
.Nodes
.getNodeAs
<ImplicitCastExpr
>("expr");
78 QualType Target
= MatchedExpr
->getType().getDesugaredType(*Result
.Context
);
80 MatchedExpr
->getSubExpr()->getType().getDesugaredType(*Result
.Context
);
82 diag(MatchedExpr
->getExprLoc(), "multilevel pointer conversion from %0 to "
83 "%1, please use explicit cast")
87 } // namespace clang::tidy::bugprone