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
UseUsingCheck(StringRef Name,ClangTidyContext * Context)19 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
20 : ClangTidyCheck(Name, Context),
21 IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
22
storeOptions(ClangTidyOptions::OptionMap & Opts)23 void UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
24 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
25 }
26
registerMatchers(MatchFinder * Finder)27 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
28 Finder->addMatcher(typedefDecl(unless(isInstantiated())).bind("typedef"),
29 this);
30 // This matcher used to find tag declarations in source code within typedefs.
31 // They appear in the AST just *prior* to the typedefs.
32 Finder->addMatcher(tagDecl(unless(isImplicit())).bind("tagdecl"), this);
33 }
34
check(const MatchFinder::MatchResult & Result)35 void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
36 // Match CXXRecordDecl only to store the range of the last non-implicit full
37 // declaration, to later check whether it's within the typdef itself.
38 const auto *MatchedTagDecl = Result.Nodes.getNodeAs<TagDecl>("tagdecl");
39 if (MatchedTagDecl) {
40 LastTagDeclRange = MatchedTagDecl->getSourceRange();
41 return;
42 }
43
44 const auto *MatchedDecl = Result.Nodes.getNodeAs<TypedefDecl>("typedef");
45 if (MatchedDecl->getLocation().isInvalid())
46 return;
47
48 SourceLocation StartLoc = MatchedDecl->getBeginLoc();
49
50 if (StartLoc.isMacroID() && IgnoreMacros)
51 return;
52
53 static const char *UseUsingWarning = "use 'using' instead of 'typedef'";
54
55 // Warn at StartLoc but do not fix if there is macro or array.
56 if (MatchedDecl->getUnderlyingType()->isArrayType() || StartLoc.isMacroID()) {
57 diag(StartLoc, UseUsingWarning);
58 return;
59 }
60
61 auto printPolicy = PrintingPolicy(getLangOpts());
62 printPolicy.SuppressScope = true;
63 printPolicy.ConstantArraySizeAsWritten = true;
64 printPolicy.UseVoidForZeroParams = false;
65 printPolicy.PrintInjectedClassNameWithArguments = false;
66
67 std::string Type = MatchedDecl->getUnderlyingType().getAsString(printPolicy);
68 std::string Name = MatchedDecl->getNameAsString();
69 SourceRange ReplaceRange = MatchedDecl->getSourceRange();
70
71 // typedefs with multiple comma-separated definitions produce multiple
72 // consecutive TypedefDecl nodes whose SourceRanges overlap. Each range starts
73 // at the "typedef" and then continues *across* previous definitions through
74 // the end of the current TypedefDecl definition.
75 // But also we need to check that the ranges belong to the same file because
76 // different files may contain overlapping ranges.
77 std::string Using = "using ";
78 if (ReplaceRange.getBegin().isMacroID() ||
79 (Result.SourceManager->getFileID(ReplaceRange.getBegin()) !=
80 Result.SourceManager->getFileID(LastReplacementEnd)) ||
81 (ReplaceRange.getBegin() >= LastReplacementEnd)) {
82 // This is the first (and possibly the only) TypedefDecl in a typedef. Save
83 // Type and Name in case we find subsequent TypedefDecl's in this typedef.
84 FirstTypedefType = Type;
85 FirstTypedefName = Name;
86 } else {
87 // This is additional TypedefDecl in a comma-separated typedef declaration.
88 // Start replacement *after* prior replacement and separate with semicolon.
89 ReplaceRange.setBegin(LastReplacementEnd);
90 Using = ";\nusing ";
91
92 // If this additional TypedefDecl's Type starts with the first TypedefDecl's
93 // type, make this using statement refer back to the first type, e.g. make
94 // "typedef int Foo, *Foo_p;" -> "using Foo = int;\nusing Foo_p = Foo*;"
95 if (Type.size() > FirstTypedefType.size() &&
96 Type.substr(0, FirstTypedefType.size()) == FirstTypedefType)
97 Type = FirstTypedefName + Type.substr(FirstTypedefType.size() + 1);
98 }
99 if (!ReplaceRange.getEnd().isMacroID())
100 LastReplacementEnd = ReplaceRange.getEnd().getLocWithOffset(Name.size());
101
102 auto Diag = diag(ReplaceRange.getBegin(), UseUsingWarning);
103
104 // If typedef contains a full tag declaration, extract its full text.
105 if (LastTagDeclRange.isValid() &&
106 ReplaceRange.fullyContains(LastTagDeclRange)) {
107 bool Invalid;
108 Type = std::string(
109 Lexer::getSourceText(CharSourceRange::getTokenRange(LastTagDeclRange),
110 *Result.SourceManager, getLangOpts(), &Invalid));
111 if (Invalid)
112 return;
113 }
114
115 std::string Replacement = Using + Name + " = " + Type;
116 Diag << FixItHint::CreateReplacement(ReplaceRange, Replacement);
117 }
118 } // namespace modernize
119 } // namespace tidy
120 } // namespace clang
121