clang-tools 24.0.0git
UseNodiscardCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "../utils/Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/Type.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15
16using namespace clang::ast_matchers;
17using namespace clang::tidy::matchers;
18
19namespace clang::tidy::modernize {
20
21static bool doesNoDiscardMacroExist(ASTContext &Context,
22 const 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.starts_with("[[") || MacroId.starts_with("__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
32namespace {
33AST_MATCHER(CXXMethodDecl, isConversionOperator) {
34 // Don't put ``[[nodiscard]]`` in front of a conversion decl
35 // like operator bool().
36 return isa<CXXConversionDecl>(Node);
37}
38AST_MATCHER(CXXMethodDecl, hasClassMutableFields) {
39 // Don't put ``[[nodiscard]]`` on functions on classes with
40 // mutable member variables.
41 return Node.getParent()->hasMutableFields();
42}
43AST_MATCHER(ParmVarDecl, hasParameterPack) {
44 // Don't put ``[[nodiscard]]`` on functions with parameter pack arguments.
45 return Node.isParameterPack();
46}
47AST_MATCHER(CXXMethodDecl, hasTemplateReturnType) {
48 // Don't put ``[[nodiscard]]`` in front of functions returning a template
49 // type.
50 return Node.getReturnType()->isTemplateTypeParmType() ||
51 Node.getReturnType()->isInstantiationDependentType();
52}
53AST_MATCHER(CXXMethodDecl, isDefinitionOrInline) {
54 // A function definition, with optional inline but not the declaration.
55 return !(Node.isThisDeclarationADefinition() && Node.isOutOfLine());
56}
57AST_MATCHER(QualType, isInstantiationDependentType) {
58 return Node->isInstantiationDependentType();
59}
60AST_MATCHER(QualType, isNonConstReferenceOrPointer) {
61 // If the function has any non-const-reference arguments
62 // bool foo(A &a)
63 // or pointer arguments
64 // bool foo(A*)
65 // then they may not care about the return value because of passing data
66 // via the arguments.
67 return (Node->isTemplateTypeParmType() || Node->isPointerType() ||
68 (Node->isReferenceType() &&
69 !Node.getNonReferenceType().isConstQualified()) ||
70 Node->isInstantiationDependentType());
71}
72} // namespace
73
75 : ClangTidyCheck(Name, Context),
76 NoDiscardMacro(Options.get("ReplacementString", "[[nodiscard]]")) {}
77
79 Options.store(Opts, "ReplacementString", NoDiscardMacro);
80}
81
82void UseNodiscardCheck::registerMatchers(MatchFinder *Finder) {
83 const auto FunctionObj =
84 cxxRecordDecl(hasAnyName("::std::function", "::boost::function"));
85 const auto NoDiscardClassTemplateSpecialization =
86 classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl(
87 has(cxxRecordDecl(hasAttr(attr::WarnUnusedResult))))));
88
89 // Find all non-void const methods which have not already been marked to
90 // warn on unused result.
91 Finder->addMatcher(
92 cxxMethodDecl(
93 isConst(), isDefinitionOrInline(),
94 unless(anyOf(
95 returns(voidType()),
96 returns(hasDeclaration(decl(hasAttr(attr::WarnUnusedResult)))),
97 returns(hasUnqualifiedDesugaredType(recordType(
98 hasDeclaration(NoDiscardClassTemplateSpecialization)))),
99 isNoReturn(), isOverloadedOperator(), isVariadic(),
100 hasTemplateReturnType(), hasClassMutableFields(),
101 isConversionOperator(), hasAttr(attr::WarnUnusedResult),
102 hasType(isInstantiationDependentType()),
103 hasAnyParameter(
104 anyOf(parmVarDecl(anyOf(hasType(FunctionObj),
105 hasType(references(FunctionObj)))),
106 hasType(isNonConstReferenceOrPointer()),
107 hasParameterPack())))))
108 .bind("no_discard"),
109 this);
110}
111
112void 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 const SourceLocation Loc = MatchedDecl->getLocation();
116 if (Loc.isInvalid() || Loc.isMacroID())
117 return;
118
119 const SourceLocation RetLoc = MatchedDecl->getInnerLocStart();
120
121 ASTContext &Context = *Result.Context;
122
123 const auto Diag = diag(RetLoc, "function %0 should be marked %1")
124 << MatchedDecl << NoDiscardMacro;
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 + " ").str());
135}
136
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 clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseNodiscardCheck(StringRef Name, ClangTidyContext *Context)
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool doesNoDiscardMacroExist(ASTContext &Context, const StringRef &MacroId)
llvm::StringMap< ClangTidyValue > OptionMap