clang-tools 10.0.0

UseNodiscardCheck.cpp
Go to the documentation of this file.
1 //===--- UseNodiscardCheck.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
9 #include "UseNodiscardCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/Decl.h"
12 #include "clang/AST/Type.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang {
18 namespace tidy {
19 namespace modernize {
20
21 static bool doesNoDiscardMacroExist(ASTContext &Context,
22 const llvm::StringRef &MacroId) {
23 // Don't check for the Macro existence if we are using an attribute
24 // either a C++17 standard attribute or pre C++17 syntax
25 if (MacroId.startswith("[[") || MacroId.startswith("__attribute__"))
26 return true;
27
28 // Otherwise look up the macro name in the context to see if its defined.
29 return Context.Idents.get(MacroId).hasMacroDefinition();
30 }
31
32 namespace {
33 AST_MATCHER(CXXMethodDecl, isOverloadedOperator) {
34 // Don't put ``[[nodiscard]]`` in front of operators.
35 return Node.isOverloadedOperator();
36 }
37 AST_MATCHER(CXXMethodDecl, isConversionOperator) {
38 // Don't put ``[[nodiscard]]`` in front of a conversion decl
39 // like operator bool().
40 return isa<CXXConversionDecl>(Node);
41 }
42 AST_MATCHER(CXXMethodDecl, hasClassMutableFields) {
43 // Don't put ``[[nodiscard]]`` on functions on classes with
44 // mutable member variables.
45 return Node.getParent()->hasMutableFields();
46 }
47 AST_MATCHER(ParmVarDecl, hasParameterPack) {
48 // Don't put ``[[nodiscard]]`` on functions with parameter pack arguments.
49 return Node.isParameterPack();
50 }
51 AST_MATCHER(CXXMethodDecl, hasTemplateReturnType) {
52 // Don't put ``[[nodiscard]]`` in front of functions returning a template
53 // type.
54 return Node.getReturnType()->isTemplateTypeParmType() ||
55 Node.getReturnType()->isInstantiationDependentType();
56 }
57 AST_MATCHER(CXXMethodDecl, isDefinitionOrInline) {
58 // A function definition, with optional inline but not the declaration.
59 return !(Node.isThisDeclarationADefinition() && Node.isOutOfLine());
60 }
61 AST_MATCHER(QualType, isInstantiationDependentType) {
62 return Node->isInstantiationDependentType();
63 }
64 AST_MATCHER(QualType, isNonConstReferenceOrPointer) {
65 // If the function has any non-const-reference arguments
66 // bool foo(A &a)
67 // or pointer arguments
68 // bool foo(A*)
69 // then they may not care about the return value because of passing data
70 // via the arguments.
71 return (Node->isTemplateTypeParmType() || Node->isPointerType() ||
72 (Node->isReferenceType() &&
73 !Node.getNonReferenceType().isConstQualified()) ||
74 Node->isInstantiationDependentType());
75 }
76 } // namespace
77
78 UseNodiscardCheck::UseNodiscardCheck(StringRef Name, ClangTidyContext *Context)
79 : ClangTidyCheck(Name, Context),
80 NoDiscardMacro(Options.get("ReplacementString", "[[nodiscard]]")) {}
81
82 void UseNodiscardCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
83 Options.store(Opts, "ReplacementString", NoDiscardMacro);
84 }
85
86 void UseNodiscardCheck::registerMatchers(MatchFinder *Finder) {
87 // If we use ``[[nodiscard]]`` attribute, we require at least C++17. Use a
88 // macro or ``__attribute__`` with pre c++17 compilers by using
89 // ReplacementString option.
90 if ((NoDiscardMacro == "[[nodiscard]]" && !getLangOpts().CPlusPlus17) ||
91 !getLangOpts().CPlusPlus)
92 return;
93
94 auto FunctionObj =
95 cxxRecordDecl(hasAnyName("::std::function", "::boost::function"));
96
97 // Find all non-void const methods which have not already been marked to
98 // warn on unused result.
99 Finder->addMatcher(
100 cxxMethodDecl(
101 allOf(isConst(), isDefinitionOrInline(),
102 unless(anyOf(
103 returns(voidType()),
104 returns(hasDeclaration(decl(hasAttr(clang::attr::WarnUnusedResult)))),
105 isNoReturn(), isOverloadedOperator(),
106 isVariadic(), hasTemplateReturnType(),
107 hasClassMutableFields(), isConversionOperator(),
108 hasAttr(clang::attr::WarnUnusedResult),
109 hasType(isInstantiationDependentType()),
110 hasAnyParameter(anyOf(
111 parmVarDecl(anyOf(hasType(FunctionObj),
112 hasType(references(FunctionObj)))),
113 hasType(isNonConstReferenceOrPointer()),
114 hasParameterPack()))))))
115 .bind("no_discard"),
116 this);
117 }
118
119 void UseNodiscardCheck::check(const MatchFinder::MatchResult &Result) {
120 const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMethodDecl>("no_discard");
121 // Don't make replacements if the location is invalid or in a macro.
122 SourceLocation Loc = MatchedDecl->getLocation();
123 if (Loc.isInvalid() || Loc.isMacroID())
124 return;
125
126 SourceLocation RetLoc = MatchedDecl->getInnerLocStart();
127
128 ASTContext &Context = *Result.Context;
129
130 auto Diag = diag(RetLoc, "function %0 should be marked " + NoDiscardMacro)
131 << MatchedDecl;
132
133 // Check for the existence of the keyword being used as the ``[[nodiscard]]``.
134 if (!doesNoDiscardMacroExist(Context, NoDiscardMacro))
135 return;
136
137 // Possible false positives include:
138 // 1. A const member function which returns a variable which is ignored
139 // but performs some external I/O operation and the return value could be
140 // ignored.
141 Diag << FixItHint::CreateInsertion(RetLoc, NoDiscardMacro + " ");
142 }
143
144 } // namespace modernize
145 } // namespace tidy
146 } // namespace clang
Loc
SourceLocation Loc
&#39;#&#39; location in the include directive
Definition: IncludeOrderCheck.cpp:37
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::modernize::doesNoDiscardMacroExist
static bool doesNoDiscardMacroExist(ASTContext &Context, const llvm::StringRef &MacroId)
Definition: UseNodiscardCheck.cpp:21
clang::tidy::modernize::UseNodiscardCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: UseNodiscardCheck.cpp:86
clang::ast_matchers::AST_MATCHER
AST_MATCHER(Expr, isMacroID)
Definition: PreferIsaOrDynCastInConditionalsCheck.cpp:18
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:47
clang::tidy::ClangTidyCheck::getLangOpts
const LangOptions & getLangOpts() const
Returns the language options from the context.
Definition: ClangTidyCheck.h:188
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:184
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:58
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
UseNodiscardCheck.h
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:97
clang::tidy::modernize::UseNodiscardCheck::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: UseNodiscardCheck.cpp:82
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:77
clang::tidy::modernize::UseNodiscardCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: UseNodiscardCheck.cpp:119
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidyCheck.cpp:21