clang-tools 24.0.0git
ReturnBracedInitListCheck.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
10#include "../utils/TypeTraits.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/DeclTemplate.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/ASTMatchers/ASTMatchers.h"
15#include "clang/Lex/Lexer.h"
16
17using namespace clang::ast_matchers;
18
19namespace clang::tidy::modernize {
20
21static bool hasInitListConstructor(const CXXRecordDecl *RD) {
22 if (RD == nullptr || !RD->hasDefinition())
23 return false;
24 auto IsInitListCtor = [](const CXXConstructorDecl *Ctor) {
25 return Ctor->hasOneParamOrDefaultArgs() &&
27 Ctor->getParamDecl(0)->getType().getNonReferenceType());
28 };
29 auto TestDecl = [&](const Decl *D) {
30 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(D))
31 return IsInitListCtor(Ctor);
32 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
33 if (const auto *Ctor =
34 dyn_cast<CXXConstructorDecl>(FTD->getTemplatedDecl()))
35 return IsInitListCtor(Ctor);
36 return false;
37 };
38 const ASTContext &Ctx = RD->getASTContext();
39 const DeclarationName Name =
40 Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalTagType(RD));
41 return llvm::any_of(RD->lookup(Name), [&](const NamedDecl *D) {
42 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(D))
43 return TestDecl(Shadow->getTargetDecl());
44 return TestDecl(D);
45 });
46}
47
49 auto SemanticallyDifferentContainer = allOf(
50 hasDeclaration(
51 // Container(size_type count, const T &value,
52 // const Allocator &alloc = Allocator());
53 cxxConstructorDecl(parameterCountIs(3),
54 hasParameter(0, hasType(qualType(hasCanonicalType(
55 isInteger())))))),
56 hasType(cxxRecordDecl(hasAnyName("::std::basic_string", "::std::vector",
57 "::std::deque", "::std::forward_list",
58 "::std::list"))));
59
60 const auto ConstructExpr =
61 cxxConstructExpr(
62 unless(anyOf(
63 // Skip explicit constructor.
64 hasDeclaration(cxxConstructorDecl(isExplicit())),
65 // Skip list initialization and constructors with an initializer
66 // list.
67 isListInitialization(), hasDescendant(initListExpr()),
68 // Skip container `vector(size_type, const T&, ...)`.
69 SemanticallyDifferentContainer)))
70 .bind("ctor");
71
72 Finder->addMatcher(
73 returnStmt(hasReturnValue(ConstructExpr),
74 forFunction(functionDecl(returns(unless(anyOf(builtinType(),
75 autoType()))))
76 .bind("fn"))),
77 this);
78}
79
80void ReturnBracedInitListCheck::check(const MatchFinder::MatchResult &Result) {
81 const auto *MatchedFunctionDecl = Result.Nodes.getNodeAs<FunctionDecl>("fn");
82 const auto *MatchedConstructExpr =
83 Result.Nodes.getNodeAs<CXXConstructExpr>("ctor");
84
85 // Don't make replacements in macro.
86 const SourceLocation Loc = MatchedConstructExpr->getExprLoc();
87 if (Loc.isMacroID())
88 return;
89
90 // Make sure that the return type matches the constructed type.
91 const QualType ReturnType =
92 MatchedFunctionDecl->getReturnType().getCanonicalType();
93 const QualType ConstructType =
94 MatchedConstructExpr->getType().getCanonicalType();
95 if (ReturnType != ConstructType)
96 return;
97
98 // Rewriting `T(args)` to a braced-init-list changes overload resolution when
99 // `T` has a std::initializer_list constructor: list-initialization prefers
100 // the initializer_list overload, so the braced form may silently select a
101 // different constructor than the parenthesized call.
102 if (hasInitListConstructor(ConstructType->getAsCXXRecordDecl()))
103 return;
104
105 const auto Diag =
106 diag(Loc, "avoid repeating the return type from the "
107 "declaration; use a braced initializer list instead");
108
109 const SourceRange CallParensRange =
110 MatchedConstructExpr->getParenOrBraceRange();
111
112 // Make sure there is an explicit constructor call.
113 if (CallParensRange.isInvalid())
114 return;
115
116 // Make sure that the ctor arguments match the declaration.
117 for (unsigned I = 0, NumParams = MatchedConstructExpr->getNumArgs();
118 I < NumParams; ++I) {
119 if (const ParmVarDecl *VD =
120 MatchedConstructExpr->getConstructor()->getParamDecl(I)) {
121 const auto ArgType = MatchedConstructExpr->getArg(I)->getType();
122 const auto ParamType = VD->getType().getNonReferenceType();
123 if (ArgType.getCanonicalType().getUnqualifiedType() !=
124 ParamType.getCanonicalType().getUnqualifiedType())
125 return;
126 }
127 }
128
129 // Range for constructor name and opening brace.
130 const CharSourceRange CtorCallSourceRange = CharSourceRange::getTokenRange(
131 Loc, CallParensRange.getBegin().getLocWithOffset(-1));
132
133 Diag << FixItHint::CreateRemoval(CtorCallSourceRange)
134 << FixItHint::CreateReplacement(CallParensRange.getBegin(), "{")
135 << FixItHint::CreateReplacement(CallParensRange.getEnd(), "}");
136}
137
138} // namespace clang::tidy::modernize
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool hasInitListConstructor(const CXXRecordDecl *RD)
bool isStdInitializerList(QualType Type)
Returns true if Type is a std::initializer_list<...> specialization.