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