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