10 #include "../utils/LexerUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
19 namespace readability {
21 void DeleteNullPointerCheck::registerMatchers(MatchFinder *Finder) {
22 const auto DeleteExpr =
23 cxxDeleteExpr(has(castExpr(has(declRefExpr(
24 to(decl(equalsBoundNode(
"deletedPointer"))))))))
27 const auto DeleteMemberExpr =
28 cxxDeleteExpr(has(castExpr(has(memberExpr(hasDeclaration(
29 fieldDecl(equalsBoundNode(
"deletedMemberPointer"))))))))
30 .bind(
"deleteMemberExpr");
32 const auto PointerExpr = ignoringImpCasts(anyOf(
33 declRefExpr(to(decl().bind(
"deletedPointer"))),
34 memberExpr(hasDeclaration(fieldDecl().bind(
"deletedMemberPointer")))));
36 const auto PointerCondition = castExpr(hasCastKind(CK_PointerToBoolean),
37 hasSourceExpression(PointerExpr));
38 const auto BinaryPointerCheckCondition = binaryOperator(
39 hasOperands(castExpr(hasCastKind(CK_NullToPointer)), PointerExpr));
42 traverse(ast_type_traits::TK_AsIs,
44 anyOf(PointerCondition, BinaryPointerCheckCondition)),
45 hasThen(anyOf(DeleteExpr, DeleteMemberExpr,
46 compoundStmt(anyOf(has(DeleteExpr),
47 has(DeleteMemberExpr)),
50 .bind(
"ifWithDelete")),
54 void DeleteNullPointerCheck::check(
const MatchFinder::MatchResult &Result) {
55 const auto *IfWithDelete = Result.Nodes.getNodeAs<IfStmt>(
"ifWithDelete");
56 const auto *Compound = Result.Nodes.getNodeAs<CompoundStmt>(
"compound");
59 IfWithDelete->getBeginLoc(),
60 "'if' statement is unnecessary; deleting null pointer has no effect");
61 if (IfWithDelete->getElse())
65 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
66 IfWithDelete->getBeginLoc(),
68 *Result.SourceManager,
69 Result.Context->getLangOpts())
73 Diag << FixItHint::CreateRemoval(
74 CharSourceRange::getTokenRange(Compound->getLBracLoc()));
75 Diag << FixItHint::CreateRemoval(
76 CharSourceRange::getTokenRange(Compound->getRBracLoc()));