clang-tools  11.0.0
UnhandledSelfAssignmentCheck.cpp
Go to the documentation of this file.
1 //===--- UnhandledSelfAssignmentCheck.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 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace bugprone {
18 
19 UnhandledSelfAssignmentCheck::UnhandledSelfAssignmentCheck(
20  StringRef Name, ClangTidyContext *Context)
21  : ClangTidyCheck(Name, Context),
22  WarnOnlyIfThisHasSuspiciousField(
23  Options.get("WarnOnlyIfThisHasSuspiciousField", true)) {}
24 
27  Options.store(Opts, "WarnOnlyIfThisHasSuspiciousField",
28  WarnOnlyIfThisHasSuspiciousField);
29 }
30 
32  // We don't care about deleted, default or implicit operator implementations.
33  const auto IsUserDefined = cxxMethodDecl(
34  isDefinition(), unless(anyOf(isDeleted(), isImplicit(), isDefaulted())));
35 
36  // We don't need to worry when a copy assignment operator gets the other
37  // object by value.
38  const auto HasReferenceParam =
39  cxxMethodDecl(hasParameter(0, parmVarDecl(hasType(referenceType()))));
40 
41  // Self-check: Code compares something with 'this' pointer. We don't check
42  // whether it is actually the parameter what we compare.
43  const auto HasNoSelfCheck = cxxMethodDecl(unless(anyOf(
44  hasDescendant(binaryOperator(hasAnyOperatorName("==", "!="),
45  has(ignoringParenCasts(cxxThisExpr())))),
46  hasDescendant(cxxOperatorCallExpr(
47  hasAnyOverloadedOperatorName("==", "!="), argumentCountIs(2),
48  has(ignoringParenCasts(cxxThisExpr())))))));
49 
50  // Both copy-and-swap and copy-and-move method creates a copy first and
51  // assign it to 'this' with swap or move.
52  // In the non-template case, we can search for the copy constructor call.
53  const auto HasNonTemplateSelfCopy = cxxMethodDecl(
54  ofClass(cxxRecordDecl(unless(hasAncestor(classTemplateDecl())))),
55  traverse(ast_type_traits::TK_AsIs,
56  hasDescendant(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
57  isCopyConstructor(), ofClass(equalsBoundNode("class"))))))));
58 
59  // In the template case, we need to handle two separate cases: 1) a local
60  // variable is created with the copy, 2) copy is created only as a temporary
61  // object.
62  const auto HasTemplateSelfCopy = cxxMethodDecl(
63  ofClass(cxxRecordDecl(hasAncestor(classTemplateDecl()))),
64  anyOf(hasDescendant(
65  varDecl(hasType(cxxRecordDecl(equalsBoundNode("class"))),
66  hasDescendant(parenListExpr()))),
67  hasDescendant(cxxUnresolvedConstructExpr(hasDescendant(declRefExpr(
68  hasType(cxxRecordDecl(equalsBoundNode("class")))))))));
69 
70  // If inside the copy assignment operator another assignment operator is
71  // called on 'this' we assume that self-check might be handled inside
72  // this nested operator.
73  const auto HasNoNestedSelfAssign =
74  cxxMethodDecl(unless(hasDescendant(cxxMemberCallExpr(callee(cxxMethodDecl(
75  hasName("operator="), ofClass(equalsBoundNode("class"))))))));
76 
77  DeclarationMatcher AdditionalMatcher = cxxMethodDecl();
78  if (WarnOnlyIfThisHasSuspiciousField) {
79  // Matcher for standard smart pointers.
80  const auto SmartPointerType = qualType(hasUnqualifiedDesugaredType(
81  recordType(hasDeclaration(classTemplateSpecializationDecl(
82  hasAnyName("::std::shared_ptr", "::std::unique_ptr",
83  "::std::weak_ptr", "::std::auto_ptr"),
84  templateArgumentCountIs(1))))));
85 
86  // We will warn only if the class has a pointer or a C array field which
87  // probably causes a problem during self-assignment (e.g. first resetting
88  // the pointer member, then trying to access the object pointed by the
89  // pointer, or memcpy overlapping arrays).
90  AdditionalMatcher = cxxMethodDecl(ofClass(cxxRecordDecl(
91  has(fieldDecl(anyOf(hasType(pointerType()), hasType(SmartPointerType),
92  hasType(arrayType())))))));
93  }
94 
95  Finder->addMatcher(cxxMethodDecl(ofClass(cxxRecordDecl().bind("class")),
96  isCopyAssignmentOperator(), IsUserDefined,
97  HasReferenceParam, HasNoSelfCheck,
98  unless(HasNonTemplateSelfCopy),
99  unless(HasTemplateSelfCopy),
100  HasNoNestedSelfAssign, AdditionalMatcher)
101  .bind("copyAssignmentOperator"),
102  this);
103 }
104 
106  const MatchFinder::MatchResult &Result) {
107  const auto *MatchedDecl =
108  Result.Nodes.getNodeAs<CXXMethodDecl>("copyAssignmentOperator");
109  diag(MatchedDecl->getLocation(),
110  "operator=() does not handle self-assignment properly");
111 }
112 
113 } // namespace bugprone
114 } // namespace tidy
115 } // namespace clang
clang::tidy::bugprone::UnhandledSelfAssignmentCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: UnhandledSelfAssignmentCheck.cpp:25
UnhandledSelfAssignmentCheck.h
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:114
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::bugprone::UnhandledSelfAssignmentCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: UnhandledSelfAssignmentCheck.cpp:31
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:471
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:76
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidyCheck.cpp:55
clang::tidy::bugprone::UnhandledSelfAssignmentCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: UnhandledSelfAssignmentCheck.cpp:105
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::ClangTidyCheck::OptionsView::store
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.
Definition: ClangTidyCheck.cpp:152
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:111