clang-tools  10.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 
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 
23 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
24  if (!getLangOpts().CPlusPlus11)
25  return;
26  Finder->addMatcher(typedefDecl(unless(isInstantiated())).bind("typedef"),
27  this);
28  // This matcher used to find structs defined in source code within typedefs.
29  // They appear in the AST just *prior* to the typedefs.
30  Finder->addMatcher(cxxRecordDecl(unless(isImplicit())).bind("struct"), this);
31 }
32 
33 void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
34  // Match CXXRecordDecl only to store the range of the last non-implicit full
35  // declaration, to later check whether it's within the typdef itself.
36  const auto *MatchedCxxRecordDecl =
37  Result.Nodes.getNodeAs<CXXRecordDecl>("struct");
38  if (MatchedCxxRecordDecl) {
39  LastCxxDeclRange = MatchedCxxRecordDecl->getSourceRange();
40  return;
41  }
42 
43  const auto *MatchedDecl = Result.Nodes.getNodeAs<TypedefDecl>("typedef");
44  if (MatchedDecl->getLocation().isInvalid())
45  return;
46 
47  SourceLocation StartLoc = MatchedDecl->getBeginLoc();
48 
49  if (StartLoc.isMacroID() && IgnoreMacros)
50  return;
51 
52  static const char *UseUsingWarning = "use 'using' instead of 'typedef'";
53 
54  // Warn at StartLoc but do not fix if there is macro or array.
55  if (MatchedDecl->getUnderlyingType()->isArrayType() || StartLoc.isMacroID()) {
56  diag(StartLoc, UseUsingWarning);
57  return;
58  }
59 
60  auto printPolicy = PrintingPolicy(getLangOpts());
61  printPolicy.SuppressScope = true;
62  printPolicy.ConstantArraySizeAsWritten = true;
63  printPolicy.UseVoidForZeroParams = false;
64 
65  std::string Type = MatchedDecl->getUnderlyingType().getAsString(printPolicy);
66  std::string Name = MatchedDecl->getNameAsString();
67  SourceRange ReplaceRange = MatchedDecl->getSourceRange();
68 
69  // typedefs with multiple comma-separated definitions produce multiple
70  // consecutive TypedefDecl nodes whose SourceRanges overlap. Each range starts
71  // at the "typedef" and then continues *across* previous definitions through
72  // the end of the current TypedefDecl definition.
73  std::string Using = "using ";
74  if (ReplaceRange.getBegin().isMacroID() ||
75  ReplaceRange.getBegin() >= LastReplacementEnd) {
76  // This is the first (and possibly the only) TypedefDecl in a typedef. Save
77  // Type and Name in case we find subsequent TypedefDecl's in this typedef.
78  FirstTypedefType = Type;
79  FirstTypedefName = Name;
80  } else {
81  // This is additional TypedefDecl in a comma-separated typedef declaration.
82  // Start replacement *after* prior replacement and separate with semicolon.
83  ReplaceRange.setBegin(LastReplacementEnd);
84  Using = ";\nusing ";
85 
86  // If this additional TypedefDecl's Type starts with the first TypedefDecl's
87  // type, make this using statement refer back to the first type, e.g. make
88  // "typedef int Foo, *Foo_p;" -> "using Foo = int;\nusing Foo_p = Foo*;"
89  if (Type.size() > FirstTypedefType.size() &&
90  Type.substr(0, FirstTypedefType.size()) == FirstTypedefType)
91  Type = FirstTypedefName + Type.substr(FirstTypedefType.size() + 1);
92  }
93  if (!ReplaceRange.getEnd().isMacroID())
94  LastReplacementEnd = ReplaceRange.getEnd().getLocWithOffset(Name.size());
95 
96  auto Diag = diag(ReplaceRange.getBegin(), UseUsingWarning);
97 
98  // If typedef contains a full struct/class declaration, extract its full text.
99  if (LastCxxDeclRange.isValid() && ReplaceRange.fullyContains(LastCxxDeclRange)) {
100  bool Invalid;
101  Type =
102  Lexer::getSourceText(CharSourceRange::getTokenRange(LastCxxDeclRange),
103  *Result.SourceManager, getLangOpts(), &Invalid);
104  if (Invalid)
105  return;
106  }
107 
108  std::string Replacement = Using + Name + " = " + Type;
109  Diag << FixItHint::CreateReplacement(ReplaceRange, Replacement);
110 }
111 
112 } // namespace modernize
113 } // namespace tidy
114 } // namespace clang
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Base class for all clang-tidy checks.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static constexpr llvm::StringLiteral Name
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:227
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
NodeType Type
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.