clang-tools 23.0.0git
UseUsingCheck.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 "UseUsingCheck.h"
10#include "../utils/LexerUtils.h"
11#include "clang/AST/DeclGroup.h"
12#include "clang/Basic/LangOptions.h"
13#include "clang/Basic/SourceLocation.h"
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/TokenKinds.h"
16#include "clang/Lex/Lexer.h"
17#include <string>
18
19using namespace clang::ast_matchers;
20namespace {
21
22AST_MATCHER(clang::LinkageSpecDecl, isExternCLinkage) {
23 return Node.getLanguage() == clang::LinkageSpecLanguageIDs::C;
24}
25} // namespace
26
27namespace clang::tidy::modernize {
28
29static constexpr StringRef ExternCDeclName = "extern-c-decl";
30static constexpr StringRef ParentDeclName = "parent-decl";
31static constexpr StringRef TagDeclName = "tag-decl";
32static constexpr StringRef TypedefName = "typedef";
33static constexpr StringRef DeclStmtName = "decl-stmt";
34
36 : ClangTidyCheck(Name, Context),
37 IgnoreMacros(Options.get("IgnoreMacros", true)),
38 IgnoreExternC(Options.get("IgnoreExternC", false)) {}
39
41 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
42 Options.store(Opts, "IgnoreExternC", IgnoreExternC);
43}
44
45void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
46 Finder->addMatcher(
47 typedefDecl(
48 unless(isInstantiated()),
49 optionally(hasAncestor(
50 linkageSpecDecl(isExternCLinkage()).bind(ExternCDeclName))),
51 anyOf(hasParent(decl().bind(ParentDeclName)),
52 hasParent(declStmt().bind(DeclStmtName))))
53 .bind(TypedefName),
54 this);
55
56 // This matcher is used to find tag declarations in source code within
57 // typedefs. They appear in the AST just *prior* to the typedefs.
58 Finder->addMatcher(
59 tagDecl(
60 anyOf(allOf(unless(anyOf(isImplicit(),
61 classTemplateSpecializationDecl())),
62 anyOf(hasParent(decl().bind(ParentDeclName)),
63 hasParent(declStmt().bind(DeclStmtName)))),
64 // We want the parent of the ClassTemplateDecl, not the parent
65 // of the specialization.
66 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
67 anyOf(hasParent(decl().bind(ParentDeclName)),
68 hasParent(declStmt().bind(DeclStmtName))))))))
69 .bind(TagDeclName),
70 this);
71}
72
73void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
74 const auto *ParentDecl = Result.Nodes.getNodeAs<Decl>(ParentDeclName);
75
76 if (!ParentDecl) {
77 const auto *ParentDeclStmt = Result.Nodes.getNodeAs<DeclStmt>(DeclStmtName);
78 if (ParentDeclStmt) {
79 if (ParentDeclStmt->isSingleDecl())
80 ParentDecl = ParentDeclStmt->getSingleDecl();
81 else
82 ParentDecl =
83 ParentDeclStmt->getDeclGroup().getDeclGroup()
84 [ParentDeclStmt->getDeclGroup().getDeclGroup().size() - 1];
85 }
86 }
87
88 if (!ParentDecl)
89 return;
90
91 const SourceManager &SM = *Result.SourceManager;
92 const LangOptions &LO = getLangOpts();
93
94 // Match CXXRecordDecl only to store the range of the last non-implicit full
95 // declaration, to later check whether it's within the typedef itself.
96 const auto *MatchedTagDecl = Result.Nodes.getNodeAs<TagDecl>(TagDeclName);
97 if (MatchedTagDecl) {
98 // It is not sufficient to just track the last TagDecl that we've seen,
99 // because if one struct or union is nested inside another, the last TagDecl
100 // before the typedef will be the nested one (PR#50990). Therefore, we also
101 // keep track of the parent declaration, so that we can look up the last
102 // TagDecl that is a sibling of the typedef in the AST.
103 if (MatchedTagDecl->isThisDeclarationADefinition())
104 LastTagDeclRanges[ParentDecl] = MatchedTagDecl->getSourceRange();
105 return;
106 }
107
108 const auto *MatchedDecl = Result.Nodes.getNodeAs<TypedefDecl>(TypedefName);
109 if (MatchedDecl->getLocation().isInvalid())
110 return;
111
112 const auto *ExternCDecl =
113 Result.Nodes.getNodeAs<LinkageSpecDecl>(ExternCDeclName);
114 if (ExternCDecl && IgnoreExternC)
115 return;
116
117 const SourceLocation StartLoc = MatchedDecl->getBeginLoc();
118
119 if (StartLoc.isMacroID() && IgnoreMacros)
120 return;
121
122 static constexpr StringRef UseUsingWarning =
123 "use 'using' instead of 'typedef'";
124
125 // Warn at StartLoc but do not fix if there is macro or array.
126 if (MatchedDecl->getUnderlyingType()->isArrayType() || StartLoc.isMacroID()) {
127 diag(StartLoc, UseUsingWarning);
128 return;
129 }
130
131 const TypeLoc TL = MatchedDecl->getTypeSourceInfo()->getTypeLoc();
132
133 bool FunctionPointerCase = false;
134 auto [Type, QualifierStr] = [MatchedDecl, this, &TL, &FunctionPointerCase,
135 &SM,
136 &LO]() -> std::pair<std::string, std::string> {
137 SourceRange TypeRange = TL.getSourceRange();
138
139 // Function pointer case, get the left and right side of the identifier
140 // without the identifier.
141 if (TypeRange.fullyContains(MatchedDecl->getLocation())) {
142 FunctionPointerCase = true;
143 SourceLocation StartLoc = MatchedDecl->getLocation();
144 SourceLocation EndLoc = MatchedDecl->getLocation();
145
146 while (true) {
147 const std::optional<Token> Prev =
148 utils::lexer::getPreviousToken(StartLoc, SM, LO);
149 const std::optional<Token> Next =
151 if (!Prev || Prev->isNot(tok::l_paren) || !Next ||
152 Next->isNot(tok::r_paren))
153 break;
154
155 StartLoc = Prev->getLocation();
156 EndLoc = Next->getLocation();
157 }
158
159 const auto RangeLeftOfIdentifier =
160 CharSourceRange::getCharRange(TypeRange.getBegin(), StartLoc);
161 const auto RangeRightOfIdentifier = CharSourceRange::getCharRange(
162 Lexer::getLocForEndOfToken(EndLoc, 0, SM, LO),
163 Lexer::getLocForEndOfToken(TypeRange.getEnd(), 0, SM, LO));
164 const std::string VerbatimType =
165 (Lexer::getSourceText(RangeLeftOfIdentifier, SM, LO) +
166 Lexer::getSourceText(RangeRightOfIdentifier, SM, LO))
167 .str();
168 return {VerbatimType, ""};
169 }
170
171 StringRef ExtraReference = "";
172 if (MainTypeEndLoc.isValid() && TypeRange.fullyContains(MainTypeEndLoc)) {
173 // Each type introduced in a typedef can specify being a reference or
174 // pointer type separately, so we need to figure out if the new using-decl
175 // needs to be to a reference or pointer as well.
176 const SourceLocation Tok = utils::lexer::findPreviousAnyTokenKind(
177 MatchedDecl->getLocation(), SM, LO, tok::TokenKind::star,
178 tok::TokenKind::amp, tok::TokenKind::comma,
179 tok::TokenKind::kw_typedef);
180
181 ExtraReference = Lexer::getSourceText(
182 CharSourceRange::getCharRange(Tok, Tok.getLocWithOffset(1)), SM, LO);
183
184 if (ExtraReference != "*" && ExtraReference != "&")
185 ExtraReference = "";
186
187 TypeRange.setEnd(MainTypeEndLoc);
188 }
189 return {
190 Lexer::getSourceText(CharSourceRange::getTokenRange(TypeRange), SM, LO)
191 .str(),
192 ExtraReference.str()};
193 }();
194 const StringRef Name = MatchedDecl->getName();
195 SourceRange ReplaceRange = MatchedDecl->getSourceRange();
196
197 // typedefs with multiple comma-separated definitions produce multiple
198 // consecutive TypedefDecl nodes whose SourceRanges overlap. Each range starts
199 // at the "typedef" and then continues *across* previous definitions through
200 // the end of the current TypedefDecl definition.
201 // But also we need to check that the ranges belong to the same file because
202 // different files may contain overlapping ranges.
203 std::string Using = "using ";
204 if (ReplaceRange.getBegin().isMacroID() ||
205 (Result.SourceManager->getFileID(ReplaceRange.getBegin()) !=
206 Result.SourceManager->getFileID(LastReplacementEnd)) ||
207 (ReplaceRange.getBegin() >= LastReplacementEnd)) {
208 // This is the first (and possibly the only) TypedefDecl in a typedef. Save
209 // Type and Name in case we find subsequent TypedefDecl's in this typedef.
210 FirstTypedefType = Type;
211 FirstTypedefName = Name.str();
212 MainTypeEndLoc = TL.getEndLoc();
213 } else {
214 // This is additional TypedefDecl in a comma-separated typedef declaration.
215 // Start replacement *after* prior replacement and separate with semicolon.
216 ReplaceRange.setBegin(LastReplacementEnd);
217 Using = ";\nusing ";
218
219 // If this additional TypedefDecl's Type starts with the first TypedefDecl's
220 // type, make this using statement refer back to the first type, e.g. make
221 // "typedef int Foo, *Foo_p;" -> "using Foo = int;\nusing Foo_p = Foo*;"
222 if (Type == FirstTypedefType && !QualifierStr.empty())
223 Type = FirstTypedefName;
224 }
225
226 if (!ReplaceRange.getEnd().isMacroID()) {
227 const SourceLocation::IntTy Offset = FunctionPointerCase ? 0 : Name.size();
228 LastReplacementEnd = ReplaceRange.getEnd().getLocWithOffset(Offset);
229 }
230
231 auto Diag = diag(ReplaceRange.getBegin(), UseUsingWarning);
232
233 // If typedef contains a full tag declaration, extract its full text.
234 auto LastTagDeclRange = LastTagDeclRanges.find(ParentDecl);
235 if (LastTagDeclRange != LastTagDeclRanges.end() &&
236 LastTagDeclRange->second.isValid() &&
237 ReplaceRange.fullyContains(LastTagDeclRange->second)) {
238 Type = std::string(Lexer::getSourceText(
239 CharSourceRange::getTokenRange(LastTagDeclRange->second), SM, LO));
240 if (Type.empty())
241 return;
242 }
243
244 const std::string Replacement =
245 (Using + Name + " = " + Type + QualifierStr).str();
246 Diag << FixItHint::CreateReplacement(ReplaceRange, Replacement);
247}
248} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseUsingCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
static constexpr StringRef ExternCDeclName
static constexpr StringRef ParentDeclName
static constexpr StringRef TagDeclName
static constexpr StringRef TypedefName
static constexpr StringRef DeclStmtName
std::optional< Token > getPreviousToken(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
Returns previous token or std::nullopt if not found.
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:104
SourceLocation findPreviousAnyTokenKind(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts, TokenKind TK, TokenKinds... TKs)
Definition LexerUtils.h:47
llvm::StringMap< ClangTidyValue > OptionMap