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