1 //===--- AddUsing.cpp --------------------------------------------*- C++-*-===// 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 "AST.h" 10 #include "Config.h" 11 #include "FindTarget.h" 12 #include "refactor/Tweak.h" 13 #include "support/Logger.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/RecursiveASTVisitor.h" 16 17 namespace clang { 18 namespace clangd { 19 namespace { 20 21 // Tweak for removing full namespace qualifier under cursor on DeclRefExpr and 22 // types and adding "using" statement instead. 23 // 24 // Only qualifiers that refer exclusively to namespaces (no record types) are 25 // supported. There is some guessing of appropriate place to insert the using 26 // declaration. If we find any existing usings, we insert it there. If not, we 27 // insert right after the inner-most relevant namespace declaration. If there is 28 // none, or there is, but it was declared via macro, we insert above the first 29 // top level decl. 30 // 31 // Currently this only removes qualifier from under the cursor. In the future, 32 // we should improve this to remove qualifier from all occurrences of this 33 // symbol. 34 class AddUsing : public Tweak { 35 public: 36 const char *id() const override; 37 38 bool prepare(const Selection &Inputs) override; 39 Expected<Effect> apply(const Selection &Inputs) override; 40 std::string title() const override; 41 llvm::StringLiteral kind() const override { 42 return CodeAction::REFACTOR_KIND; 43 } 44 45 private: 46 // All of the following are set by prepare(). 47 // The qualifier to remove. 48 NestedNameSpecifierLoc QualifierToRemove; 49 // The name following QualifierToRemove. 50 llvm::StringRef Name; 51 // If valid, the insertion point for "using" statement must come after this. 52 // This is relevant when the type is defined in the main file, to make sure 53 // the type/function is already defined at the point where "using" is added. 54 SourceLocation MustInsertAfterLoc; 55 }; 56 REGISTER_TWEAK(AddUsing) 57 58 std::string AddUsing::title() const { 59 return std::string(llvm::formatv( 60 "Add using-declaration for {0} and remove qualifier", Name)); 61 } 62 63 // Locates all "using" statements relevant to SelectionDeclContext. 64 class UsingFinder : public RecursiveASTVisitor<UsingFinder> { 65 public: 66 UsingFinder(std::vector<const UsingDecl *> &Results, 67 const DeclContext *SelectionDeclContext, const SourceManager &SM) 68 : Results(Results), SelectionDeclContext(SelectionDeclContext), SM(SM) {} 69 70 bool VisitUsingDecl(UsingDecl *D) { 71 auto Loc = D->getUsingLoc(); 72 if (SM.getFileID(Loc) != SM.getMainFileID()) { 73 return true; 74 } 75 if (D->getDeclContext()->Encloses(SelectionDeclContext)) { 76 Results.push_back(D); 77 } 78 return true; 79 } 80 81 bool TraverseDecl(Decl *Node) { 82 // There is no need to go deeper into nodes that do not enclose selection, 83 // since "using" there will not affect selection, nor would it make a good 84 // insertion point. 85 if (Node->getDeclContext()->Encloses(SelectionDeclContext)) { 86 return RecursiveASTVisitor<UsingFinder>::TraverseDecl(Node); 87 } 88 return true; 89 } 90 91 private: 92 std::vector<const UsingDecl *> &Results; 93 const DeclContext *SelectionDeclContext; 94 const SourceManager &SM; 95 }; 96 97 bool isFullyQualified(const NestedNameSpecifier *NNS) { 98 if (!NNS) 99 return false; 100 return NNS->getKind() == NestedNameSpecifier::Global || 101 isFullyQualified(NNS->getPrefix()); 102 } 103 104 struct InsertionPointData { 105 // Location to insert the "using" statement. If invalid then the statement 106 // should not be inserted at all (it already exists). 107 SourceLocation Loc; 108 // Extra suffix to place after the "using" statement. Depending on what the 109 // insertion point is anchored to, we may need one or more \n to ensure 110 // proper formatting. 111 std::string Suffix; 112 // Whether using should be fully qualified, even if what the user typed was 113 // not. This is based on our detection of the local style. 114 bool AlwaysFullyQualify = false; 115 }; 116 117 // Finds the best place to insert the "using" statement. Returns invalid 118 // SourceLocation if the "using" statement already exists. 119 // 120 // The insertion point might be a little awkward if the decl we're anchoring to 121 // has a comment in an unfortunate place (e.g. directly above function or using 122 // decl, or immediately following "namespace {". We should add some helpers for 123 // dealing with that and use them in other code modifications as well. 124 llvm::Expected<InsertionPointData> 125 findInsertionPoint(const Tweak::Selection &Inputs, 126 const NestedNameSpecifierLoc &QualifierToRemove, 127 const llvm::StringRef Name, 128 const SourceLocation MustInsertAfterLoc) { 129 auto &SM = Inputs.AST->getSourceManager(); 130 131 // Search for all using decls that affect this point in file. We need this for 132 // two reasons: to skip adding "using" if one already exists and to find best 133 // place to add it, if it doesn't exist. 134 SourceLocation LastUsingLoc; 135 std::vector<const UsingDecl *> Usings; 136 UsingFinder(Usings, &Inputs.ASTSelection.commonAncestor()->getDeclContext(), 137 SM) 138 .TraverseAST(Inputs.AST->getASTContext()); 139 140 auto IsValidPoint = [&](const SourceLocation Loc) { 141 return MustInsertAfterLoc.isInvalid() || 142 SM.isBeforeInTranslationUnit(MustInsertAfterLoc, Loc); 143 }; 144 145 bool AlwaysFullyQualify = true; 146 for (auto &U : Usings) { 147 // Only "upgrade" to fully qualified is all relevant using decls are fully 148 // qualified. Otherwise trust what the user typed. 149 if (!isFullyQualified(U->getQualifier())) 150 AlwaysFullyQualify = false; 151 152 if (SM.isBeforeInTranslationUnit(Inputs.Cursor, U->getUsingLoc())) 153 // "Usings" is sorted, so we're done. 154 break; 155 if (U->getQualifier()->getAsNamespace()->getCanonicalDecl() == 156 QualifierToRemove.getNestedNameSpecifier() 157 ->getAsNamespace() 158 ->getCanonicalDecl() && 159 U->getName() == Name) { 160 return InsertionPointData(); 161 } 162 163 // Insertion point will be before last UsingDecl that affects cursor 164 // position. For most cases this should stick with the local convention of 165 // add using inside or outside namespace. 166 LastUsingLoc = U->getUsingLoc(); 167 } 168 if (LastUsingLoc.isValid() && IsValidPoint(LastUsingLoc)) { 169 InsertionPointData Out; 170 Out.Loc = LastUsingLoc; 171 Out.AlwaysFullyQualify = AlwaysFullyQualify; 172 return Out; 173 } 174 175 // No relevant "using" statements. Try the nearest namespace level. 176 const DeclContext *ParentDeclCtx = 177 &Inputs.ASTSelection.commonAncestor()->getDeclContext(); 178 while (ParentDeclCtx && !ParentDeclCtx->isFileContext()) { 179 ParentDeclCtx = ParentDeclCtx->getLexicalParent(); 180 } 181 if (auto *ND = llvm::dyn_cast_or_null<NamespaceDecl>(ParentDeclCtx)) { 182 auto Toks = Inputs.AST->getTokens().expandedTokens(ND->getSourceRange()); 183 const auto *Tok = llvm::find_if(Toks, [](const syntax::Token &Tok) { 184 return Tok.kind() == tok::l_brace; 185 }); 186 if (Tok == Toks.end() || Tok->endLocation().isInvalid()) { 187 return error("Namespace with no {"); 188 } 189 if (!Tok->endLocation().isMacroID() && IsValidPoint(Tok->endLocation())) { 190 InsertionPointData Out; 191 Out.Loc = Tok->endLocation(); 192 Out.Suffix = "\n"; 193 return Out; 194 } 195 } 196 // No using, no namespace, no idea where to insert. Try above the first 197 // top level decl after MustInsertAfterLoc. 198 auto TLDs = Inputs.AST->getLocalTopLevelDecls(); 199 for (const auto &TLD : TLDs) { 200 if (!IsValidPoint(TLD->getBeginLoc())) 201 continue; 202 InsertionPointData Out; 203 Out.Loc = SM.getExpansionLoc(TLD->getBeginLoc()); 204 Out.Suffix = "\n\n"; 205 return Out; 206 } 207 return error("Cannot find place to insert \"using\""); 208 } 209 210 bool isNamespaceForbidden(const Tweak::Selection &Inputs, 211 const NestedNameSpecifier &Namespace) { 212 std::string NamespaceStr = printNamespaceScope(*Namespace.getAsNamespace()); 213 214 for (StringRef Banned : Config::current().Style.FullyQualifiedNamespaces) { 215 StringRef PrefixMatch = NamespaceStr; 216 if (PrefixMatch.consume_front(Banned) && PrefixMatch.consume_front("::")) 217 return true; 218 } 219 220 return false; 221 } 222 223 std::string getNNSLAsString(NestedNameSpecifierLoc &NNSL, 224 const PrintingPolicy &Policy) { 225 std::string Out; 226 llvm::raw_string_ostream OutStream(Out); 227 NNSL.getNestedNameSpecifier()->print(OutStream, Policy); 228 return OutStream.str(); 229 } 230 231 bool AddUsing::prepare(const Selection &Inputs) { 232 auto &SM = Inputs.AST->getSourceManager(); 233 const auto &TB = Inputs.AST->getTokens(); 234 235 // Do not suggest "using" in header files. That way madness lies. 236 if (isHeaderFile(SM.getFileEntryForID(SM.getMainFileID())->getName(), 237 Inputs.AST->getLangOpts())) 238 return false; 239 240 auto *Node = Inputs.ASTSelection.commonAncestor(); 241 if (Node == nullptr) 242 return false; 243 244 // If we're looking at a type or NestedNameSpecifier, walk up the tree until 245 // we find the "main" node we care about, which would be ElaboratedTypeLoc or 246 // DeclRefExpr. 247 for (; Node->Parent; Node = Node->Parent) { 248 if (Node->ASTNode.get<NestedNameSpecifierLoc>()) { 249 continue; 250 } else if (auto *T = Node->ASTNode.get<TypeLoc>()) { 251 if (T->getAs<ElaboratedTypeLoc>()) { 252 break; 253 } else if (Node->Parent->ASTNode.get<TypeLoc>() || 254 Node->Parent->ASTNode.get<NestedNameSpecifierLoc>()) { 255 // Node is TypeLoc, but it's parent is either TypeLoc or 256 // NestedNameSpecifier. In both cases, we want to go up, to find 257 // the outermost TypeLoc. 258 continue; 259 } 260 } 261 break; 262 } 263 if (Node == nullptr) 264 return false; 265 266 if (auto *D = Node->ASTNode.get<DeclRefExpr>()) { 267 if (auto *II = D->getDecl()->getIdentifier()) { 268 QualifierToRemove = D->getQualifierLoc(); 269 Name = II->getName(); 270 MustInsertAfterLoc = D->getDecl()->getBeginLoc(); 271 } 272 } else if (auto *T = Node->ASTNode.get<TypeLoc>()) { 273 if (auto E = T->getAs<ElaboratedTypeLoc>()) { 274 QualifierToRemove = E.getQualifierLoc(); 275 276 auto SpelledTokens = 277 TB.spelledForExpanded(TB.expandedTokens(E.getSourceRange())); 278 if (!SpelledTokens) 279 return false; 280 auto SpelledRange = syntax::Token::range(SM, SpelledTokens->front(), 281 SpelledTokens->back()); 282 Name = SpelledRange.text(SM); 283 284 std::string QualifierToRemoveStr = getNNSLAsString( 285 QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy()); 286 if (!Name.consume_front(QualifierToRemoveStr)) 287 return false; // What's spelled doesn't match the qualifier. 288 289 if (const auto *ET = E.getTypePtr()) { 290 if (const auto *TDT = 291 dyn_cast<TypedefType>(ET->getNamedType().getTypePtr())) { 292 MustInsertAfterLoc = TDT->getDecl()->getBeginLoc(); 293 } else if (auto *TD = ET->getAsTagDecl()) { 294 MustInsertAfterLoc = TD->getBeginLoc(); 295 } 296 } 297 } 298 } 299 300 // FIXME: This only supports removing qualifiers that are made up of just 301 // namespace names. If qualifier contains a type, we could take the longest 302 // namespace prefix and remove that. 303 if (!QualifierToRemove.hasQualifier() || 304 !QualifierToRemove.getNestedNameSpecifier()->getAsNamespace() || 305 Name.empty()) { 306 return false; 307 } 308 309 if (isNamespaceForbidden(Inputs, *QualifierToRemove.getNestedNameSpecifier())) 310 return false; 311 312 // Macros are difficult. We only want to offer code action when what's spelled 313 // under the cursor is a namespace qualifier. If it's a macro that expands to 314 // a qualifier, user would not know what code action will actually change. 315 // On the other hand, if the qualifier is part of the macro argument, we 316 // should still support that. 317 if (SM.isMacroBodyExpansion(QualifierToRemove.getBeginLoc()) || 318 !SM.isWrittenInSameFile(QualifierToRemove.getBeginLoc(), 319 QualifierToRemove.getEndLoc())) { 320 return false; 321 } 322 323 return true; 324 } 325 326 Expected<Tweak::Effect> AddUsing::apply(const Selection &Inputs) { 327 auto &SM = Inputs.AST->getSourceManager(); 328 329 std::string QualifierToRemoveStr = getNNSLAsString( 330 QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy()); 331 tooling::Replacements R; 332 if (auto Err = R.add(tooling::Replacement( 333 SM, SM.getSpellingLoc(QualifierToRemove.getBeginLoc()), 334 QualifierToRemoveStr.length(), ""))) { 335 return std::move(Err); 336 } 337 338 auto InsertionPoint = 339 findInsertionPoint(Inputs, QualifierToRemove, Name, MustInsertAfterLoc); 340 if (!InsertionPoint) { 341 return InsertionPoint.takeError(); 342 } 343 344 if (InsertionPoint->Loc.isValid()) { 345 // Add the using statement at appropriate location. 346 std::string UsingText; 347 llvm::raw_string_ostream UsingTextStream(UsingText); 348 UsingTextStream << "using "; 349 if (InsertionPoint->AlwaysFullyQualify && 350 !isFullyQualified(QualifierToRemove.getNestedNameSpecifier())) 351 UsingTextStream << "::"; 352 UsingTextStream << QualifierToRemoveStr << Name << ";" 353 << InsertionPoint->Suffix; 354 355 assert(SM.getFileID(InsertionPoint->Loc) == SM.getMainFileID()); 356 if (auto Err = R.add(tooling::Replacement(SM, InsertionPoint->Loc, 0, 357 UsingTextStream.str()))) { 358 return std::move(Err); 359 } 360 } 361 362 return Effect::mainFileEdit(Inputs.AST->getASTContext().getSourceManager(), 363 std::move(R)); 364 } 365 366 } // namespace 367 } // namespace clangd 368 } // namespace clang 369