1 //===--- ReturnBracedInitListCheck.cpp - clang-tidy------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "ReturnBracedInitListCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13 #include "clang/Tooling/FixIt.h"
15 using namespace clang::ast_matchers
;
21 void ReturnBracedInitListCheck::registerMatchers(MatchFinder
*Finder
) {
22 // Skip list initialization and constructors with an initializer list.
25 unless(anyOf(hasDeclaration(cxxConstructorDecl(isExplicit())),
26 isListInitialization(), hasDescendant(initListExpr()))))
30 returnStmt(hasReturnValue(ConstructExpr
),
31 forFunction(functionDecl(returns(unless(anyOf(builtinType(),
37 void ReturnBracedInitListCheck::check(const MatchFinder::MatchResult
&Result
) {
38 const auto *MatchedFunctionDecl
= Result
.Nodes
.getNodeAs
<FunctionDecl
>("fn");
39 const auto *MatchedConstructExpr
=
40 Result
.Nodes
.getNodeAs
<CXXConstructExpr
>("ctor");
42 // Don't make replacements in macro.
43 SourceLocation Loc
= MatchedConstructExpr
->getExprLoc();
47 // Make sure that the return type matches the constructed type.
48 const QualType ReturnType
=
49 MatchedFunctionDecl
->getReturnType().getCanonicalType();
50 const QualType ConstructType
=
51 MatchedConstructExpr
->getType().getCanonicalType();
52 if (ReturnType
!= ConstructType
)
55 auto Diag
= diag(Loc
, "avoid repeating the return type from the "
56 "declaration; use a braced initializer list instead");
58 const SourceRange CallParensRange
=
59 MatchedConstructExpr
->getParenOrBraceRange();
61 // Make sure there is an explicit constructor call.
62 if (CallParensRange
.isInvalid())
65 // Make sure that the ctor arguments match the declaration.
66 for (unsigned I
= 0, NumParams
= MatchedConstructExpr
->getNumArgs();
68 if (const auto *VD
= dyn_cast
<VarDecl
>(
69 MatchedConstructExpr
->getConstructor()->getParamDecl(I
))) {
70 if (MatchedConstructExpr
->getArg(I
)->getType().getCanonicalType() !=
71 VD
->getType().getCanonicalType())
76 // Range for constructor name and opening brace.
77 CharSourceRange CtorCallSourceRange
= CharSourceRange::getTokenRange(
78 Loc
, CallParensRange
.getBegin().getLocWithOffset(-1));
80 Diag
<< FixItHint::CreateRemoval(CtorCallSourceRange
)
81 << FixItHint::CreateReplacement(CallParensRange
.getBegin(), "{")
82 << FixItHint::CreateReplacement(CallParensRange
.getEnd(), "}");
85 } // namespace modernize