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