clang-tools 18.0.0git
UseUsingCheck.cpp
Go to the documentation of this file.
1//===--- UseUsingCheck.cpp - clang-tidy------------------------------------===//
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 "clang/AST/ASTContext.h"
11#include "clang/Lex/Lexer.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::modernize {
16
17static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
18static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
19static constexpr llvm::StringLiteral TypedefName = "typedef";
20
22 : ClangTidyCheck(Name, Context),
23 IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
24
26 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
27}
28
29void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
30 Finder->addMatcher(typedefDecl(unless(isInstantiated()),
31 hasParent(decl().bind(ParentDeclName)))
32 .bind(TypedefName),
33 this);
34
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.
37 Finder->addMatcher(
38 tagDecl(
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)))))))
46 .bind(TagDeclName),
47 this);
48}
49
50void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
51 const auto *ParentDecl = Result.Nodes.getNodeAs<Decl>(ParentDeclName);
52 if (!ParentDecl)
53 return;
54
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);
58 if (MatchedTagDecl) {
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 LastTagDeclRanges[ParentDecl] = MatchedTagDecl->getSourceRange();
65 return;
66 }
67
68 const auto *MatchedDecl = Result.Nodes.getNodeAs<TypedefDecl>(TypedefName);
69 if (MatchedDecl->getLocation().isInvalid())
70 return;
71
72 SourceLocation StartLoc = MatchedDecl->getBeginLoc();
73
74 if (StartLoc.isMacroID() && IgnoreMacros)
75 return;
76
77 static const char *UseUsingWarning = "use 'using' instead of 'typedef'";
78
79 // Warn at StartLoc but do not fix if there is macro or array.
80 if (MatchedDecl->getUnderlyingType()->isArrayType() || StartLoc.isMacroID()) {
81 diag(StartLoc, UseUsingWarning);
82 return;
83 }
84
85 PrintingPolicy PrintPolicy(getLangOpts());
86 PrintPolicy.SuppressScope = true;
87 PrintPolicy.ConstantArraySizeAsWritten = true;
88 PrintPolicy.UseVoidForZeroParams = false;
89 PrintPolicy.PrintInjectedClassNameWithArguments = false;
90
91 std::string Type = MatchedDecl->getUnderlyingType().getAsString(PrintPolicy);
92 std::string Name = MatchedDecl->getNameAsString();
93 SourceRange ReplaceRange = MatchedDecl->getSourceRange();
94
95 // typedefs with multiple comma-separated definitions produce multiple
96 // consecutive TypedefDecl nodes whose SourceRanges overlap. Each range starts
97 // at the "typedef" and then continues *across* previous definitions through
98 // the end of the current TypedefDecl definition.
99 // But also we need to check that the ranges belong to the same file because
100 // different files may contain overlapping ranges.
101 std::string Using = "using ";
102 if (ReplaceRange.getBegin().isMacroID() ||
103 (Result.SourceManager->getFileID(ReplaceRange.getBegin()) !=
104 Result.SourceManager->getFileID(LastReplacementEnd)) ||
105 (ReplaceRange.getBegin() >= LastReplacementEnd)) {
106 // This is the first (and possibly the only) TypedefDecl in a typedef. Save
107 // Type and Name in case we find subsequent TypedefDecl's in this typedef.
108 FirstTypedefType = Type;
109 FirstTypedefName = Name;
110 } else {
111 // This is additional TypedefDecl in a comma-separated typedef declaration.
112 // Start replacement *after* prior replacement and separate with semicolon.
113 ReplaceRange.setBegin(LastReplacementEnd);
114 Using = ";\nusing ";
115
116 // If this additional TypedefDecl's Type starts with the first TypedefDecl's
117 // type, make this using statement refer back to the first type, e.g. make
118 // "typedef int Foo, *Foo_p;" -> "using Foo = int;\nusing Foo_p = Foo*;"
119 if (Type.size() > FirstTypedefType.size() &&
120 Type.substr(0, FirstTypedefType.size()) == FirstTypedefType)
121 Type = FirstTypedefName + Type.substr(FirstTypedefType.size() + 1);
122 }
123 if (!ReplaceRange.getEnd().isMacroID()) {
124 const SourceLocation::IntTy Offset = MatchedDecl->getFunctionType() ? 0 : Name.size();
125 LastReplacementEnd = ReplaceRange.getEnd().getLocWithOffset(Offset);
126 }
127
128 auto Diag = diag(ReplaceRange.getBegin(), UseUsingWarning);
129
130 // If typedef contains a full tag declaration, extract its full text.
131 auto LastTagDeclRange = LastTagDeclRanges.find(ParentDecl);
132 if (LastTagDeclRange != LastTagDeclRanges.end() &&
133 LastTagDeclRange->second.isValid() &&
134 ReplaceRange.fullyContains(LastTagDeclRange->second)) {
135 Type = std::string(Lexer::getSourceText(
136 CharSourceRange::getTokenRange(LastTagDeclRange->second),
137 *Result.SourceManager, getLangOpts()));
138 if (Type.empty())
139 return;
140 }
141
142 std::string Replacement = Using + Name + " = " + Type;
143 Diag << FixItHint::CreateReplacement(ReplaceRange, Replacement);
144}
145} // namespace clang::tidy::modernize
const FunctionDecl * Decl
size_t Offset
NodeType Type
llvm::StringRef Name
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
UseUsingCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static constexpr llvm::StringLiteral ParentDeclName
static constexpr llvm::StringLiteral TagDeclName
static constexpr llvm::StringLiteral TypedefName
llvm::StringMap< ClangTidyValue > OptionMap