1 //===--- UseUsingCheck.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 "UseUsingCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/Lex/Lexer.h"
13 using namespace clang::ast_matchers
;
15 namespace clang::tidy::modernize
{
17 static constexpr llvm::StringLiteral ParentDeclName
= "parent-decl";
18 static constexpr llvm::StringLiteral TagDeclName
= "tag-decl";
19 static constexpr llvm::StringLiteral TypedefName
= "typedef";
21 UseUsingCheck::UseUsingCheck(StringRef Name
, ClangTidyContext
*Context
)
22 : ClangTidyCheck(Name
, Context
),
23 IgnoreMacros(Options
.getLocalOrGlobal("IgnoreMacros", true)) {}
25 void UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap
&Opts
) {
26 Options
.store(Opts
, "IgnoreMacros", IgnoreMacros
);
29 void UseUsingCheck::registerMatchers(MatchFinder
*Finder
) {
30 Finder
->addMatcher(typedefDecl(unless(isInstantiated()),
31 hasParent(decl().bind(ParentDeclName
)))
35 // This matcher is used to find tag declarations in source code within
36 // typedefs. They appear in the AST just *prior* to the typedefs.
39 anyOf(allOf(unless(anyOf(isImplicit(),
40 classTemplateSpecializationDecl())),
41 hasParent(decl().bind(ParentDeclName
))),
42 // We want the parent of the ClassTemplateDecl, not the parent
43 // of the specialization.
44 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
45 hasParent(decl().bind(ParentDeclName
)))))))
50 void UseUsingCheck::check(const MatchFinder::MatchResult
&Result
) {
51 const auto *ParentDecl
= Result
.Nodes
.getNodeAs
<Decl
>(ParentDeclName
);
55 // Match CXXRecordDecl only to store the range of the last non-implicit full
56 // declaration, to later check whether it's within the typdef itself.
57 const auto *MatchedTagDecl
= Result
.Nodes
.getNodeAs
<TagDecl
>(TagDeclName
);
59 // It is not sufficient to just track the last TagDecl that we've seen,
60 // because if one struct or union is nested inside another, the last TagDecl
61 // before the typedef will be the nested one (PR#50990). Therefore, we also
62 // keep track of the parent declaration, so that we can look up the last
63 // TagDecl that is a sibling of the typedef in the AST.
64 if (MatchedTagDecl
->isThisDeclarationADefinition())
65 LastTagDeclRanges
[ParentDecl
] = MatchedTagDecl
->getSourceRange();
69 const auto *MatchedDecl
= Result
.Nodes
.getNodeAs
<TypedefDecl
>(TypedefName
);
70 if (MatchedDecl
->getLocation().isInvalid())
73 SourceLocation StartLoc
= MatchedDecl
->getBeginLoc();
75 if (StartLoc
.isMacroID() && IgnoreMacros
)
78 static const char *UseUsingWarning
= "use 'using' instead of 'typedef'";
80 // Warn at StartLoc but do not fix if there is macro or array.
81 if (MatchedDecl
->getUnderlyingType()->isArrayType() || StartLoc
.isMacroID()) {
82 diag(StartLoc
, UseUsingWarning
);
86 PrintingPolicy
PrintPolicy(getLangOpts());
87 PrintPolicy
.SuppressScope
= true;
88 PrintPolicy
.ConstantArraySizeAsWritten
= true;
89 PrintPolicy
.UseVoidForZeroParams
= false;
90 PrintPolicy
.PrintInjectedClassNameWithArguments
= false;
92 std::string Type
= MatchedDecl
->getUnderlyingType().getAsString(PrintPolicy
);
93 std::string Name
= MatchedDecl
->getNameAsString();
94 SourceRange ReplaceRange
= MatchedDecl
->getSourceRange();
96 // typedefs with multiple comma-separated definitions produce multiple
97 // consecutive TypedefDecl nodes whose SourceRanges overlap. Each range starts
98 // at the "typedef" and then continues *across* previous definitions through
99 // the end of the current TypedefDecl definition.
100 // But also we need to check that the ranges belong to the same file because
101 // different files may contain overlapping ranges.
102 std::string Using
= "using ";
103 if (ReplaceRange
.getBegin().isMacroID() ||
104 (Result
.SourceManager
->getFileID(ReplaceRange
.getBegin()) !=
105 Result
.SourceManager
->getFileID(LastReplacementEnd
)) ||
106 (ReplaceRange
.getBegin() >= LastReplacementEnd
)) {
107 // This is the first (and possibly the only) TypedefDecl in a typedef. Save
108 // Type and Name in case we find subsequent TypedefDecl's in this typedef.
109 FirstTypedefType
= Type
;
110 FirstTypedefName
= Name
;
112 // This is additional TypedefDecl in a comma-separated typedef declaration.
113 // Start replacement *after* prior replacement and separate with semicolon.
114 ReplaceRange
.setBegin(LastReplacementEnd
);
117 // If this additional TypedefDecl's Type starts with the first TypedefDecl's
118 // type, make this using statement refer back to the first type, e.g. make
119 // "typedef int Foo, *Foo_p;" -> "using Foo = int;\nusing Foo_p = Foo*;"
120 if (Type
.size() > FirstTypedefType
.size() &&
121 Type
.substr(0, FirstTypedefType
.size()) == FirstTypedefType
)
122 Type
= FirstTypedefName
+ Type
.substr(FirstTypedefType
.size() + 1);
124 if (!ReplaceRange
.getEnd().isMacroID()) {
125 const SourceLocation::IntTy Offset
= MatchedDecl
->getFunctionType() ? 0 : Name
.size();
126 LastReplacementEnd
= ReplaceRange
.getEnd().getLocWithOffset(Offset
);
129 auto Diag
= diag(ReplaceRange
.getBegin(), UseUsingWarning
);
131 // If typedef contains a full tag declaration, extract its full text.
132 auto LastTagDeclRange
= LastTagDeclRanges
.find(ParentDecl
);
133 if (LastTagDeclRange
!= LastTagDeclRanges
.end() &&
134 LastTagDeclRange
->second
.isValid() &&
135 ReplaceRange
.fullyContains(LastTagDeclRange
->second
)) {
136 Type
= std::string(Lexer::getSourceText(
137 CharSourceRange::getTokenRange(LastTagDeclRange
->second
),
138 *Result
.SourceManager
, getLangOpts()));
143 std::string Replacement
= Using
+ Name
+ " = " + Type
;
144 Diag
<< FixItHint::CreateReplacement(ReplaceRange
, Replacement
);
146 } // namespace clang::tidy::modernize