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