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
doesNoDiscardMacroExist(ASTContext & Context,const llvm::StringRef & MacroId)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 {
AST_MATCHER(CXXMethodDecl,isOverloadedOperator)33 AST_MATCHER(CXXMethodDecl, isOverloadedOperator) {
34 // Don't put ``[[nodiscard]]`` in front of operators.
35 return Node.isOverloadedOperator();
36 }
AST_MATCHER(CXXMethodDecl,isConversionOperator)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 }
AST_MATCHER(CXXMethodDecl,hasClassMutableFields)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 }
AST_MATCHER(ParmVarDecl,hasParameterPack)47 AST_MATCHER(ParmVarDecl, hasParameterPack) {
48 // Don't put ``[[nodiscard]]`` on functions with parameter pack arguments.
49 return Node.isParameterPack();
50 }
AST_MATCHER(CXXMethodDecl,hasTemplateReturnType)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 }
AST_MATCHER(CXXMethodDecl,isDefinitionOrInline)57 AST_MATCHER(CXXMethodDecl, isDefinitionOrInline) {
58 // A function definition, with optional inline but not the declaration.
59 return !(Node.isThisDeclarationADefinition() && Node.isOutOfLine());
60 }
AST_MATCHER(QualType,isInstantiationDependentType)61 AST_MATCHER(QualType, isInstantiationDependentType) {
62 return Node->isInstantiationDependentType();
63 }
AST_MATCHER(QualType,isNonConstReferenceOrPointer)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
UseNodiscardCheck(StringRef Name,ClangTidyContext * Context)78 UseNodiscardCheck::UseNodiscardCheck(StringRef Name, ClangTidyContext *Context)
79 : ClangTidyCheck(Name, Context),
80 NoDiscardMacro(Options.get("ReplacementString", "[[nodiscard]]")) {}
81
storeOptions(ClangTidyOptions::OptionMap & Opts)82 void UseNodiscardCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
83 Options.store(Opts, "ReplacementString", NoDiscardMacro);
84 }
85
registerMatchers(MatchFinder * Finder)86 void UseNodiscardCheck::registerMatchers(MatchFinder *Finder) {
87 auto FunctionObj =
88 cxxRecordDecl(hasAnyName("::std::function", "::boost::function"));
89
90 // Find all non-void const methods which have not already been marked to
91 // warn on unused result.
92 Finder->addMatcher(
93 cxxMethodDecl(
94 allOf(isConst(), isDefinitionOrInline(),
95 unless(anyOf(
96 returns(voidType()),
97 returns(hasDeclaration(decl(hasAttr(clang::attr::WarnUnusedResult)))),
98 isNoReturn(), isOverloadedOperator(),
99 isVariadic(), hasTemplateReturnType(),
100 hasClassMutableFields(), isConversionOperator(),
101 hasAttr(clang::attr::WarnUnusedResult),
102 hasType(isInstantiationDependentType()),
103 hasAnyParameter(anyOf(
104 parmVarDecl(anyOf(hasType(FunctionObj),
105 hasType(references(FunctionObj)))),
106 hasType(isNonConstReferenceOrPointer()),
107 hasParameterPack()))))))
108 .bind("no_discard"),
109 this);
110 }
111
check(const MatchFinder::MatchResult & Result)112 void UseNodiscardCheck::check(const MatchFinder::MatchResult &Result) {
113 const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMethodDecl>("no_discard");
114 // Don't make replacements if the location is invalid or in a macro.
115 SourceLocation Loc = MatchedDecl->getLocation();
116 if (Loc.isInvalid() || Loc.isMacroID())
117 return;
118
119 SourceLocation RetLoc = MatchedDecl->getInnerLocStart();
120
121 ASTContext &Context = *Result.Context;
122
123 auto Diag = diag(RetLoc, "function %0 should be marked " + NoDiscardMacro)
124 << MatchedDecl;
125
126 // Check for the existence of the keyword being used as the ``[[nodiscard]]``.
127 if (!doesNoDiscardMacroExist(Context, NoDiscardMacro))
128 return;
129
130 // Possible false positives include:
131 // 1. A const member function which returns a variable which is ignored
132 // but performs some external I/O operation and the return value could be
133 // ignored.
134 Diag << FixItHint::CreateInsertion(RetLoc, NoDiscardMacro + " ");
135 }
136
isLanguageVersionSupported(const LangOptions & LangOpts) const137 bool UseNodiscardCheck::isLanguageVersionSupported(
138 const LangOptions &LangOpts) const {
139 // If we use ``[[nodiscard]]`` attribute, we require at least C++17. Use a
140 // macro or ``__attribute__`` with pre c++17 compilers by using
141 // ReplacementString option.
142
143 if (NoDiscardMacro == "[[nodiscard]]")
144 return LangOpts.CPlusPlus17;
145
146 return LangOpts.CPlusPlus;
147 }
148
149 } // namespace modernize
150 } // namespace tidy
151 } // namespace clang
152