clang-tools  11.0.0
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 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace modernize {
18 
19 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
20  : ClangTidyCheck(Name, Context),
21  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
22 
24  Options.store(Opts, "IgnoreMacros", IgnoreMacros);
25 }
26 
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 
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
Type
NodeType Type
Definition: HTMLGenerator.cpp:73
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:114
clang::tidy::modernize::UseUsingCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: UseUsingCheck.cpp:27
clang::tidy::ClangTidyCheck::getLangOpts
const LangOptions & getLangOpts() const
Returns the language options from the context.
Definition: ClangTidyCheck.h:475
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:471
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:76
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::tidy::modernize::UseUsingCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: UseUsingCheck.cpp:23
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidyCheck.cpp:55
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
UseUsingCheck.h
clang::tidy::ClangTidyCheck::OptionsView::store
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.
Definition: ClangTidyCheck.cpp:152
clang::tidy::modernize::UseUsingCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: UseUsingCheck.cpp:35
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:111