clang-tools 20.0.0git
ContainerDataPointerCheck.cpp
Go to the documentation of this file.
1//===--- ContainerDataPointerCheck.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//===----------------------------------------------------------------------===//
8
10
11#include "../utils/Matchers.h"
12#include "../utils/OptionsUtils.h"
13#include "clang/Lex/Lexer.h"
14#include "llvm/ADT/StringRef.h"
15
16using namespace clang::ast_matchers;
17
19
20constexpr llvm::StringLiteral ContainerExprName = "container-expr";
21constexpr llvm::StringLiteral DerefContainerExprName = "deref-container-expr";
22constexpr llvm::StringLiteral AddrOfContainerExprName =
23 "addr-of-container-expr";
24constexpr llvm::StringLiteral AddressOfName = "address-of";
25
28 Options.store(Opts, "IgnoredContainers",
29 utils::options::serializeStringList(IgnoredContainers));
30}
31
33 ClangTidyContext *Context)
34 : ClangTidyCheck(Name, Context),
35 IgnoredContainers(utils::options::parseStringList(
36 Options.get("IgnoredContainers", ""))) {}
37
39 const auto Record =
40 cxxRecordDecl(
41 unless(matchers::matchesAnyListedName(IgnoredContainers)),
42 isSameOrDerivedFrom(
43 namedDecl(
44 has(cxxMethodDecl(isPublic(), hasName("data")).bind("data")))
45 .bind("container")))
46 .bind("record");
47
48 const auto NonTemplateContainerType =
49 qualType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(Record))));
50 const auto TemplateContainerType =
51 qualType(hasUnqualifiedDesugaredType(templateSpecializationType(
52 hasDeclaration(classTemplateDecl(has(Record))))));
53
54 const auto Container =
55 qualType(anyOf(NonTemplateContainerType, TemplateContainerType));
56
57 const auto ContainerExpr = anyOf(
58 unaryOperator(
59 hasOperatorName("*"),
60 hasUnaryOperand(
61 expr(hasType(pointsTo(Container))).bind(DerefContainerExprName)))
62 .bind(ContainerExprName),
63 unaryOperator(hasOperatorName("&"),
64 hasUnaryOperand(expr(anyOf(hasType(Container),
65 hasType(references(Container))))
67 .bind(ContainerExprName),
68 expr(anyOf(hasType(Container), hasType(pointsTo(Container)),
69 hasType(references(Container))))
70 .bind(ContainerExprName));
71
72 const auto Zero = integerLiteral(equals(0));
73
74 const auto SubscriptOperator = callee(cxxMethodDecl(hasName("operator[]")));
75
76 Finder->addMatcher(
77 unaryOperator(
78 unless(isExpansionInSystemHeader()), hasOperatorName("&"),
79 hasUnaryOperand(expr(
80 anyOf(cxxOperatorCallExpr(SubscriptOperator, argumentCountIs(2),
81 hasArgument(0, ContainerExpr),
82 hasArgument(1, Zero)),
83 cxxMemberCallExpr(SubscriptOperator, on(ContainerExpr),
84 argumentCountIs(1), hasArgument(0, Zero)),
85 arraySubscriptExpr(hasLHS(ContainerExpr), hasRHS(Zero))))))
86 .bind(AddressOfName),
87 this);
88}
89
90void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) {
91 const auto *UO = Result.Nodes.getNodeAs<UnaryOperator>(AddressOfName);
92 const auto *CE = Result.Nodes.getNodeAs<Expr>(ContainerExprName);
93 const auto *DCE = Result.Nodes.getNodeAs<Expr>(DerefContainerExprName);
94 const auto *ACE = Result.Nodes.getNodeAs<Expr>(AddrOfContainerExprName);
95
96 if (!UO || !CE)
97 return;
98
99 if (DCE && !CE->getType()->isPointerType())
100 CE = DCE;
101 else if (ACE)
102 CE = ACE;
103
104 SourceRange SrcRange = CE->getSourceRange();
105
106 std::string ReplacementText{
107 Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange),
108 *Result.SourceManager, getLangOpts())};
109
110 if (!isa<DeclRefExpr, ArraySubscriptExpr, CXXOperatorCallExpr, CallExpr,
111 MemberExpr>(CE))
112 ReplacementText = "(" + ReplacementText + ")";
113
114 if (CE->getType()->isPointerType())
115 ReplacementText += "->data()";
116 else
117 ReplacementText += ".data()";
118
119 FixItHint Hint =
120 FixItHint::CreateReplacement(UO->getSourceRange(), ReplacementText);
121 diag(UO->getBeginLoc(),
122 "'data' should be used for accessing the data pointer instead of taking "
123 "the address of the 0-th element")
124 << Hint;
125}
126} // namespace clang::tidy::readability
CaptureExpr CE
llvm::SmallString< 256U > Name
std::string Container
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
ContainerDataPointerCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(llvm::ArrayRef< StringRef > NameList)
constexpr llvm::StringLiteral AddressOfName
constexpr llvm::StringLiteral DerefContainerExprName
constexpr llvm::StringLiteral AddrOfContainerExprName
constexpr llvm::StringLiteral ContainerExprName
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap