UseUsingCheck.cpp 6.1 KB

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