| 1 | //===-- ChangeNamespace.cpp - Change namespace implementation -------------===// |
| 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 "ChangeNamespace.h" |
| 9 | #include "clang/AST/ASTContext.h" |
| 10 | #include "clang/Format/Format.h" |
| 11 | #include "clang/Lex/Lexer.h" |
| 12 | #include "llvm/Support/Casting.h" |
| 13 | #include "llvm/Support/ErrorHandling.h" |
| 14 | |
| 15 | using namespace clang::ast_matchers; |
| 16 | |
| 17 | namespace clang { |
| 18 | namespace change_namespace { |
| 19 | |
| 20 | namespace { |
| 21 | |
| 22 | inline std::string joinNamespaces(ArrayRef<StringRef> Namespaces) { |
| 23 | return llvm::join(R&: Namespaces, Separator: "::" ); |
| 24 | } |
| 25 | |
| 26 | // Given "a::b::c", returns {"a", "b", "c"}. |
| 27 | llvm::SmallVector<llvm::StringRef, 4> splitSymbolName(llvm::StringRef Name) { |
| 28 | llvm::SmallVector<llvm::StringRef, 4> Splitted; |
| 29 | Name.split(A&: Splitted, Separator: "::" , /*MaxSplit=*/-1, |
| 30 | /*KeepEmpty=*/false); |
| 31 | return Splitted; |
| 32 | } |
| 33 | |
| 34 | SourceLocation startLocationForType(TypeLoc TLoc) { |
| 35 | // For elaborated types (e.g. `struct a::A`) we want the portion after the |
| 36 | // `struct` but including the namespace qualifier, `a::`. |
| 37 | if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) { |
| 38 | NestedNameSpecifierLoc NestedNameSpecifier = |
| 39 | TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc(); |
| 40 | if (NestedNameSpecifier.getNestedNameSpecifier()) |
| 41 | return NestedNameSpecifier.getBeginLoc(); |
| 42 | TLoc = TLoc.getNextTypeLoc(); |
| 43 | } |
| 44 | return TLoc.getBeginLoc(); |
| 45 | } |
| 46 | |
| 47 | SourceLocation endLocationForType(TypeLoc TLoc) { |
| 48 | // Dig past any namespace or keyword qualifications. |
| 49 | while (TLoc.getTypeLocClass() == TypeLoc::Elaborated || |
| 50 | TLoc.getTypeLocClass() == TypeLoc::Qualified) |
| 51 | TLoc = TLoc.getNextTypeLoc(); |
| 52 | |
| 53 | // The location for template specializations (e.g. Foo<int>) includes the |
| 54 | // templated types in its location range. We want to restrict this to just |
| 55 | // before the `<` character. |
| 56 | if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization) |
| 57 | return TLoc.castAs<TemplateSpecializationTypeLoc>() |
| 58 | .getLAngleLoc() |
| 59 | .getLocWithOffset(Offset: -1); |
| 60 | return TLoc.getEndLoc(); |
| 61 | } |
| 62 | |
| 63 | // Returns the containing namespace of `InnerNs` by skipping `PartialNsName`. |
| 64 | // If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName` |
| 65 | // is empty, nullptr is returned. |
| 66 | // For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then |
| 67 | // the NamespaceDecl of namespace "a" will be returned. |
| 68 | const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs, |
| 69 | llvm::StringRef PartialNsName) { |
| 70 | if (!InnerNs || PartialNsName.empty()) |
| 71 | return nullptr; |
| 72 | const auto *CurrentContext = llvm::cast<DeclContext>(Val: InnerNs); |
| 73 | const auto *CurrentNs = InnerNs; |
| 74 | auto PartialNsNameSplitted = splitSymbolName(Name: PartialNsName); |
| 75 | while (!PartialNsNameSplitted.empty()) { |
| 76 | // Get the inner-most namespace in CurrentContext. |
| 77 | while (CurrentContext && !llvm::isa<NamespaceDecl>(Val: CurrentContext)) |
| 78 | CurrentContext = CurrentContext->getParent(); |
| 79 | if (!CurrentContext) |
| 80 | return nullptr; |
| 81 | CurrentNs = llvm::cast<NamespaceDecl>(Val: CurrentContext); |
| 82 | if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString()) |
| 83 | return nullptr; |
| 84 | PartialNsNameSplitted.pop_back(); |
| 85 | CurrentContext = CurrentContext->getParent(); |
| 86 | } |
| 87 | return CurrentNs; |
| 88 | } |
| 89 | |
| 90 | static std::unique_ptr<Lexer> |
| 91 | getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM, |
| 92 | const LangOptions &LangOpts) { |
| 93 | if (Loc.isMacroID() && |
| 94 | !Lexer::isAtEndOfMacroExpansion(loc: Loc, SM, LangOpts, MacroEnd: &Loc)) |
| 95 | return nullptr; |
| 96 | // Break down the source location. |
| 97 | std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); |
| 98 | // Try to load the file buffer. |
| 99 | bool InvalidTemp = false; |
| 100 | llvm::StringRef File = SM.getBufferData(FID: LocInfo.first, Invalid: &InvalidTemp); |
| 101 | if (InvalidTemp) |
| 102 | return nullptr; |
| 103 | |
| 104 | const char *TokBegin = File.data() + LocInfo.second; |
| 105 | // Lex from the start of the given location. |
| 106 | return std::make_unique<Lexer>(args: SM.getLocForStartOfFile(FID: LocInfo.first), |
| 107 | args: LangOpts, args: File.begin(), args&: TokBegin, args: File.end()); |
| 108 | } |
| 109 | |
| 110 | // FIXME: get rid of this helper function if this is supported in clang-refactor |
| 111 | // library. |
| 112 | static SourceLocation getStartOfNextLine(SourceLocation Loc, |
| 113 | const SourceManager &SM, |
| 114 | const LangOptions &LangOpts) { |
| 115 | std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts); |
| 116 | if (!Lex) |
| 117 | return SourceLocation(); |
| 118 | llvm::SmallVector<char, 16> Line; |
| 119 | // FIXME: this is a bit hacky to get ReadToEndOfLine work. |
| 120 | Lex->setParsingPreprocessorDirective(true); |
| 121 | Lex->ReadToEndOfLine(Result: &Line); |
| 122 | auto End = Loc.getLocWithOffset(Offset: Line.size()); |
| 123 | return SM.getLocForEndOfFile(FID: SM.getDecomposedLoc(Loc).first) == End |
| 124 | ? End |
| 125 | : End.getLocWithOffset(Offset: 1); |
| 126 | } |
| 127 | |
| 128 | // Returns `R` with new range that refers to code after `Replaces` being |
| 129 | // applied. |
| 130 | tooling::Replacement |
| 131 | getReplacementInChangedCode(const tooling::Replacements &Replaces, |
| 132 | const tooling::Replacement &R) { |
| 133 | unsigned NewStart = Replaces.getShiftedCodePosition(Position: R.getOffset()); |
| 134 | unsigned NewEnd = |
| 135 | Replaces.getShiftedCodePosition(Position: R.getOffset() + R.getLength()); |
| 136 | return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart, |
| 137 | R.getReplacementText()); |
| 138 | } |
| 139 | |
| 140 | // Adds a replacement `R` into `Replaces` or merges it into `Replaces` by |
| 141 | // applying all existing Replaces first if there is conflict. |
| 142 | void addOrMergeReplacement(const tooling::Replacement &R, |
| 143 | tooling::Replacements *Replaces) { |
| 144 | auto Err = Replaces->add(R); |
| 145 | if (Err) { |
| 146 | llvm::consumeError(Err: std::move(Err)); |
| 147 | auto Replace = getReplacementInChangedCode(Replaces: *Replaces, R); |
| 148 | *Replaces = Replaces->merge(Replaces: tooling::Replacements(Replace)); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End, |
| 153 | llvm::StringRef ReplacementText, |
| 154 | const SourceManager &SM) { |
| 155 | if (!Start.isValid() || !End.isValid()) { |
| 156 | llvm::errs() << "start or end location were invalid\n" ; |
| 157 | return tooling::Replacement(); |
| 158 | } |
| 159 | if (SM.getDecomposedLoc(Loc: Start).first != SM.getDecomposedLoc(Loc: End).first) { |
| 160 | llvm::errs() |
| 161 | << "start or end location were in different macro expansions\n" ; |
| 162 | return tooling::Replacement(); |
| 163 | } |
| 164 | Start = SM.getSpellingLoc(Loc: Start); |
| 165 | End = SM.getSpellingLoc(Loc: End); |
| 166 | if (SM.getFileID(SpellingLoc: Start) != SM.getFileID(SpellingLoc: End)) { |
| 167 | llvm::errs() << "start or end location were in different files\n" ; |
| 168 | return tooling::Replacement(); |
| 169 | } |
| 170 | return tooling::Replacement( |
| 171 | SM, CharSourceRange::getTokenRange(B: SM.getSpellingLoc(Loc: Start), |
| 172 | E: SM.getSpellingLoc(Loc: End)), |
| 173 | ReplacementText); |
| 174 | } |
| 175 | |
| 176 | void addReplacementOrDie( |
| 177 | SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText, |
| 178 | const SourceManager &SM, |
| 179 | std::map<std::string, tooling::Replacements> *FileToReplacements) { |
| 180 | const auto R = createReplacement(Start, End, ReplacementText, SM); |
| 181 | auto Err = (*FileToReplacements)[std::string(R.getFilePath())].add(R); |
| 182 | if (Err) |
| 183 | llvm_unreachable(llvm::toString(std::move(Err)).c_str()); |
| 184 | } |
| 185 | |
| 186 | tooling::Replacement createInsertion(SourceLocation Loc, |
| 187 | llvm::StringRef InsertText, |
| 188 | const SourceManager &SM) { |
| 189 | if (Loc.isInvalid()) { |
| 190 | llvm::errs() << "insert Location is invalid.\n" ; |
| 191 | return tooling::Replacement(); |
| 192 | } |
| 193 | Loc = SM.getSpellingLoc(Loc); |
| 194 | return tooling::Replacement(SM, Loc, 0, InsertText); |
| 195 | } |
| 196 | |
| 197 | // Returns the shortest qualified name for declaration `DeclName` in the |
| 198 | // namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName` |
| 199 | // is "a::c::d", then "b::X" will be returned. |
| 200 | // Note that if `DeclName` is `::b::X` and `NsName` is `::a::b`, this returns |
| 201 | // "::b::X" instead of "b::X" since there will be a name conflict otherwise. |
| 202 | // \param DeclName A fully qualified name, "::a::b::X" or "a::b::X". |
| 203 | // \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace |
| 204 | // will have empty name. |
| 205 | std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName, |
| 206 | llvm::StringRef NsName) { |
| 207 | DeclName = DeclName.ltrim(Char: ':'); |
| 208 | NsName = NsName.ltrim(Char: ':'); |
| 209 | if (!DeclName.contains(C: ':')) |
| 210 | return std::string(DeclName); |
| 211 | |
| 212 | auto NsNameSplitted = splitSymbolName(Name: NsName); |
| 213 | auto DeclNsSplitted = splitSymbolName(Name: DeclName); |
| 214 | llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val(); |
| 215 | // If the Decl is in global namespace, there is no need to shorten it. |
| 216 | if (DeclNsSplitted.empty()) |
| 217 | return std::string(UnqualifiedDeclName); |
| 218 | // If NsName is the global namespace, we can simply use the DeclName sans |
| 219 | // leading "::". |
| 220 | if (NsNameSplitted.empty()) |
| 221 | return std::string(DeclName); |
| 222 | |
| 223 | if (NsNameSplitted.front() != DeclNsSplitted.front()) { |
| 224 | // The DeclName must be fully-qualified, but we still need to decide if a |
| 225 | // leading "::" is necessary. For example, if `NsName` is "a::b::c" and the |
| 226 | // `DeclName` is "b::X", then the reference must be qualified as "::b::X" |
| 227 | // to avoid conflict. |
| 228 | if (llvm::is_contained(Range&: NsNameSplitted, Element: DeclNsSplitted.front())) |
| 229 | return ("::" + DeclName).str(); |
| 230 | return std::string(DeclName); |
| 231 | } |
| 232 | // Since there is already an overlap namespace, we know that `DeclName` can be |
| 233 | // shortened, so we reduce the longest common prefix. |
| 234 | auto DeclI = DeclNsSplitted.begin(); |
| 235 | auto DeclE = DeclNsSplitted.end(); |
| 236 | auto NsI = NsNameSplitted.begin(); |
| 237 | auto NsE = NsNameSplitted.end(); |
| 238 | for (; DeclI != DeclE && NsI != NsE && *DeclI == *NsI; ++DeclI, ++NsI) { |
| 239 | } |
| 240 | return (DeclI == DeclE) |
| 241 | ? UnqualifiedDeclName.str() |
| 242 | : (llvm::join(Begin: DeclI, End: DeclE, Separator: "::" ) + "::" + UnqualifiedDeclName) |
| 243 | .str(); |
| 244 | } |
| 245 | |
| 246 | std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) { |
| 247 | if (Code.back() != '\n') |
| 248 | Code += "\n" ; |
| 249 | auto NsSplitted = splitSymbolName(Name: NestedNs); |
| 250 | while (!NsSplitted.empty()) { |
| 251 | // FIXME: consider code style for comments. |
| 252 | Code = ("namespace " + NsSplitted.back() + " {\n" + Code + |
| 253 | "} // namespace " + NsSplitted.back() + "\n" ) |
| 254 | .str(); |
| 255 | NsSplitted.pop_back(); |
| 256 | } |
| 257 | return Code; |
| 258 | } |
| 259 | |
| 260 | // Returns true if \p D is a nested DeclContext in \p Context |
| 261 | bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) { |
| 262 | while (D) { |
| 263 | if (D == Context) |
| 264 | return true; |
| 265 | D = D->getParent(); |
| 266 | } |
| 267 | return false; |
| 268 | } |
| 269 | |
| 270 | // Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx. |
| 271 | bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D, |
| 272 | const DeclContext *DeclCtx, SourceLocation Loc) { |
| 273 | SourceLocation DeclLoc = SM.getSpellingLoc(Loc: D->getBeginLoc()); |
| 274 | Loc = SM.getSpellingLoc(Loc); |
| 275 | return SM.isBeforeInTranslationUnit(LHS: DeclLoc, RHS: Loc) && |
| 276 | (SM.getFileID(SpellingLoc: DeclLoc) == SM.getFileID(SpellingLoc: Loc) && |
| 277 | isNestedDeclContext(D: DeclCtx, Context: D->getDeclContext())); |
| 278 | } |
| 279 | |
| 280 | // Given a qualified symbol name, returns true if the symbol will be |
| 281 | // incorrectly qualified without leading "::". For example, a symbol |
| 282 | // "nx::ny::Foo" in namespace "na::nx::ny" without leading "::"; a symbol |
| 283 | // "util::X" in namespace "na" can potentially conflict with "na::util" (if this |
| 284 | // exists). |
| 285 | bool conflictInNamespace(const ASTContext &AST, llvm::StringRef QualifiedSymbol, |
| 286 | llvm::StringRef Namespace) { |
| 287 | auto SymbolSplitted = splitSymbolName(Name: QualifiedSymbol.trim(Chars: ":" )); |
| 288 | assert(!SymbolSplitted.empty()); |
| 289 | SymbolSplitted.pop_back(); // We are only interested in namespaces. |
| 290 | |
| 291 | if (SymbolSplitted.size() >= 1 && !Namespace.empty()) { |
| 292 | auto SymbolTopNs = SymbolSplitted.front(); |
| 293 | auto NsSplitted = splitSymbolName(Name: Namespace.trim(Chars: ":" )); |
| 294 | assert(!NsSplitted.empty()); |
| 295 | |
| 296 | auto LookupDecl = [&AST](const Decl &Scope, |
| 297 | llvm::StringRef Name) -> const NamedDecl * { |
| 298 | const auto *DC = llvm::dyn_cast<DeclContext>(Val: &Scope); |
| 299 | if (!DC) |
| 300 | return nullptr; |
| 301 | auto LookupRes = DC->lookup(Name: DeclarationName(&AST.Idents.get(Name))); |
| 302 | if (LookupRes.empty()) |
| 303 | return nullptr; |
| 304 | return LookupRes.front(); |
| 305 | }; |
| 306 | // We do not check the outermost namespace since it would not be a |
| 307 | // conflict if it equals to the symbol's outermost namespace and the |
| 308 | // symbol name would have been shortened. |
| 309 | const NamedDecl *Scope = |
| 310 | LookupDecl(*AST.getTranslationUnitDecl(), NsSplitted.front()); |
| 311 | for (const auto &I : llvm::drop_begin(RangeOrContainer&: NsSplitted)) { |
| 312 | if (I == SymbolTopNs) // Handles "::ny" in "::nx::ny" case. |
| 313 | return true; |
| 314 | // Handles "::util" and "::nx::util" conflicts. |
| 315 | if (Scope) { |
| 316 | if (LookupDecl(*Scope, SymbolTopNs)) |
| 317 | return true; |
| 318 | Scope = LookupDecl(*Scope, I); |
| 319 | } |
| 320 | } |
| 321 | if (Scope && LookupDecl(*Scope, SymbolTopNs)) |
| 322 | return true; |
| 323 | } |
| 324 | return false; |
| 325 | } |
| 326 | |
| 327 | bool isTemplateParameter(TypeLoc Type) { |
| 328 | while (!Type.isNull()) { |
| 329 | if (Type.getTypeLocClass() == TypeLoc::SubstTemplateTypeParm) |
| 330 | return true; |
| 331 | Type = Type.getNextTypeLoc(); |
| 332 | } |
| 333 | return false; |
| 334 | } |
| 335 | |
| 336 | } // anonymous namespace |
| 337 | |
| 338 | ChangeNamespaceTool::ChangeNamespaceTool( |
| 339 | llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern, |
| 340 | llvm::ArrayRef<std::string> AllowedSymbolPatterns, |
| 341 | std::map<std::string, tooling::Replacements> *FileToReplacements, |
| 342 | llvm::StringRef FallbackStyle) |
| 343 | : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements), |
| 344 | OldNamespace(OldNs.ltrim(Char: ':')), NewNamespace(NewNs.ltrim(Char: ':')), |
| 345 | FilePattern(FilePattern), FilePatternRE(FilePattern) { |
| 346 | FileToReplacements->clear(); |
| 347 | auto OldNsSplitted = splitSymbolName(Name: OldNamespace); |
| 348 | auto NewNsSplitted = splitSymbolName(Name: NewNamespace); |
| 349 | // Calculates `DiffOldNamespace` and `DiffNewNamespace`. |
| 350 | while (!OldNsSplitted.empty() && !NewNsSplitted.empty() && |
| 351 | OldNsSplitted.front() == NewNsSplitted.front()) { |
| 352 | OldNsSplitted.erase(CI: OldNsSplitted.begin()); |
| 353 | NewNsSplitted.erase(CI: NewNsSplitted.begin()); |
| 354 | } |
| 355 | DiffOldNamespace = joinNamespaces(Namespaces: OldNsSplitted); |
| 356 | DiffNewNamespace = joinNamespaces(Namespaces: NewNsSplitted); |
| 357 | |
| 358 | for (const auto &Pattern : AllowedSymbolPatterns) |
| 359 | AllowedSymbolRegexes.emplace_back(args: Pattern); |
| 360 | } |
| 361 | |
| 362 | void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
| 363 | std::string FullOldNs = "::" + OldNamespace; |
| 364 | // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the |
| 365 | // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will |
| 366 | // be "a::b". Declarations in this namespace will not be visible in the new |
| 367 | // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-". |
| 368 | llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted; |
| 369 | llvm::StringRef(DiffOldNamespace) |
| 370 | .split(A&: DiffOldNsSplitted, Separator: "::" , /*MaxSplit=*/-1, |
| 371 | /*KeepEmpty=*/false); |
| 372 | std::string Prefix = "-" ; |
| 373 | if (!DiffOldNsSplitted.empty()) |
| 374 | Prefix = (StringRef(FullOldNs).drop_back(N: DiffOldNamespace.size()) + |
| 375 | DiffOldNsSplitted.front()) |
| 376 | .str(); |
| 377 | auto IsInMovedNs = |
| 378 | allOf(hasAncestor(namespaceDecl(hasName(Name: FullOldNs)).bind(ID: "ns_decl" )), |
| 379 | isExpansionInFileMatching(RegExp: FilePattern)); |
| 380 | auto IsVisibleInNewNs = anyOf( |
| 381 | IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Name: Prefix))))); |
| 382 | // Match using declarations. |
| 383 | Finder->addMatcher( |
| 384 | NodeMatch: usingDecl(isExpansionInFileMatching(RegExp: FilePattern), IsVisibleInNewNs) |
| 385 | .bind(ID: "using" ), |
| 386 | Action: this); |
| 387 | // Match using namespace declarations. |
| 388 | Finder->addMatcher(NodeMatch: usingDirectiveDecl(isExpansionInFileMatching(RegExp: FilePattern), |
| 389 | IsVisibleInNewNs) |
| 390 | .bind(ID: "using_namespace" ), |
| 391 | Action: this); |
| 392 | // Match namespace alias declarations. |
| 393 | Finder->addMatcher(NodeMatch: namespaceAliasDecl(isExpansionInFileMatching(RegExp: FilePattern), |
| 394 | IsVisibleInNewNs) |
| 395 | .bind(ID: "namespace_alias" ), |
| 396 | Action: this); |
| 397 | |
| 398 | // Match old namespace blocks. |
| 399 | Finder->addMatcher( |
| 400 | NodeMatch: namespaceDecl(hasName(Name: FullOldNs), isExpansionInFileMatching(RegExp: FilePattern)) |
| 401 | .bind(ID: "old_ns" ), |
| 402 | Action: this); |
| 403 | |
| 404 | // Match class forward-declarations in the old namespace. |
| 405 | // Note that forward-declarations in classes are not matched. |
| 406 | Finder->addMatcher(NodeMatch: cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), |
| 407 | IsInMovedNs, hasParent(namespaceDecl())) |
| 408 | .bind(ID: "class_fwd_decl" ), |
| 409 | Action: this); |
| 410 | |
| 411 | // Match template class forward-declarations in the old namespace. |
| 412 | Finder->addMatcher( |
| 413 | NodeMatch: classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))), |
| 414 | IsInMovedNs, hasParent(namespaceDecl())) |
| 415 | .bind(ID: "template_class_fwd_decl" ), |
| 416 | Action: this); |
| 417 | |
| 418 | // Match references to types that are not defined in the old namespace. |
| 419 | // Forward-declarations in the old namespace are also matched since they will |
| 420 | // be moved back to the old namespace. |
| 421 | auto DeclMatcher = namedDecl( |
| 422 | hasAncestor(namespaceDecl()), |
| 423 | unless(anyOf( |
| 424 | isImplicit(), hasAncestor(namespaceDecl(isAnonymous())), |
| 425 | hasAncestor(cxxRecordDecl()), |
| 426 | allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition()))))))); |
| 427 | |
| 428 | // Using shadow declarations in classes always refers to base class, which |
| 429 | // does not need to be qualified since it can be inferred from inheritance. |
| 430 | // Note that this does not match using alias declarations. |
| 431 | auto UsingShadowDeclInClass = |
| 432 | usingDecl(hasAnyUsingShadowDecl(InnerMatcher: decl()), hasParent(cxxRecordDecl())); |
| 433 | |
| 434 | // Match TypeLocs on the declaration. Carefully match only the outermost |
| 435 | // TypeLoc and template specialization arguments (which are not outermost) |
| 436 | // that are directly linked to types matching `DeclMatcher`. Nested name |
| 437 | // specifier locs are handled separately below. |
| 438 | Finder->addMatcher( |
| 439 | NodeMatch: typeLoc(IsInMovedNs, |
| 440 | loc(InnerMatcher: qualType(hasDeclaration(InnerMatcher: DeclMatcher.bind(ID: "from_decl" )))), |
| 441 | unless(anyOf(hasParent(typeLoc(loc(InnerMatcher: qualType( |
| 442 | hasDeclaration(InnerMatcher: DeclMatcher), |
| 443 | unless(templateSpecializationType()))))), |
| 444 | hasParent(nestedNameSpecifierLoc()), |
| 445 | hasAncestor(decl(isImplicit())), |
| 446 | hasAncestor(UsingShadowDeclInClass), |
| 447 | hasAncestor(functionDecl(isDefaulted())))), |
| 448 | hasAncestor(decl().bind(ID: "dc" ))) |
| 449 | .bind(ID: "type" ), |
| 450 | Action: this); |
| 451 | |
| 452 | // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to |
| 453 | // special case it. |
| 454 | // Since using declarations inside classes must have the base class in the |
| 455 | // nested name specifier, we leave it to the nested name specifier matcher. |
| 456 | Finder->addMatcher(NodeMatch: usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(InnerMatcher: decl()), |
| 457 | unless(UsingShadowDeclInClass)) |
| 458 | .bind(ID: "using_with_shadow" ), |
| 459 | Action: this); |
| 460 | |
| 461 | // Handle types in nested name specifier. Specifiers that are in a TypeLoc |
| 462 | // matched above are not matched, e.g. "A::" in "A::A" is not matched since |
| 463 | // "A::A" would have already been fixed. |
| 464 | Finder->addMatcher( |
| 465 | NodeMatch: nestedNameSpecifierLoc( |
| 466 | hasAncestor(decl(IsInMovedNs).bind(ID: "dc" )), |
| 467 | loc(InnerMatcher: nestedNameSpecifier( |
| 468 | specifiesType(InnerMatcher: hasDeclaration(InnerMatcher: DeclMatcher.bind(ID: "from_decl" ))))), |
| 469 | unless(anyOf(hasAncestor(decl(isImplicit())), |
| 470 | hasAncestor(UsingShadowDeclInClass), |
| 471 | hasAncestor(functionDecl(isDefaulted())), |
| 472 | hasAncestor(typeLoc(loc(InnerMatcher: qualType(hasDeclaration( |
| 473 | InnerMatcher: decl(equalsBoundNode(ID: "from_decl" )))))))))) |
| 474 | .bind(ID: "nested_specifier_loc" ), |
| 475 | Action: this); |
| 476 | |
| 477 | // Matches base class initializers in constructors. TypeLocs of base class |
| 478 | // initializers do not need to be fixed. For example, |
| 479 | // class X : public a::b::Y { |
| 480 | // public: |
| 481 | // X() : Y::Y() {} // Y::Y do not need namespace specifier. |
| 482 | // }; |
| 483 | Finder->addMatcher( |
| 484 | NodeMatch: cxxCtorInitializer(isBaseInitializer()).bind(ID: "base_initializer" ), Action: this); |
| 485 | |
| 486 | // Handle function. |
| 487 | // Only handle functions that are defined in a namespace excluding member |
| 488 | // function, static methods (qualified by nested specifier), and functions |
| 489 | // defined in the global namespace. |
| 490 | // Note that the matcher does not exclude calls to out-of-line static method |
| 491 | // definitions, so we need to exclude them in the callback handler. |
| 492 | auto FuncMatcher = |
| 493 | functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs, |
| 494 | hasAncestor(namespaceDecl(isAnonymous())), |
| 495 | hasAncestor(cxxRecordDecl()))), |
| 496 | hasParent(namespaceDecl())); |
| 497 | Finder->addMatcher(NodeMatch: expr(hasAncestor(decl().bind(ID: "dc" )), IsInMovedNs, |
| 498 | unless(hasAncestor(decl(isImplicit()))), |
| 499 | anyOf(callExpr(callee(InnerMatcher: FuncMatcher)).bind(ID: "call" ), |
| 500 | declRefExpr(to(InnerMatcher: FuncMatcher.bind(ID: "func_decl" ))) |
| 501 | .bind(ID: "func_ref" ))), |
| 502 | Action: this); |
| 503 | |
| 504 | auto GlobalVarMatcher = varDecl( |
| 505 | hasGlobalStorage(), hasParent(namespaceDecl()), |
| 506 | unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous()))))); |
| 507 | Finder->addMatcher(NodeMatch: declRefExpr(IsInMovedNs, hasAncestor(decl().bind(ID: "dc" )), |
| 508 | to(InnerMatcher: GlobalVarMatcher.bind(ID: "var_decl" ))) |
| 509 | .bind(ID: "var_ref" ), |
| 510 | Action: this); |
| 511 | |
| 512 | // Handle unscoped enum constant. |
| 513 | auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl( |
| 514 | hasParent(namespaceDecl()), |
| 515 | unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()), |
| 516 | hasAncestor(namespaceDecl(isAnonymous()))))))); |
| 517 | Finder->addMatcher( |
| 518 | NodeMatch: declRefExpr(IsInMovedNs, hasAncestor(decl().bind(ID: "dc" )), |
| 519 | to(InnerMatcher: UnscopedEnumMatcher.bind(ID: "enum_const_decl" ))) |
| 520 | .bind(ID: "enum_const_ref" ), |
| 521 | Action: this); |
| 522 | } |
| 523 | |
| 524 | void ChangeNamespaceTool::run( |
| 525 | const ast_matchers::MatchFinder::MatchResult &Result) { |
| 526 | if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>(ID: "using" )) { |
| 527 | UsingDecls.insert(Ptr: Using); |
| 528 | } else if (const auto *UsingNamespace = |
| 529 | Result.Nodes.getNodeAs<UsingDirectiveDecl>( |
| 530 | ID: "using_namespace" )) { |
| 531 | UsingNamespaceDecls.insert(Ptr: UsingNamespace); |
| 532 | } else if (const auto *NamespaceAlias = |
| 533 | Result.Nodes.getNodeAs<NamespaceAliasDecl>( |
| 534 | ID: "namespace_alias" )) { |
| 535 | NamespaceAliasDecls.insert(Ptr: NamespaceAlias); |
| 536 | } else if (const auto *NsDecl = |
| 537 | Result.Nodes.getNodeAs<NamespaceDecl>(ID: "old_ns" )) { |
| 538 | moveOldNamespace(Result, NsDecl); |
| 539 | } else if (const auto *FwdDecl = |
| 540 | Result.Nodes.getNodeAs<CXXRecordDecl>(ID: "class_fwd_decl" )) { |
| 541 | moveClassForwardDeclaration(Result, FwdDecl: cast<NamedDecl>(Val: FwdDecl)); |
| 542 | } else if (const auto *TemplateFwdDecl = |
| 543 | Result.Nodes.getNodeAs<ClassTemplateDecl>( |
| 544 | ID: "template_class_fwd_decl" )) { |
| 545 | moveClassForwardDeclaration(Result, FwdDecl: cast<NamedDecl>(Val: TemplateFwdDecl)); |
| 546 | } else if (const auto *UsingWithShadow = |
| 547 | Result.Nodes.getNodeAs<UsingDecl>(ID: "using_with_shadow" )) { |
| 548 | fixUsingShadowDecl(Result, UsingDeclaration: UsingWithShadow); |
| 549 | } else if (const auto *Specifier = |
| 550 | Result.Nodes.getNodeAs<NestedNameSpecifierLoc>( |
| 551 | ID: "nested_specifier_loc" )) { |
| 552 | SourceLocation Start = Specifier->getBeginLoc(); |
| 553 | SourceLocation End = endLocationForType(TLoc: Specifier->getTypeLoc()); |
| 554 | fixTypeLoc(Result, Start, End, Type: Specifier->getTypeLoc()); |
| 555 | } else if (const auto *BaseInitializer = |
| 556 | Result.Nodes.getNodeAs<CXXCtorInitializer>( |
| 557 | ID: "base_initializer" )) { |
| 558 | BaseCtorInitializerTypeLocs.push_back( |
| 559 | Elt: BaseInitializer->getTypeSourceInfo()->getTypeLoc()); |
| 560 | } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>(ID: "type" )) { |
| 561 | // This avoids fixing types with record types as qualifier, which is not |
| 562 | // filtered by matchers in some cases, e.g. the type is templated. We should |
| 563 | // handle the record type qualifier instead. |
| 564 | TypeLoc Loc = *TLoc; |
| 565 | while (Loc.getTypeLocClass() == TypeLoc::Qualified) |
| 566 | Loc = Loc.getNextTypeLoc(); |
| 567 | if (Loc.getTypeLocClass() == TypeLoc::Elaborated) { |
| 568 | NestedNameSpecifierLoc NestedNameSpecifier = |
| 569 | Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc(); |
| 570 | // FIXME: avoid changing injected class names. |
| 571 | if (auto *NNS = NestedNameSpecifier.getNestedNameSpecifier()) { |
| 572 | const Type *SpecifierType = NNS->getAsType(); |
| 573 | if (SpecifierType && SpecifierType->isRecordType()) |
| 574 | return; |
| 575 | } |
| 576 | } |
| 577 | fixTypeLoc(Result, Start: startLocationForType(TLoc: Loc), End: endLocationForType(TLoc: Loc), Type: Loc); |
| 578 | } else if (const auto *VarRef = |
| 579 | Result.Nodes.getNodeAs<DeclRefExpr>(ID: "var_ref" )) { |
| 580 | const auto *Var = Result.Nodes.getNodeAs<VarDecl>(ID: "var_decl" ); |
| 581 | assert(Var); |
| 582 | if (Var->getCanonicalDecl()->isStaticDataMember()) |
| 583 | return; |
| 584 | const auto *Context = Result.Nodes.getNodeAs<Decl>(ID: "dc" ); |
| 585 | assert(Context && "Empty decl context." ); |
| 586 | fixDeclRefExpr(Result, UseContext: Context->getDeclContext(), |
| 587 | From: llvm::cast<NamedDecl>(Val: Var), Ref: VarRef); |
| 588 | } else if (const auto *EnumConstRef = |
| 589 | Result.Nodes.getNodeAs<DeclRefExpr>(ID: "enum_const_ref" )) { |
| 590 | // Do not rename the reference if it is already scoped by the EnumDecl name. |
| 591 | if (EnumConstRef->hasQualifier() && |
| 592 | EnumConstRef->getQualifier()->getKind() == |
| 593 | NestedNameSpecifier::SpecifierKind::TypeSpec && |
| 594 | EnumConstRef->getQualifier()->getAsType()->isEnumeralType()) |
| 595 | return; |
| 596 | const auto *EnumConstDecl = |
| 597 | Result.Nodes.getNodeAs<EnumConstantDecl>(ID: "enum_const_decl" ); |
| 598 | assert(EnumConstDecl); |
| 599 | const auto *Context = Result.Nodes.getNodeAs<Decl>(ID: "dc" ); |
| 600 | assert(Context && "Empty decl context." ); |
| 601 | // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it |
| 602 | // if it turns out to be an issue. |
| 603 | fixDeclRefExpr(Result, UseContext: Context->getDeclContext(), |
| 604 | From: llvm::cast<NamedDecl>(Val: EnumConstDecl), Ref: EnumConstRef); |
| 605 | } else if (const auto *FuncRef = |
| 606 | Result.Nodes.getNodeAs<DeclRefExpr>(ID: "func_ref" )) { |
| 607 | // If this reference has been processed as a function call, we do not |
| 608 | // process it again. |
| 609 | if (!ProcessedFuncRefs.insert(Ptr: FuncRef).second) |
| 610 | return; |
| 611 | const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(ID: "func_decl" ); |
| 612 | assert(Func); |
| 613 | const auto *Context = Result.Nodes.getNodeAs<Decl>(ID: "dc" ); |
| 614 | assert(Context && "Empty decl context." ); |
| 615 | fixDeclRefExpr(Result, UseContext: Context->getDeclContext(), |
| 616 | From: llvm::cast<NamedDecl>(Val: Func), Ref: FuncRef); |
| 617 | } else { |
| 618 | const auto *Call = Result.Nodes.getNodeAs<CallExpr>(ID: "call" ); |
| 619 | assert(Call != nullptr && "Expecting callback for CallExpr." ); |
| 620 | const auto *CalleeFuncRef = |
| 621 | llvm::cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()); |
| 622 | ProcessedFuncRefs.insert(Ptr: CalleeFuncRef); |
| 623 | const FunctionDecl *Func = Call->getDirectCallee(); |
| 624 | assert(Func != nullptr); |
| 625 | // FIXME: ignore overloaded operators. This would miss cases where operators |
| 626 | // are called by qualified names (i.e. "ns::operator <"). Ignore such |
| 627 | // cases for now. |
| 628 | if (Func->isOverloadedOperator()) |
| 629 | return; |
| 630 | // Ignore out-of-line static methods since they will be handled by nested |
| 631 | // name specifiers. |
| 632 | if (Func->getCanonicalDecl()->getStorageClass() == |
| 633 | StorageClass::SC_Static && |
| 634 | Func->isOutOfLine()) |
| 635 | return; |
| 636 | const auto *Context = Result.Nodes.getNodeAs<Decl>(ID: "dc" ); |
| 637 | assert(Context && "Empty decl context." ); |
| 638 | SourceRange CalleeRange = Call->getCallee()->getSourceRange(); |
| 639 | replaceQualifiedSymbolInDeclContext( |
| 640 | Result, DeclContext: Context->getDeclContext(), Start: CalleeRange.getBegin(), |
| 641 | End: CalleeRange.getEnd(), FromDecl: llvm::cast<NamedDecl>(Val: Func)); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl, |
| 646 | const SourceManager &SM, |
| 647 | const LangOptions &LangOpts) { |
| 648 | std::unique_ptr<Lexer> Lex = |
| 649 | getLexerStartingFromLoc(Loc: NsDecl->getBeginLoc(), SM, LangOpts); |
| 650 | assert(Lex && "Failed to create lexer from the beginning of namespace." ); |
| 651 | if (!Lex) |
| 652 | return SourceLocation(); |
| 653 | Token Tok; |
| 654 | while (!Lex->LexFromRawLexer(Result&: Tok) && Tok.isNot(K: tok::TokenKind::l_brace)) { |
| 655 | } |
| 656 | return Tok.isNot(K: tok::TokenKind::l_brace) |
| 657 | ? SourceLocation() |
| 658 | : Tok.getEndLoc().getLocWithOffset(Offset: 1); |
| 659 | } |
| 660 | |
| 661 | // Stores information about a moved namespace in `MoveNamespaces` and leaves |
| 662 | // the actual movement to `onEndOfTranslationUnit()`. |
| 663 | void ChangeNamespaceTool::moveOldNamespace( |
| 664 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 665 | const NamespaceDecl *NsDecl) { |
| 666 | // If the namespace is empty, do nothing. |
| 667 | if (Decl::castToDeclContext(NsDecl)->decls_empty()) |
| 668 | return; |
| 669 | |
| 670 | const SourceManager &SM = *Result.SourceManager; |
| 671 | // Get the range of the code in the old namespace. |
| 672 | SourceLocation Start = |
| 673 | getLocAfterNamespaceLBrace(NsDecl, SM, LangOpts: Result.Context->getLangOpts()); |
| 674 | assert(Start.isValid() && "Can't find l_brace for namespace." ); |
| 675 | MoveNamespace MoveNs; |
| 676 | MoveNs.Offset = SM.getFileOffset(SpellingLoc: Start); |
| 677 | // The range of the moved namespace is from the location just past the left |
| 678 | // brace to the location right before the right brace. |
| 679 | MoveNs.Length = SM.getFileOffset(SpellingLoc: NsDecl->getRBraceLoc()) - MoveNs.Offset; |
| 680 | |
| 681 | // Insert the new namespace after `DiffOldNamespace`. For example, if |
| 682 | // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then |
| 683 | // "x::y" will be inserted inside the existing namespace "a" and after "a::b". |
| 684 | // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b" |
| 685 | // in the above example. |
| 686 | // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new |
| 687 | // namespace will be a nested namespace in the old namespace. |
| 688 | const NamespaceDecl *OuterNs = getOuterNamespace(InnerNs: NsDecl, PartialNsName: DiffOldNamespace); |
| 689 | SourceLocation InsertionLoc = Start; |
| 690 | if (OuterNs) { |
| 691 | SourceLocation LocAfterNs = getStartOfNextLine( |
| 692 | Loc: OuterNs->getRBraceLoc(), SM, LangOpts: Result.Context->getLangOpts()); |
| 693 | assert(LocAfterNs.isValid() && |
| 694 | "Failed to get location after DiffOldNamespace" ); |
| 695 | InsertionLoc = LocAfterNs; |
| 696 | } |
| 697 | MoveNs.InsertionOffset = SM.getFileOffset(SpellingLoc: SM.getSpellingLoc(Loc: InsertionLoc)); |
| 698 | MoveNs.FID = SM.getFileID(SpellingLoc: Start); |
| 699 | MoveNs.SourceMgr = Result.SourceManager; |
| 700 | MoveNamespaces[std::string(SM.getFilename(SpellingLoc: Start))].push_back(x: MoveNs); |
| 701 | } |
| 702 | |
| 703 | // Removes a class forward declaration from the code in the moved namespace and |
| 704 | // creates an `InsertForwardDeclaration` to insert the forward declaration back |
| 705 | // into the old namespace after moving code from the old namespace to the new |
| 706 | // namespace. |
| 707 | // For example, changing "a" to "x": |
| 708 | // Old code: |
| 709 | // namespace a { |
| 710 | // class FWD; |
| 711 | // class A { FWD *fwd; } |
| 712 | // } // a |
| 713 | // New code: |
| 714 | // namespace a { |
| 715 | // class FWD; |
| 716 | // } // a |
| 717 | // namespace x { |
| 718 | // class A { a::FWD *fwd; } |
| 719 | // } // x |
| 720 | void ChangeNamespaceTool::moveClassForwardDeclaration( |
| 721 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 722 | const NamedDecl *FwdDecl) { |
| 723 | SourceLocation Start = FwdDecl->getBeginLoc(); |
| 724 | SourceLocation End = FwdDecl->getEndLoc(); |
| 725 | const SourceManager &SM = *Result.SourceManager; |
| 726 | SourceLocation AfterSemi = Lexer::findLocationAfterToken( |
| 727 | loc: End, TKind: tok::semi, SM, LangOpts: Result.Context->getLangOpts(), |
| 728 | /*SkipTrailingWhitespaceAndNewLine=*/true); |
| 729 | if (AfterSemi.isValid()) |
| 730 | End = AfterSemi.getLocWithOffset(Offset: -1); |
| 731 | // Delete the forward declaration from the code to be moved. |
| 732 | addReplacementOrDie(Start, End, ReplacementText: "" , SM, FileToReplacements: &FileToReplacements); |
| 733 | llvm::StringRef Code = Lexer::getSourceText( |
| 734 | Range: CharSourceRange::getTokenRange(B: SM.getSpellingLoc(Loc: Start), |
| 735 | E: SM.getSpellingLoc(Loc: End)), |
| 736 | SM, LangOpts: Result.Context->getLangOpts()); |
| 737 | // Insert the forward declaration back into the old namespace after moving the |
| 738 | // code from old namespace to new namespace. |
| 739 | // Insertion information is stored in `InsertFwdDecls` and actual |
| 740 | // insertion will be performed in `onEndOfTranslationUnit`. |
| 741 | // Get the (old) namespace that contains the forward declaration. |
| 742 | const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>(ID: "ns_decl" ); |
| 743 | // The namespace contains the forward declaration, so it must not be empty. |
| 744 | assert(!NsDecl->decls_empty()); |
| 745 | const auto Insertion = createInsertion( |
| 746 | Loc: getLocAfterNamespaceLBrace(NsDecl, SM, LangOpts: Result.Context->getLangOpts()), |
| 747 | InsertText: Code, SM); |
| 748 | InsertForwardDeclaration InsertFwd; |
| 749 | InsertFwd.InsertionOffset = Insertion.getOffset(); |
| 750 | InsertFwd.ForwardDeclText = Insertion.getReplacementText().str(); |
| 751 | InsertFwdDecls[std::string(Insertion.getFilePath())].push_back(x: InsertFwd); |
| 752 | } |
| 753 | |
| 754 | // Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p |
| 755 | // FromDecl with the shortest qualified name possible when the reference is in |
| 756 | // `NewNamespace`. |
| 757 | void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext( |
| 758 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 759 | const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End, |
| 760 | const NamedDecl *FromDecl) { |
| 761 | const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext(); |
| 762 | if (llvm::isa<TranslationUnitDecl>(Val: NsDeclContext)) { |
| 763 | // This should not happen in usual unless the TypeLoc is in function type |
| 764 | // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of |
| 765 | // `T` will be the translation unit. We simply use fully-qualified name |
| 766 | // here. |
| 767 | // Note that `FromDecl` must not be defined in the old namespace (according |
| 768 | // to `DeclMatcher`), so its fully-qualified name will not change after |
| 769 | // changing the namespace. |
| 770 | addReplacementOrDie(Start, End, ReplacementText: FromDecl->getQualifiedNameAsString(), |
| 771 | SM: *Result.SourceManager, FileToReplacements: &FileToReplacements); |
| 772 | return; |
| 773 | } |
| 774 | const auto *NsDecl = llvm::cast<NamespaceDecl>(Val: NsDeclContext); |
| 775 | // Calculate the name of the `NsDecl` after it is moved to new namespace. |
| 776 | std::string OldNs = NsDecl->getQualifiedNameAsString(); |
| 777 | llvm::StringRef Postfix = OldNs; |
| 778 | bool Consumed = Postfix.consume_front(Prefix: OldNamespace); |
| 779 | assert(Consumed && "Expect OldNS to start with OldNamespace." ); |
| 780 | (void)Consumed; |
| 781 | const std::string NewNs = (NewNamespace + Postfix).str(); |
| 782 | |
| 783 | llvm::StringRef NestedName = Lexer::getSourceText( |
| 784 | Range: CharSourceRange::getTokenRange( |
| 785 | B: Result.SourceManager->getSpellingLoc(Loc: Start), |
| 786 | E: Result.SourceManager->getSpellingLoc(Loc: End)), |
| 787 | SM: *Result.SourceManager, LangOpts: Result.Context->getLangOpts()); |
| 788 | std::string FromDeclName = FromDecl->getQualifiedNameAsString(); |
| 789 | for (llvm::Regex &RE : AllowedSymbolRegexes) |
| 790 | if (RE.match(String: FromDeclName)) |
| 791 | return; |
| 792 | std::string ReplaceName = |
| 793 | getShortestQualifiedNameInNamespace(DeclName: FromDeclName, NsName: NewNs); |
| 794 | // Checks if there is any using namespace declarations that can shorten the |
| 795 | // qualified name. |
| 796 | for (const auto *UsingNamespace : UsingNamespaceDecls) { |
| 797 | if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx, |
| 798 | Start)) |
| 799 | continue; |
| 800 | StringRef FromDeclNameRef = FromDeclName; |
| 801 | if (FromDeclNameRef.consume_front(Prefix: UsingNamespace->getNominatedNamespace() |
| 802 | ->getQualifiedNameAsString())) { |
| 803 | FromDeclNameRef = FromDeclNameRef.drop_front(N: 2); |
| 804 | if (FromDeclNameRef.size() < ReplaceName.size()) |
| 805 | ReplaceName = std::string(FromDeclNameRef); |
| 806 | } |
| 807 | } |
| 808 | // Checks if there is any namespace alias declarations that can shorten the |
| 809 | // qualified name. |
| 810 | for (const auto *NamespaceAlias : NamespaceAliasDecls) { |
| 811 | if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx, |
| 812 | Start)) |
| 813 | continue; |
| 814 | StringRef FromDeclNameRef = FromDeclName; |
| 815 | if (FromDeclNameRef.consume_front( |
| 816 | Prefix: NamespaceAlias->getNamespace()->getQualifiedNameAsString() + |
| 817 | "::" )) { |
| 818 | std::string AliasName = NamespaceAlias->getNameAsString(); |
| 819 | std::string AliasQualifiedName = |
| 820 | NamespaceAlias->getQualifiedNameAsString(); |
| 821 | // We only consider namespace aliases define in the global namespace or |
| 822 | // in namespaces that are directly visible from the reference, i.e. |
| 823 | // ancestor of the `OldNs`. Note that declarations in ancestor namespaces |
| 824 | // but not visible in the new namespace is filtered out by |
| 825 | // "IsVisibleInNewNs" matcher. |
| 826 | if (AliasQualifiedName != AliasName) { |
| 827 | // The alias is defined in some namespace. |
| 828 | assert(StringRef(AliasQualifiedName).ends_with("::" + AliasName)); |
| 829 | llvm::StringRef AliasNs = |
| 830 | StringRef(AliasQualifiedName).drop_back(N: AliasName.size() + 2); |
| 831 | if (!llvm::StringRef(OldNs).starts_with(Prefix: AliasNs)) |
| 832 | continue; |
| 833 | } |
| 834 | std::string NameWithAliasNamespace = |
| 835 | (AliasName + "::" + FromDeclNameRef).str(); |
| 836 | if (NameWithAliasNamespace.size() < ReplaceName.size()) |
| 837 | ReplaceName = NameWithAliasNamespace; |
| 838 | } |
| 839 | } |
| 840 | // Checks if there is any using shadow declarations that can shorten the |
| 841 | // qualified name. |
| 842 | bool Matched = false; |
| 843 | for (const UsingDecl *Using : UsingDecls) { |
| 844 | if (Matched) |
| 845 | break; |
| 846 | if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) { |
| 847 | for (const auto *UsingShadow : Using->shadows()) { |
| 848 | const auto *TargetDecl = UsingShadow->getTargetDecl(); |
| 849 | if (TargetDecl->getQualifiedNameAsString() == |
| 850 | FromDecl->getQualifiedNameAsString()) { |
| 851 | ReplaceName = FromDecl->getNameAsString(); |
| 852 | Matched = true; |
| 853 | break; |
| 854 | } |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | bool Conflict = conflictInNamespace(AST: DeclCtx->getParentASTContext(), |
| 859 | QualifiedSymbol: ReplaceName, Namespace: NewNamespace); |
| 860 | // If the new nested name in the new namespace is the same as it was in the |
| 861 | // old namespace, we don't create replacement unless there can be ambiguity. |
| 862 | if ((NestedName == ReplaceName && !Conflict) || |
| 863 | (NestedName.starts_with(Prefix: "::" ) && NestedName.drop_front(N: 2) == ReplaceName)) |
| 864 | return; |
| 865 | // If the reference need to be fully-qualified, add a leading "::" unless |
| 866 | // NewNamespace is the global namespace. |
| 867 | if (ReplaceName == FromDeclName && !NewNamespace.empty() && Conflict) |
| 868 | ReplaceName = "::" + ReplaceName; |
| 869 | addReplacementOrDie(Start, End, ReplacementText: ReplaceName, SM: *Result.SourceManager, |
| 870 | FileToReplacements: &FileToReplacements); |
| 871 | } |
| 872 | |
| 873 | // Replace the [Start, End] of `Type` with the shortest qualified name when the |
| 874 | // `Type` is in `NewNamespace`. |
| 875 | void ChangeNamespaceTool::fixTypeLoc( |
| 876 | const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start, |
| 877 | SourceLocation End, TypeLoc Type) { |
| 878 | // FIXME: do not rename template parameter. |
| 879 | if (Start.isInvalid() || End.isInvalid()) |
| 880 | return; |
| 881 | // Types of CXXCtorInitializers do not need to be fixed. |
| 882 | if (llvm::is_contained(Range&: BaseCtorInitializerTypeLocs, Element: Type)) |
| 883 | return; |
| 884 | if (isTemplateParameter(Type)) |
| 885 | return; |
| 886 | // The declaration which this TypeLoc refers to. |
| 887 | const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>(ID: "from_decl" ); |
| 888 | // `hasDeclaration` gives underlying declaration, but if the type is |
| 889 | // a typedef type, we need to use the typedef type instead. |
| 890 | auto IsInMovedNs = [&](const NamedDecl *D) { |
| 891 | if (!llvm::StringRef(D->getQualifiedNameAsString()) |
| 892 | .starts_with(Prefix: OldNamespace + "::" )) |
| 893 | return false; |
| 894 | auto ExpansionLoc = Result.SourceManager->getExpansionLoc(Loc: D->getBeginLoc()); |
| 895 | if (ExpansionLoc.isInvalid()) |
| 896 | return false; |
| 897 | llvm::StringRef Filename = Result.SourceManager->getFilename(SpellingLoc: ExpansionLoc); |
| 898 | return FilePatternRE.match(Filename); |
| 899 | }; |
| 900 | // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if |
| 901 | // `Type` is an alias type, we make `FromDecl` the type alias declaration. |
| 902 | // Also, don't fix the \p Type if it refers to a type alias decl in the moved |
| 903 | // namespace since the alias decl will be moved along with the type reference. |
| 904 | if (auto *Typedef = Type.getType()->getAs<TypedefType>()) { |
| 905 | FromDecl = Typedef->getDecl(); |
| 906 | if (IsInMovedNs(FromDecl)) |
| 907 | return; |
| 908 | } else if (auto *TemplateType = |
| 909 | Type.getType()->getAs<TemplateSpecializationType>()) { |
| 910 | if (TemplateType->isTypeAlias()) { |
| 911 | FromDecl = TemplateType->getTemplateName().getAsTemplateDecl(); |
| 912 | if (IsInMovedNs(FromDecl)) |
| 913 | return; |
| 914 | } |
| 915 | } |
| 916 | const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>(ID: "dc" ); |
| 917 | assert(DeclCtx && "Empty decl context." ); |
| 918 | replaceQualifiedSymbolInDeclContext(Result, DeclCtx: DeclCtx->getDeclContext(), Start, |
| 919 | End, FromDecl); |
| 920 | } |
| 921 | |
| 922 | void ChangeNamespaceTool::fixUsingShadowDecl( |
| 923 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 924 | const UsingDecl *UsingDeclaration) { |
| 925 | SourceLocation Start = UsingDeclaration->getBeginLoc(); |
| 926 | SourceLocation End = UsingDeclaration->getEndLoc(); |
| 927 | if (Start.isInvalid() || End.isInvalid()) |
| 928 | return; |
| 929 | |
| 930 | assert(UsingDeclaration->shadow_size() > 0); |
| 931 | // FIXME: it might not be always accurate to use the first using-decl. |
| 932 | const NamedDecl *TargetDecl = |
| 933 | UsingDeclaration->shadow_begin()->getTargetDecl(); |
| 934 | std::string TargetDeclName = TargetDecl->getQualifiedNameAsString(); |
| 935 | // FIXME: check if target_decl_name is in moved ns, which doesn't make much |
| 936 | // sense. If this happens, we need to use name with the new namespace. |
| 937 | // Use fully qualified name in UsingDecl for now. |
| 938 | addReplacementOrDie(Start, End, ReplacementText: "using ::" + TargetDeclName, |
| 939 | SM: *Result.SourceManager, FileToReplacements: &FileToReplacements); |
| 940 | } |
| 941 | |
| 942 | void ChangeNamespaceTool::fixDeclRefExpr( |
| 943 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 944 | const DeclContext *UseContext, const NamedDecl *From, |
| 945 | const DeclRefExpr *Ref) { |
| 946 | SourceRange RefRange = Ref->getSourceRange(); |
| 947 | replaceQualifiedSymbolInDeclContext(Result, DeclCtx: UseContext, Start: RefRange.getBegin(), |
| 948 | End: RefRange.getEnd(), FromDecl: From); |
| 949 | } |
| 950 | |
| 951 | void ChangeNamespaceTool::onEndOfTranslationUnit() { |
| 952 | // Move namespace blocks and insert forward declaration to old namespace. |
| 953 | for (const auto &FileAndNsMoves : MoveNamespaces) { |
| 954 | auto &NsMoves = FileAndNsMoves.second; |
| 955 | if (NsMoves.empty()) |
| 956 | continue; |
| 957 | const std::string &FilePath = FileAndNsMoves.first; |
| 958 | auto &Replaces = FileToReplacements[FilePath]; |
| 959 | auto &SM = *NsMoves.begin()->SourceMgr; |
| 960 | llvm::StringRef Code = SM.getBufferData(FID: NsMoves.begin()->FID); |
| 961 | auto ChangedCode = tooling::applyAllReplacements(Code, Replaces); |
| 962 | if (!ChangedCode) { |
| 963 | llvm::errs() << llvm::toString(E: ChangedCode.takeError()) << "\n" ; |
| 964 | continue; |
| 965 | } |
| 966 | // Replacements on the changed code for moving namespaces and inserting |
| 967 | // forward declarations to old namespaces. |
| 968 | tooling::Replacements NewReplacements; |
| 969 | // Cut the changed code from the old namespace and paste the code in the new |
| 970 | // namespace. |
| 971 | for (const auto &NsMove : NsMoves) { |
| 972 | // Calculate the range of the old namespace block in the changed |
| 973 | // code. |
| 974 | const unsigned NewOffset = Replaces.getShiftedCodePosition(Position: NsMove.Offset); |
| 975 | const unsigned NewLength = |
| 976 | Replaces.getShiftedCodePosition(Position: NsMove.Offset + NsMove.Length) - |
| 977 | NewOffset; |
| 978 | tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "" ); |
| 979 | std::string MovedCode = ChangedCode->substr(pos: NewOffset, n: NewLength); |
| 980 | std::string MovedCodeWrappedInNewNs = |
| 981 | wrapCodeInNamespace(NestedNs: DiffNewNamespace, Code: MovedCode); |
| 982 | // Calculate the new offset at which the code will be inserted in the |
| 983 | // changed code. |
| 984 | unsigned NewInsertionOffset = |
| 985 | Replaces.getShiftedCodePosition(Position: NsMove.InsertionOffset); |
| 986 | tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0, |
| 987 | MovedCodeWrappedInNewNs); |
| 988 | addOrMergeReplacement(R: Deletion, Replaces: &NewReplacements); |
| 989 | addOrMergeReplacement(R: Insertion, Replaces: &NewReplacements); |
| 990 | } |
| 991 | // After moving namespaces, insert forward declarations back to old |
| 992 | // namespaces. |
| 993 | const auto &FwdDeclInsertions = InsertFwdDecls[FilePath]; |
| 994 | for (const auto &FwdDeclInsertion : FwdDeclInsertions) { |
| 995 | unsigned NewInsertionOffset = |
| 996 | Replaces.getShiftedCodePosition(Position: FwdDeclInsertion.InsertionOffset); |
| 997 | tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0, |
| 998 | FwdDeclInsertion.ForwardDeclText); |
| 999 | addOrMergeReplacement(R: Insertion, Replaces: &NewReplacements); |
| 1000 | } |
| 1001 | // Add replacements referring to the changed code to existing replacements, |
| 1002 | // which refers to the original code. |
| 1003 | Replaces = Replaces.merge(Replaces: NewReplacements); |
| 1004 | auto Style = |
| 1005 | format::getStyle(StyleName: format::DefaultFormatStyle, FileName: FilePath, FallbackStyle); |
| 1006 | if (!Style) { |
| 1007 | llvm::errs() << llvm::toString(E: Style.takeError()) << "\n" ; |
| 1008 | continue; |
| 1009 | } |
| 1010 | // Clean up old namespaces if there is nothing in it after moving. |
| 1011 | auto CleanReplacements = |
| 1012 | format::cleanupAroundReplacements(Code, Replaces, Style: *Style); |
| 1013 | if (!CleanReplacements) { |
| 1014 | llvm::errs() << llvm::toString(E: CleanReplacements.takeError()) << "\n" ; |
| 1015 | continue; |
| 1016 | } |
| 1017 | FileToReplacements[FilePath] = *CleanReplacements; |
| 1018 | } |
| 1019 | |
| 1020 | // Make sure we don't generate replacements for files that do not match |
| 1021 | // FilePattern. |
| 1022 | for (auto &Entry : FileToReplacements) |
| 1023 | if (!FilePatternRE.match(String: Entry.first)) |
| 1024 | Entry.second.clear(); |
| 1025 | } |
| 1026 | |
| 1027 | } // namespace change_namespace |
| 1028 | } // namespace clang |
| 1029 | |