clang-tools 19.0.0git
ConstReturnTypeCheck.cpp
Go to the documentation of this file.
1//===--- ConstReturnTypeCheck.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 "../utils/LexerUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Basic/SourceLocation.h"
14#include "clang/Lex/Lexer.h"
15#include <optional>
16
17using namespace clang::ast_matchers;
18
20
21// Finds the location of the qualifying `const` token in the `FunctionDecl`'s
22// return type. Returns `std::nullopt` when the return type is not
23// `const`-qualified or `const` does not appear in `Def`'s source, like when the
24// type is an alias or a macro.
25static std::optional<Token>
26findConstToRemove(const FunctionDecl *Def,
27 const MatchFinder::MatchResult &Result) {
28 if (!Def->getReturnType().isLocalConstQualified())
29 return std::nullopt;
30
31 // Get the begin location for the function name, including any qualifiers
32 // written in the source (for out-of-line declarations). A FunctionDecl's
33 // "location" is the start of its name, so, when the name is unqualified, we
34 // use `getLocation()`.
35 SourceLocation NameBeginLoc = Def->getQualifier()
36 ? Def->getQualifierLoc().getBeginLoc()
37 : Def->getLocation();
38 // Since either of the locs can be in a macro, use `makeFileCharRange` to be
39 // sure that we have a consistent `CharSourceRange`, located entirely in the
40 // source file.
41 CharSourceRange FileRange = Lexer::makeFileCharRange(
42 CharSourceRange::getCharRange(Def->getBeginLoc(), NameBeginLoc),
43 *Result.SourceManager, Result.Context->getLangOpts());
44
45 if (FileRange.isInvalid())
46 return std::nullopt;
47
49 tok::kw_const, FileRange, *Result.Context, *Result.SourceManager);
50}
51
52namespace {
53
54AST_MATCHER(QualType, isLocalConstQualified) {
55 return Node.isLocalConstQualified();
56}
57
58AST_MATCHER(QualType, isTypeOfType) {
59 return isa<TypeOfType>(Node.getTypePtr());
60}
61
62AST_MATCHER(QualType, isTypeOfExprType) {
63 return isa<TypeOfExprType>(Node.getTypePtr());
64}
65
66struct CheckResult {
67 // Source range of the relevant `const` token in the definition being checked.
68 CharSourceRange ConstRange;
69
70 // FixItHints associated with the definition being checked.
71 llvm::SmallVector<clang::FixItHint, 4> Hints;
72
73 // Locations of any declarations that could not be fixed.
74 llvm::SmallVector<clang::SourceLocation, 4> DeclLocs;
75};
76
77} // namespace
78
79// Does the actual work of the check.
80static CheckResult checkDef(const clang::FunctionDecl *Def,
81 const MatchFinder::MatchResult &MatchResult) {
82 CheckResult Result;
83 std::optional<Token> Tok = findConstToRemove(Def, MatchResult);
84 if (!Tok)
85 return Result;
86
87 Result.ConstRange =
88 CharSourceRange::getCharRange(Tok->getLocation(), Tok->getEndLoc());
89 Result.Hints.push_back(FixItHint::CreateRemoval(Result.ConstRange));
90
91 // Fix the definition and any visible declarations, but don't warn
92 // separately for each declaration. Instead, associate all fixes with the
93 // single warning at the definition.
94 for (const FunctionDecl *Decl = Def->getPreviousDecl(); Decl != nullptr;
95 Decl = Decl->getPreviousDecl()) {
96 if (std::optional<Token> T = findConstToRemove(Decl, MatchResult))
97 Result.Hints.push_back(FixItHint::CreateRemoval(
98 CharSourceRange::getCharRange(T->getLocation(), T->getEndLoc())));
99 else
100 // `getInnerLocStart` gives the start of the return type.
101 Result.DeclLocs.push_back(Decl->getInnerLocStart());
102 }
103 return Result;
104}
105
107 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
108}
109
110void ConstReturnTypeCheck::registerMatchers(MatchFinder *Finder) {
111 // Find all function definitions for which the return types are `const`
112 // qualified, ignoring decltype types.
113 auto NonLocalConstType =
114 qualType(unless(isLocalConstQualified()),
115 anyOf(decltypeType(), autoType(), isTypeOfType(),
116 isTypeOfExprType(), substTemplateTypeParmType()));
117 Finder->addMatcher(
118 functionDecl(
119 returns(allOf(isConstQualified(), unless(NonLocalConstType))),
120 anyOf(isDefinition(), cxxMethodDecl(isPure())),
121 // Overridden functions are not actionable.
122 unless(cxxMethodDecl(isOverride())))
123 .bind("func"),
124 this);
125}
126
127void ConstReturnTypeCheck::check(const MatchFinder::MatchResult &Result) {
128 const auto *Def = Result.Nodes.getNodeAs<FunctionDecl>("func");
129 // Suppress the check if macros are involved.
130 if (IgnoreMacros &&
131 (Def->getBeginLoc().isMacroID() || Def->getEndLoc().isMacroID()))
132 return;
133
134 CheckResult CR = checkDef(Def, Result);
135 {
136 // Clang only supports one in-flight diagnostic at a time. So, delimit the
137 // scope of `Diagnostic` to allow further diagnostics after the scope. We
138 // use `getInnerLocStart` to get the start of the return type.
139 DiagnosticBuilder Diagnostic =
140 diag(Def->getInnerLocStart(),
141 "return type %0 is 'const'-qualified at the top level, which may "
142 "reduce code readability without improving const correctness")
143 << Def->getReturnType();
144 if (CR.ConstRange.isValid())
145 Diagnostic << CR.ConstRange;
146
147 // Do not propose fixes for virtual function.
148 const auto *Method = dyn_cast<CXXMethodDecl>(Def);
149 if (Method && Method->isVirtual())
150 return;
151
152 for (auto &Hint : CR.Hints)
153 Diagnostic << Hint;
154 }
155 for (auto Loc : CR.DeclLocs)
156 diag(Loc, "could not transform this declaration", DiagnosticIDs::Note);
157}
158
159} // namespace clang::tidy::readability
const FunctionDecl * Decl
DiagnosticCallback Diagnostic
llvm::SmallVector< clang::SourceLocation, 4 > DeclLocs
CharSourceRange ConstRange
SourceLocation Loc
std::vector< FixItHint > Hints
::clang::DynTypedNode Node
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.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static CheckResult checkDef(const clang::FunctionDecl *Def, const MatchFinder::MatchResult &MatchResult)
static std::optional< Token > findConstToRemove(const FunctionDecl *Def, const MatchFinder::MatchResult &Result)
std::optional< Token > getQualifyingToken(tok::TokenKind TK, CharSourceRange Range, const ASTContext &Context, const SourceManager &SM)
Assuming that Range spans a CVR-qualified type, returns the token in Range that is responsible for th...
Definition: LexerUtils.cpp:149
llvm::StringMap< ClangTidyValue > OptionMap