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 | bc71550 | 2017-01-26 15:08:44 | [diff] [blame] | 199 | // Note that if `DeclName` is `::b::X` and `NsName` is `::a::b`, this returns |
| 200 | // "::b::X" instead of "b::X" since there will be a name conflict otherwise. |
Eric Liu | 447164d | 2016-10-05 15:52:39 | [diff] [blame] | 201 | // \param DeclName A fully qualified name, "::a::b::X" or "a::b::X". |
| 202 | // \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace |
| 203 | // will have empty name. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 204 | std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName, |
| 205 | llvm::StringRef NsName) { |
Eric Liu | 447164d | 2016-10-05 15:52:39 | [diff] [blame] | 206 | DeclName = DeclName.ltrim(':'); |
| 207 | NsName = NsName.ltrim(':'); |
Eric Liu | 447164d | 2016-10-05 15:52:39 | [diff] [blame] | 208 | if (DeclName.find(':') == llvm::StringRef::npos) |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 209 | return DeclName; |
Eric Liu | 447164d | 2016-10-05 15:52:39 | [diff] [blame] | 210 | |
Eric Liu | bc71550 | 2017-01-26 15:08:44 | [diff] [blame] | 211 | llvm::SmallVector<llvm::StringRef, 4> NsNameSplitted; |
| 212 | NsName.split(NsNameSplitted, "::", /*MaxSplit=*/-1, |
| 213 | /*KeepEmpty=*/false); |
| 214 | llvm::SmallVector<llvm::StringRef, 4> DeclNsSplitted; |
| 215 | DeclName.split(DeclNsSplitted, "::", /*MaxSplit=*/-1, |
| 216 | /*KeepEmpty=*/false); |
| 217 | llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val(); |
| 218 | // If the Decl is in global namespace, there is no need to shorten it. |
| 219 | if (DeclNsSplitted.empty()) |
| 220 | return UnqualifiedDeclName; |
| 221 | // If NsName is the global namespace, we can simply use the DeclName sans |
| 222 | // leading "::". |
| 223 | if (NsNameSplitted.empty()) |
| 224 | return DeclName; |
| 225 | |
| 226 | if (NsNameSplitted.front() != DeclNsSplitted.front()) { |
| 227 | // The DeclName must be fully-qualified, but we still need to decide if a |
| 228 | // leading "::" is necessary. For example, if `NsName` is "a::b::c" and the |
| 229 | // `DeclName` is "b::X", then the reference must be qualified as "::b::X" |
| 230 | // to avoid conflict. |
| 231 | if (llvm::is_contained(NsNameSplitted, DeclNsSplitted.front())) |
| 232 | return ("::" + DeclName).str(); |
| 233 | return DeclName; |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 234 | } |
Eric Liu | bc71550 | 2017-01-26 15:08:44 | [diff] [blame] | 235 | // Since there is already an overlap namespace, we know that `DeclName` can be |
| 236 | // shortened, so we reduce the longest common prefix. |
| 237 | auto DeclI = DeclNsSplitted.begin(); |
| 238 | auto DeclE = DeclNsSplitted.end(); |
| 239 | auto NsI = NsNameSplitted.begin(); |
| 240 | auto NsE = NsNameSplitted.end(); |
| 241 | for (; DeclI != DeclE && NsI != NsE && *DeclI == *NsI; ++DeclI, ++NsI) { |
| 242 | } |
| 243 | return (DeclI == DeclE) |
| 244 | ? UnqualifiedDeclName.str() |
| 245 | : (llvm::join(DeclI, DeclE, "::") + "::" + UnqualifiedDeclName) |
| 246 | .str(); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 247 | } |
| 248 | |
| 249 | std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) { |
| 250 | if (Code.back() != '\n') |
| 251 | Code += "\n"; |
| 252 | llvm::SmallVector<StringRef, 4> NsSplitted; |
Eric Liu | 2dd0e1b | 2016-12-05 11:17:04 | [diff] [blame] | 253 | NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1, |
| 254 | /*KeepEmpty=*/false); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 255 | while (!NsSplitted.empty()) { |
| 256 | // FIXME: consider code style for comments. |
| 257 | Code = ("namespace " + NsSplitted.back() + " {\n" + Code + |
| 258 | "} // namespace " + NsSplitted.back() + "\n") |
| 259 | .str(); |
| 260 | NsSplitted.pop_back(); |
| 261 | } |
| 262 | return Code; |
| 263 | } |
| 264 | |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 265 | // Returns true if \p D is a nested DeclContext in \p Context |
| 266 | bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) { |
| 267 | while (D) { |
| 268 | if (D == Context) |
| 269 | return true; |
| 270 | D = D->getParent(); |
| 271 | } |
| 272 | return false; |
| 273 | } |
| 274 | |
| 275 | // Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx. |
| 276 | bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D, |
| 277 | const DeclContext *DeclCtx, SourceLocation Loc) { |
Eric Liu | a13c419 | 2017-02-13 17:24:14 | [diff] [blame] | 278 | SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocStart()); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 279 | Loc = SM.getSpellingLoc(Loc); |
| 280 | return SM.isBeforeInTranslationUnit(DeclLoc, Loc) && |
| 281 | (SM.getFileID(DeclLoc) == SM.getFileID(Loc) && |
| 282 | isNestedDeclContext(DeclCtx, D->getDeclContext())); |
| 283 | } |
| 284 | |
Eric Liu | 0325a77 | 2017-02-02 17:40:38 | [diff] [blame] | 285 | AST_MATCHER(EnumDecl, isScoped) { |
| 286 | return Node.isScoped(); |
| 287 | } |
| 288 | |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 289 | } // anonymous namespace |
| 290 | |
| 291 | ChangeNamespaceTool::ChangeNamespaceTool( |
| 292 | llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern, |
Eric Liu | 7fccc99 | 2017-02-24 11:54:45 | [diff] [blame^] | 293 | llvm::ArrayRef<std::string> WhiteListedSymbolPatterns, |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 294 | std::map<std::string, tooling::Replacements> *FileToReplacements, |
| 295 | llvm::StringRef FallbackStyle) |
| 296 | : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements), |
| 297 | OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')), |
Eric Liu | c265b02 | 2016-12-01 17:25:55 | [diff] [blame] | 298 | FilePattern(FilePattern), FilePatternRE(FilePattern) { |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 299 | FileToReplacements->clear(); |
| 300 | llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted; |
| 301 | llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted; |
| 302 | llvm::StringRef(OldNamespace).split(OldNsSplitted, "::"); |
| 303 | llvm::StringRef(NewNamespace).split(NewNsSplitted, "::"); |
| 304 | // Calculates `DiffOldNamespace` and `DiffNewNamespace`. |
| 305 | while (!OldNsSplitted.empty() && !NewNsSplitted.empty() && |
| 306 | OldNsSplitted.front() == NewNsSplitted.front()) { |
| 307 | OldNsSplitted.erase(OldNsSplitted.begin()); |
| 308 | NewNsSplitted.erase(NewNsSplitted.begin()); |
| 309 | } |
| 310 | DiffOldNamespace = joinNamespaces(OldNsSplitted); |
| 311 | DiffNewNamespace = joinNamespaces(NewNsSplitted); |
Eric Liu | 7fccc99 | 2017-02-24 11:54:45 | [diff] [blame^] | 312 | |
| 313 | for (const auto &Pattern : WhiteListedSymbolPatterns) |
| 314 | WhiteListedSymbolRegexes.emplace_back(Pattern); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 315 | } |
| 316 | |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 317 | void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 318 | std::string FullOldNs = "::" + OldNamespace; |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 319 | // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the |
| 320 | // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will |
| 321 | // be "a::b". Declarations in this namespace will not be visible in the new |
| 322 | // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-". |
| 323 | llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted; |
Eric Liu | 2dd0e1b | 2016-12-05 11:17:04 | [diff] [blame] | 324 | llvm::StringRef(DiffOldNamespace) |
| 325 | .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1, |
| 326 | /*KeepEmpty=*/false); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 327 | std::string Prefix = "-"; |
| 328 | if (!DiffOldNsSplitted.empty()) |
| 329 | Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) + |
| 330 | DiffOldNsSplitted.front()) |
| 331 | .str(); |
| 332 | auto IsInMovedNs = |
| 333 | allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")), |
| 334 | isExpansionInFileMatching(FilePattern)); |
| 335 | auto IsVisibleInNewNs = anyOf( |
| 336 | IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix))))); |
| 337 | // Match using declarations. |
| 338 | Finder->addMatcher( |
| 339 | usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs) |
| 340 | .bind("using"), |
| 341 | this); |
| 342 | // Match using namespace declarations. |
| 343 | Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern), |
| 344 | IsVisibleInNewNs) |
| 345 | .bind("using_namespace"), |
| 346 | this); |
Eric Liu | 180dac6 | 2016-12-23 10:47:09 | [diff] [blame] | 347 | // Match namespace alias declarations. |
| 348 | Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern), |
| 349 | IsVisibleInNewNs) |
| 350 | .bind("namespace_alias"), |
| 351 | this); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 352 | |
| 353 | // Match old namespace blocks. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 354 | Finder->addMatcher( |
| 355 | namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern)) |
| 356 | .bind("old_ns"), |
| 357 | this); |
| 358 | |
Eric Liu | 41552d6 | 2016-12-07 14:20:52 | [diff] [blame] | 359 | // Match class forward-declarations in the old namespace. |
| 360 | // Note that forward-declarations in classes are not matched. |
| 361 | Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), |
| 362 | IsInMovedNs, hasParent(namespaceDecl())) |
| 363 | .bind("class_fwd_decl"), |
| 364 | this); |
| 365 | |
| 366 | // Match template class forward-declarations in the old namespace. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 367 | Finder->addMatcher( |
Eric Liu | 41552d6 | 2016-12-07 14:20:52 | [diff] [blame] | 368 | classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))), |
| 369 | IsInMovedNs, hasParent(namespaceDecl())) |
| 370 | .bind("template_class_fwd_decl"), |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 371 | this); |
| 372 | |
| 373 | // Match references to types that are not defined in the old namespace. |
| 374 | // Forward-declarations in the old namespace are also matched since they will |
| 375 | // be moved back to the old namespace. |
| 376 | auto DeclMatcher = namedDecl( |
| 377 | hasAncestor(namespaceDecl()), |
| 378 | unless(anyOf( |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 379 | isImplicit(), hasAncestor(namespaceDecl(isAnonymous())), |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 380 | hasAncestor(cxxRecordDecl()), |
| 381 | allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition()))))))); |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 382 | |
Eric Liu | 8685c76 | 2016-12-07 17:04:07 | [diff] [blame] | 383 | // Using shadow declarations in classes always refers to base class, which |
| 384 | // does not need to be qualified since it can be inferred from inheritance. |
| 385 | // Note that this does not match using alias declarations. |
| 386 | auto UsingShadowDeclInClass = |
| 387 | usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl())); |
| 388 | |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 389 | // Match TypeLocs on the declaration. Carefully match only the outermost |
Eric Liu | 8393cb0 | 2016-10-31 08:28:29 | [diff] [blame] | 390 | // TypeLoc and template specialization arguments (which are not outermost) |
| 391 | // that are directly linked to types matching `DeclMatcher`. Nested name |
| 392 | // specifier locs are handled separately below. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 393 | Finder->addMatcher( |
| 394 | typeLoc(IsInMovedNs, |
| 395 | loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))), |
Eric Liu | 8393cb0 | 2016-10-31 08:28:29 | [diff] [blame] | 396 | unless(anyOf(hasParent(typeLoc(loc(qualType( |
| 397 | allOf(hasDeclaration(DeclMatcher), |
| 398 | unless(templateSpecializationType())))))), |
Eric Liu | 8685c76 | 2016-12-07 17:04:07 | [diff] [blame] | 399 | hasParent(nestedNameSpecifierLoc()), |
| 400 | hasAncestor(isImplicit()), |
| 401 | hasAncestor(UsingShadowDeclInClass))), |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 402 | hasAncestor(decl().bind("dc"))) |
| 403 | .bind("type"), |
| 404 | this); |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 405 | |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 406 | // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to |
| 407 | // special case it. |
Eric Liu | 8685c76 | 2016-12-07 17:04:07 | [diff] [blame] | 408 | // Since using declarations inside classes must have the base class in the |
| 409 | // nested name specifier, we leave it to the nested name specifier matcher. |
| 410 | Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()), |
| 411 | unless(UsingShadowDeclInClass)) |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 412 | .bind("using_with_shadow"), |
| 413 | this); |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 414 | |
Eric Liu | ff51f01 | 2016-11-16 16:54:53 | [diff] [blame] | 415 | // Handle types in nested name specifier. Specifiers that are in a TypeLoc |
| 416 | // matched above are not matched, e.g. "A::" in "A::A" is not matched since |
| 417 | // "A::A" would have already been fixed. |
Eric Liu | 8685c76 | 2016-12-07 17:04:07 | [diff] [blame] | 418 | Finder->addMatcher( |
| 419 | nestedNameSpecifierLoc( |
| 420 | hasAncestor(decl(IsInMovedNs).bind("dc")), |
| 421 | loc(nestedNameSpecifier( |
| 422 | specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))), |
| 423 | unless(anyOf(hasAncestor(isImplicit()), |
| 424 | hasAncestor(UsingShadowDeclInClass), |
| 425 | hasAncestor(typeLoc(loc(qualType(hasDeclaration( |
| 426 | decl(equalsBoundNode("from_decl")))))))))) |
| 427 | .bind("nested_specifier_loc"), |
| 428 | this); |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 429 | |
Eric Liu | ff51f01 | 2016-11-16 16:54:53 | [diff] [blame] | 430 | // Matches base class initializers in constructors. TypeLocs of base class |
| 431 | // initializers do not need to be fixed. For example, |
| 432 | // class X : public a::b::Y { |
| 433 | // public: |
| 434 | // X() : Y::Y() {} // Y::Y do not need namespace specifier. |
| 435 | // }; |
| 436 | Finder->addMatcher( |
| 437 | cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this); |
| 438 | |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 439 | // Handle function. |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 440 | // Only handle functions that are defined in a namespace excluding member |
| 441 | // function, static methods (qualified by nested specifier), and functions |
| 442 | // defined in the global namespace. |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 443 | // Note that the matcher does not exclude calls to out-of-line static method |
| 444 | // definitions, so we need to exclude them in the callback handler. |
Eric Liu | 912d039 | 2016-09-27 12:54:48 | [diff] [blame] | 445 | auto FuncMatcher = |
| 446 | functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs, |
| 447 | hasAncestor(namespaceDecl(isAnonymous())), |
| 448 | hasAncestor(cxxRecordDecl()))), |
| 449 | hasParent(namespaceDecl())); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 450 | Finder->addMatcher(decl(forEachDescendant(expr(anyOf( |
| 451 | callExpr(callee(FuncMatcher)).bind("call"), |
| 452 | declRefExpr(to(FuncMatcher.bind("func_decl"))) |
| 453 | .bind("func_ref")))), |
| 454 | IsInMovedNs, unless(isImplicit())) |
| 455 | .bind("dc"), |
| 456 | this); |
Eric Liu | 159f013 | 2016-09-30 04:32:39 | [diff] [blame] | 457 | |
| 458 | auto GlobalVarMatcher = varDecl( |
| 459 | hasGlobalStorage(), hasParent(namespaceDecl()), |
| 460 | unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous()))))); |
| 461 | Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")), |
| 462 | to(GlobalVarMatcher.bind("var_decl"))) |
| 463 | .bind("var_ref"), |
| 464 | this); |
Eric Liu | 0325a77 | 2017-02-02 17:40:38 | [diff] [blame] | 465 | |
| 466 | // Handle unscoped enum constant. |
| 467 | auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl( |
| 468 | hasParent(namespaceDecl()), |
| 469 | unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()), |
| 470 | hasAncestor(namespaceDecl(isAnonymous()))))))); |
| 471 | Finder->addMatcher( |
| 472 | declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")), |
| 473 | to(UnscopedEnumMatcher.bind("enum_const_decl"))) |
| 474 | .bind("enum_const_ref"), |
| 475 | this); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 476 | } |
| 477 | |
| 478 | void ChangeNamespaceTool::run( |
| 479 | const ast_matchers::MatchFinder::MatchResult &Result) { |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 480 | if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) { |
| 481 | UsingDecls.insert(Using); |
| 482 | } else if (const auto *UsingNamespace = |
| 483 | Result.Nodes.getNodeAs<UsingDirectiveDecl>( |
| 484 | "using_namespace")) { |
| 485 | UsingNamespaceDecls.insert(UsingNamespace); |
Eric Liu | 180dac6 | 2016-12-23 10:47:09 | [diff] [blame] | 486 | } else if (const auto *NamespaceAlias = |
| 487 | Result.Nodes.getNodeAs<NamespaceAliasDecl>( |
| 488 | "namespace_alias")) { |
| 489 | NamespaceAliasDecls.insert(NamespaceAlias); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 490 | } else if (const auto *NsDecl = |
| 491 | Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) { |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 492 | moveOldNamespace(Result, NsDecl); |
| 493 | } else if (const auto *FwdDecl = |
Eric Liu | 41552d6 | 2016-12-07 14:20:52 | [diff] [blame] | 494 | Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) { |
| 495 | moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl)); |
| 496 | } else if (const auto *TemplateFwdDecl = |
| 497 | Result.Nodes.getNodeAs<ClassTemplateDecl>( |
| 498 | "template_class_fwd_decl")) { |
| 499 | moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl)); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 500 | } else if (const auto *UsingWithShadow = |
| 501 | Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) { |
| 502 | fixUsingShadowDecl(Result, UsingWithShadow); |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 503 | } else if (const auto *Specifier = |
| 504 | Result.Nodes.getNodeAs<NestedNameSpecifierLoc>( |
| 505 | "nested_specifier_loc")) { |
| 506 | SourceLocation Start = Specifier->getBeginLoc(); |
Eric Liu | c265b02 | 2016-12-01 17:25:55 | [diff] [blame] | 507 | SourceLocation End = endLocationForType(Specifier->getTypeLoc()); |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 508 | fixTypeLoc(Result, Start, End, Specifier->getTypeLoc()); |
Eric Liu | ff51f01 | 2016-11-16 16:54:53 | [diff] [blame] | 509 | } else if (const auto *BaseInitializer = |
| 510 | Result.Nodes.getNodeAs<CXXCtorInitializer>( |
| 511 | "base_initializer")) { |
| 512 | BaseCtorInitializerTypeLocs.push_back( |
| 513 | BaseInitializer->getTypeSourceInfo()->getTypeLoc()); |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 514 | } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) { |
Eric Liu | 26cf68a | 2016-12-15 10:42:35 | [diff] [blame] | 515 | // This avoids fixing types with record types as qualifier, which is not |
| 516 | // filtered by matchers in some cases, e.g. the type is templated. We should |
| 517 | // handle the record type qualifier instead. |
Eric Liu | 0c0aea0 | 2016-12-15 13:02:41 | [diff] [blame] | 518 | TypeLoc Loc = *TLoc; |
| 519 | while (Loc.getTypeLocClass() == TypeLoc::Qualified) |
| 520 | Loc = Loc.getNextTypeLoc(); |
| 521 | if (Loc.getTypeLocClass() == TypeLoc::Elaborated) { |
Eric Liu | 26cf68a | 2016-12-15 10:42:35 | [diff] [blame] | 522 | NestedNameSpecifierLoc NestedNameSpecifier = |
Eric Liu | 0c0aea0 | 2016-12-15 13:02:41 | [diff] [blame] | 523 | Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc(); |
Eric Liu | 26cf68a | 2016-12-15 10:42:35 | [diff] [blame] | 524 | const Type *SpecifierType = |
| 525 | NestedNameSpecifier.getNestedNameSpecifier()->getAsType(); |
| 526 | if (SpecifierType && SpecifierType->isRecordType()) |
| 527 | return; |
| 528 | } |
Eric Liu | 0c0aea0 | 2016-12-15 13:02:41 | [diff] [blame] | 529 | fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 | [diff] [blame] | 530 | } else if (const auto *VarRef = |
| 531 | Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) { |
Eric Liu | 159f013 | 2016-09-30 04:32:39 | [diff] [blame] | 532 | const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl"); |
| 533 | assert(Var); |
| 534 | if (Var->getCanonicalDecl()->isStaticDataMember()) |
| 535 | return; |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 536 | const auto *Context = Result.Nodes.getNodeAs<Decl>("dc"); |
Eric Liu | 159f013 | 2016-09-30 04:32:39 | [diff] [blame] | 537 | assert(Context && "Empty decl context."); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 538 | fixDeclRefExpr(Result, Context->getDeclContext(), |
| 539 | llvm::cast<NamedDecl>(Var), VarRef); |
Eric Liu | 0325a77 | 2017-02-02 17:40:38 | [diff] [blame] | 540 | } else if (const auto *EnumConstRef = |
| 541 | Result.Nodes.getNodeAs<DeclRefExpr>("enum_const_ref")) { |
| 542 | // Do not rename the reference if it is already scoped by the EnumDecl name. |
| 543 | if (EnumConstRef->hasQualifier() && |
Eric Liu | 28c30ce | 2017-02-02 19:46:12 | [diff] [blame] | 544 | EnumConstRef->getQualifier()->getKind() == |
| 545 | NestedNameSpecifier::SpecifierKind::TypeSpec && |
Eric Liu | 0325a77 | 2017-02-02 17:40:38 | [diff] [blame] | 546 | EnumConstRef->getQualifier()->getAsType()->isEnumeralType()) |
| 547 | return; |
| 548 | const auto *EnumConstDecl = |
| 549 | Result.Nodes.getNodeAs<EnumConstantDecl>("enum_const_decl"); |
| 550 | assert(EnumConstDecl); |
| 551 | const auto *Context = Result.Nodes.getNodeAs<Decl>("dc"); |
| 552 | assert(Context && "Empty decl context."); |
| 553 | // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it |
| 554 | // if it turns out to be an issue. |
| 555 | fixDeclRefExpr(Result, Context->getDeclContext(), |
| 556 | llvm::cast<NamedDecl>(EnumConstDecl), EnumConstRef); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 557 | } else if (const auto *FuncRef = |
| 558 | Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) { |
Eric Liu | e3f35e4 | 2016-12-20 14:39:04 | [diff] [blame] | 559 | // If this reference has been processed as a function call, we do not |
| 560 | // process it again. |
| 561 | if (ProcessedFuncRefs.count(FuncRef)) |
| 562 | return; |
| 563 | ProcessedFuncRefs.insert(FuncRef); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 564 | const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl"); |
| 565 | assert(Func); |
| 566 | const auto *Context = Result.Nodes.getNodeAs<Decl>("dc"); |
| 567 | assert(Context && "Empty decl context."); |
| 568 | fixDeclRefExpr(Result, Context->getDeclContext(), |
| 569 | llvm::cast<NamedDecl>(Func), FuncRef); |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 570 | } else { |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 571 | const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 | [diff] [blame] | 572 | assert(Call != nullptr && "Expecting callback for CallExpr."); |
Eric Liu | e3f35e4 | 2016-12-20 14:39:04 | [diff] [blame] | 573 | const auto *CalleeFuncRef = |
| 574 | llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()); |
| 575 | ProcessedFuncRefs.insert(CalleeFuncRef); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 576 | const FunctionDecl *Func = Call->getDirectCallee(); |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 577 | assert(Func != nullptr); |
Eric Liu | e3f35e4 | 2016-12-20 14:39:04 | [diff] [blame] | 578 | // FIXME: ignore overloaded operators. This would miss cases where operators |
| 579 | // are called by qualified names (i.e. "ns::operator <"). Ignore such |
| 580 | // cases for now. |
| 581 | if (Func->isOverloadedOperator()) |
| 582 | return; |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 583 | // Ignore out-of-line static methods since they will be handled by nested |
| 584 | // name specifiers. |
| 585 | if (Func->getCanonicalDecl()->getStorageClass() == |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 586 | StorageClass::SC_Static && |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 587 | Func->isOutOfLine()) |
| 588 | return; |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 589 | const auto *Context = Result.Nodes.getNodeAs<Decl>("dc"); |
Eric Liu | 12068d8 | 2016-09-22 11:54:00 | [diff] [blame] | 590 | assert(Context && "Empty decl context."); |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 591 | SourceRange CalleeRange = Call->getCallee()->getSourceRange(); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 592 | replaceQualifiedSymbolInDeclContext( |
| 593 | Result, Context->getDeclContext(), CalleeRange.getBegin(), |
Eric Liu | 231c655 | 2016-11-10 18:15:34 | [diff] [blame] | 594 | CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func)); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 595 | } |
| 596 | } |
| 597 | |
Eric Liu | 73f49fd | 2016-10-12 12:34:18 | [diff] [blame] | 598 | static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl, |
| 599 | const SourceManager &SM, |
| 600 | const LangOptions &LangOpts) { |
| 601 | std::unique_ptr<Lexer> Lex = |
| 602 | getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts); |
| 603 | assert(Lex.get() && |
| 604 | "Failed to create lexer from the beginning of namespace."); |
| 605 | if (!Lex.get()) |
| 606 | return SourceLocation(); |
| 607 | Token Tok; |
| 608 | while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) { |
| 609 | } |
| 610 | return Tok.isNot(tok::TokenKind::l_brace) |
| 611 | ? SourceLocation() |
| 612 | : Tok.getEndLoc().getLocWithOffset(1); |
| 613 | } |
| 614 | |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 615 | // Stores information about a moved namespace in `MoveNamespaces` and leaves |
| 616 | // the actual movement to `onEndOfTranslationUnit()`. |
| 617 | void ChangeNamespaceTool::moveOldNamespace( |
| 618 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 619 | const NamespaceDecl *NsDecl) { |
| 620 | // If the namespace is empty, do nothing. |
| 621 | if (Decl::castToDeclContext(NsDecl)->decls_empty()) |
| 622 | return; |
| 623 | |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 624 | const SourceManager &SM = *Result.SourceManager; |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 625 | // Get the range of the code in the old namespace. |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 626 | SourceLocation Start = |
| 627 | getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts()); |
Eric Liu | 73f49fd | 2016-10-12 12:34:18 | [diff] [blame] | 628 | assert(Start.isValid() && "Can't find l_brace for namespace."); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 629 | MoveNamespace MoveNs; |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 630 | MoveNs.Offset = SM.getFileOffset(Start); |
| 631 | // The range of the moved namespace is from the location just past the left |
| 632 | // brace to the location right before the right brace. |
| 633 | MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset; |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 634 | |
| 635 | // Insert the new namespace after `DiffOldNamespace`. For example, if |
| 636 | // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then |
| 637 | // "x::y" will be inserted inside the existing namespace "a" and after "a::b". |
| 638 | // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b" |
| 639 | // in the above example. |
Eric Liu | 6aa9416 | 2016-11-10 18:29:01 | [diff] [blame] | 640 | // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new |
| 641 | // namespace will be a nested namespace in the old namespace. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 642 | const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace); |
Eric Liu | 6aa9416 | 2016-11-10 18:29:01 | [diff] [blame] | 643 | SourceLocation InsertionLoc = Start; |
| 644 | if (OuterNs) { |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 645 | SourceLocation LocAfterNs = getStartOfNextLine( |
| 646 | OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts()); |
Eric Liu | 6aa9416 | 2016-11-10 18:29:01 | [diff] [blame] | 647 | assert(LocAfterNs.isValid() && |
| 648 | "Failed to get location after DiffOldNamespace"); |
| 649 | InsertionLoc = LocAfterNs; |
| 650 | } |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 651 | MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc)); |
| 652 | MoveNs.FID = SM.getFileID(Start); |
Eric Liu | cc83c66 | 2016-09-19 17:58:59 | [diff] [blame] | 653 | MoveNs.SourceMgr = Result.SourceManager; |
Eric Liu | ee5104b | 2017-01-04 14:49:08 | [diff] [blame] | 654 | MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 655 | } |
| 656 | |
| 657 | // Removes a class forward declaration from the code in the moved namespace and |
| 658 | // creates an `InsertForwardDeclaration` to insert the forward declaration back |
| 659 | // into the old namespace after moving code from the old namespace to the new |
| 660 | // namespace. |
| 661 | // For example, changing "a" to "x": |
| 662 | // Old code: |
| 663 | // namespace a { |
| 664 | // class FWD; |
| 665 | // class A { FWD *fwd; } |
| 666 | // } // a |
| 667 | // New code: |
| 668 | // namespace a { |
| 669 | // class FWD; |
| 670 | // } // a |
| 671 | // namespace x { |
| 672 | // class A { a::FWD *fwd; } |
| 673 | // } // x |
| 674 | void ChangeNamespaceTool::moveClassForwardDeclaration( |
| 675 | const ast_matchers::MatchFinder::MatchResult &Result, |
Eric Liu | 41552d6 | 2016-12-07 14:20:52 | [diff] [blame] | 676 | const NamedDecl *FwdDecl) { |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 677 | SourceLocation Start = FwdDecl->getLocStart(); |
| 678 | SourceLocation End = FwdDecl->getLocEnd(); |
| 679 | SourceLocation AfterSemi = Lexer::findLocationAfterToken( |
| 680 | End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(), |
| 681 | /*SkipTrailingWhitespaceAndNewLine=*/true); |
| 682 | if (AfterSemi.isValid()) |
| 683 | End = AfterSemi.getLocWithOffset(-1); |
| 684 | // Delete the forward declaration from the code to be moved. |
Eric Liu | 4fe99e1 | 2016-12-14 17:01:52 | [diff] [blame] | 685 | addReplacementOrDie(Start, End, "", *Result.SourceManager, |
| 686 | &FileToReplacements); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 687 | llvm::StringRef Code = Lexer::getSourceText( |
| 688 | CharSourceRange::getTokenRange( |
| 689 | Result.SourceManager->getSpellingLoc(Start), |
| 690 | Result.SourceManager->getSpellingLoc(End)), |
| 691 | *Result.SourceManager, Result.Context->getLangOpts()); |
| 692 | // Insert the forward declaration back into the old namespace after moving the |
| 693 | // code from old namespace to new namespace. |
| 694 | // Insertion information is stored in `InsertFwdDecls` and actual |
| 695 | // insertion will be performed in `onEndOfTranslationUnit`. |
| 696 | // Get the (old) namespace that contains the forward declaration. |
| 697 | const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl"); |
| 698 | // The namespace contains the forward declaration, so it must not be empty. |
| 699 | assert(!NsDecl->decls_empty()); |
| 700 | const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(), |
| 701 | Code, *Result.SourceManager); |
| 702 | InsertForwardDeclaration InsertFwd; |
| 703 | InsertFwd.InsertionOffset = Insertion.getOffset(); |
| 704 | InsertFwd.ForwardDeclText = Insertion.getReplacementText().str(); |
| 705 | InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd); |
| 706 | } |
| 707 | |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 708 | // Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p |
| 709 | // FromDecl with the shortest qualified name possible when the reference is in |
| 710 | // `NewNamespace`. |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 711 | void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext( |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 712 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 713 | const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End, |
| 714 | const NamedDecl *FromDecl) { |
| 715 | const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext(); |
Eric Liu | 4fe99e1 | 2016-12-14 17:01:52 | [diff] [blame] | 716 | if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) { |
| 717 | // This should not happen in usual unless the TypeLoc is in function type |
| 718 | // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of |
| 719 | // `T` will be the translation unit. We simply use fully-qualified name |
| 720 | // here. |
| 721 | // Note that `FromDecl` must not be defined in the old namespace (according |
| 722 | // to `DeclMatcher`), so its fully-qualified name will not change after |
| 723 | // changing the namespace. |
| 724 | addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(), |
| 725 | *Result.SourceManager, &FileToReplacements); |
| 726 | return; |
| 727 | } |
Eric Liu | 231c655 | 2016-11-10 18:15:34 | [diff] [blame] | 728 | const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 729 | // Calculate the name of the `NsDecl` after it is moved to new namespace. |
| 730 | std::string OldNs = NsDecl->getQualifiedNameAsString(); |
| 731 | llvm::StringRef Postfix = OldNs; |
| 732 | bool Consumed = Postfix.consume_front(OldNamespace); |
| 733 | assert(Consumed && "Expect OldNS to start with OldNamespace."); |
| 734 | (void)Consumed; |
| 735 | const std::string NewNs = (NewNamespace + Postfix).str(); |
| 736 | |
| 737 | llvm::StringRef NestedName = Lexer::getSourceText( |
| 738 | CharSourceRange::getTokenRange( |
| 739 | Result.SourceManager->getSpellingLoc(Start), |
| 740 | Result.SourceManager->getSpellingLoc(End)), |
| 741 | *Result.SourceManager, Result.Context->getLangOpts()); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 742 | std::string FromDeclName = FromDecl->getQualifiedNameAsString(); |
Eric Liu | 7fccc99 | 2017-02-24 11:54:45 | [diff] [blame^] | 743 | for (llvm::Regex &RE : WhiteListedSymbolRegexes) |
| 744 | if (RE.match(FromDeclName)) |
| 745 | return; |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 746 | std::string ReplaceName = |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 747 | getShortestQualifiedNameInNamespace(FromDeclName, NewNs); |
| 748 | // Checks if there is any using namespace declarations that can shorten the |
| 749 | // qualified name. |
| 750 | for (const auto *UsingNamespace : UsingNamespaceDecls) { |
| 751 | if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx, |
| 752 | Start)) |
| 753 | continue; |
| 754 | StringRef FromDeclNameRef = FromDeclName; |
| 755 | if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace() |
| 756 | ->getQualifiedNameAsString())) { |
| 757 | FromDeclNameRef = FromDeclNameRef.drop_front(2); |
| 758 | if (FromDeclNameRef.size() < ReplaceName.size()) |
| 759 | ReplaceName = FromDeclNameRef; |
| 760 | } |
| 761 | } |
Eric Liu | 180dac6 | 2016-12-23 10:47:09 | [diff] [blame] | 762 | // Checks if there is any namespace alias declarations that can shorten the |
| 763 | // qualified name. |
| 764 | for (const auto *NamespaceAlias : NamespaceAliasDecls) { |
| 765 | if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx, |
| 766 | Start)) |
| 767 | continue; |
| 768 | StringRef FromDeclNameRef = FromDeclName; |
| 769 | if (FromDeclNameRef.consume_front( |
| 770 | NamespaceAlias->getNamespace()->getQualifiedNameAsString() + |
| 771 | "::")) { |
| 772 | std::string AliasName = NamespaceAlias->getNameAsString(); |
| 773 | std::string AliasQualifiedName = |
| 774 | NamespaceAlias->getQualifiedNameAsString(); |
| 775 | // We only consider namespace aliases define in the global namepspace or |
| 776 | // in namespaces that are directly visible from the reference, i.e. |
| 777 | // ancestor of the `OldNs`. Note that declarations in ancestor namespaces |
| 778 | // but not visible in the new namespace is filtered out by |
| 779 | // "IsVisibleInNewNs" matcher. |
| 780 | if (AliasQualifiedName != AliasName) { |
| 781 | // The alias is defined in some namespace. |
| 782 | assert(StringRef(AliasQualifiedName).endswith("::" + AliasName)); |
| 783 | llvm::StringRef AliasNs = |
| 784 | StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2); |
| 785 | if (!llvm::StringRef(OldNs).startswith(AliasNs)) |
| 786 | continue; |
| 787 | } |
| 788 | std::string NameWithAliasNamespace = |
| 789 | (AliasName + "::" + FromDeclNameRef).str(); |
| 790 | if (NameWithAliasNamespace.size() < ReplaceName.size()) |
| 791 | ReplaceName = NameWithAliasNamespace; |
| 792 | } |
| 793 | } |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 794 | // Checks if there is any using shadow declarations that can shorten the |
| 795 | // qualified name. |
| 796 | bool Matched = false; |
| 797 | for (const UsingDecl *Using : UsingDecls) { |
| 798 | if (Matched) |
| 799 | break; |
| 800 | if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) { |
| 801 | for (const auto *UsingShadow : Using->shadows()) { |
| 802 | const auto *TargetDecl = UsingShadow->getTargetDecl(); |
Eric Liu | ae7de71 | 2017-02-02 15:29:54 | [diff] [blame] | 803 | if (TargetDecl->getQualifiedNameAsString() == |
| 804 | FromDecl->getQualifiedNameAsString()) { |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 805 | ReplaceName = FromDecl->getNameAsString(); |
| 806 | Matched = true; |
| 807 | break; |
| 808 | } |
| 809 | } |
| 810 | } |
| 811 | } |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 812 | // If the new nested name in the new namespace is the same as it was in the |
| 813 | // old namespace, we don't create replacement. |
Eric Liu | 9122916 | 2017-01-26 16:31:32 | [diff] [blame] | 814 | if (NestedName == ReplaceName || |
| 815 | (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName)) |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 816 | return; |
Eric Liu | 97f87ad | 2016-12-07 20:08:02 | [diff] [blame] | 817 | // If the reference need to be fully-qualified, add a leading "::" unless |
| 818 | // NewNamespace is the global namespace. |
| 819 | if (ReplaceName == FromDeclName && !NewNamespace.empty()) |
| 820 | ReplaceName = "::" + ReplaceName; |
Eric Liu | 4fe99e1 | 2016-12-14 17:01:52 | [diff] [blame] | 821 | addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager, |
| 822 | &FileToReplacements); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 823 | } |
| 824 | |
| 825 | // Replace the [Start, End] of `Type` with the shortest qualified name when the |
| 826 | // `Type` is in `NewNamespace`. |
| 827 | void ChangeNamespaceTool::fixTypeLoc( |
| 828 | const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start, |
| 829 | SourceLocation End, TypeLoc Type) { |
| 830 | // FIXME: do not rename template parameter. |
| 831 | if (Start.isInvalid() || End.isInvalid()) |
| 832 | return; |
Eric Liu | ff51f01 | 2016-11-16 16:54:53 | [diff] [blame] | 833 | // Types of CXXCtorInitializers do not need to be fixed. |
| 834 | if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type)) |
| 835 | return; |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 836 | // The declaration which this TypeLoc refers to. |
| 837 | const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl"); |
| 838 | // `hasDeclaration` gives underlying declaration, but if the type is |
| 839 | // a typedef type, we need to use the typedef type instead. |
Eric Liu | 26cf68a | 2016-12-15 10:42:35 | [diff] [blame] | 840 | auto IsInMovedNs = [&](const NamedDecl *D) { |
| 841 | if (!llvm::StringRef(D->getQualifiedNameAsString()) |
| 842 | .startswith(OldNamespace + "::")) |
| 843 | return false; |
| 844 | auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart()); |
| 845 | if (ExpansionLoc.isInvalid()) |
| 846 | return false; |
| 847 | llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc); |
| 848 | return FilePatternRE.match(Filename); |
| 849 | }; |
| 850 | // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if |
| 851 | // `Type` is an alias type, we make `FromDecl` the type alias declaration. |
| 852 | // Also, don't fix the \p Type if it refers to a type alias decl in the moved |
| 853 | // namespace since the alias decl will be moved along with the type reference. |
Eric Liu | 3215886 | 2016-11-14 19:37:55 | [diff] [blame] | 854 | if (auto *Typedef = Type.getType()->getAs<TypedefType>()) { |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 855 | FromDecl = Typedef->getDecl(); |
Eric Liu | 3215886 | 2016-11-14 19:37:55 | [diff] [blame] | 856 | if (IsInMovedNs(FromDecl)) |
| 857 | return; |
Eric Liu | 26cf68a | 2016-12-15 10:42:35 | [diff] [blame] | 858 | } else if (auto *TemplateType = |
| 859 | Type.getType()->getAs<TemplateSpecializationType>()) { |
| 860 | if (TemplateType->isTypeAlias()) { |
| 861 | FromDecl = TemplateType->getTemplateName().getAsTemplateDecl(); |
| 862 | if (IsInMovedNs(FromDecl)) |
| 863 | return; |
| 864 | } |
Eric Liu | 3215886 | 2016-11-14 19:37:55 | [diff] [blame] | 865 | } |
Piotr Padlewski | 08124b1 | 2016-12-14 15:29:23 | [diff] [blame] | 866 | const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc"); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 867 | assert(DeclCtx && "Empty decl context."); |
Eric Liu | b9bf1b5 | 2016-11-08 22:44:17 | [diff] [blame] | 868 | replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start, |
| 869 | End, FromDecl); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 870 | } |
| 871 | |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 872 | void ChangeNamespaceTool::fixUsingShadowDecl( |
| 873 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 874 | const UsingDecl *UsingDeclaration) { |
| 875 | SourceLocation Start = UsingDeclaration->getLocStart(); |
| 876 | SourceLocation End = UsingDeclaration->getLocEnd(); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 | [diff] [blame] | 877 | if (Start.isInvalid() || End.isInvalid()) |
| 878 | return; |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 879 | |
| 880 | assert(UsingDeclaration->shadow_size() > 0); |
| 881 | // FIXME: it might not be always accurate to use the first using-decl. |
| 882 | const NamedDecl *TargetDecl = |
| 883 | UsingDeclaration->shadow_begin()->getTargetDecl(); |
| 884 | std::string TargetDeclName = TargetDecl->getQualifiedNameAsString(); |
| 885 | // FIXME: check if target_decl_name is in moved ns, which doesn't make much |
| 886 | // sense. If this happens, we need to use name with the new namespace. |
| 887 | // Use fully qualified name in UsingDecl for now. |
Eric Liu | 4fe99e1 | 2016-12-14 17:01:52 | [diff] [blame] | 888 | addReplacementOrDie(Start, End, "using ::" + TargetDeclName, |
| 889 | *Result.SourceManager, &FileToReplacements); |
Eric Liu | 68765a8 | 2016-09-21 15:06:12 | [diff] [blame] | 890 | } |
| 891 | |
Eric Liu | da22b3c | 2016-11-29 14:15:14 | [diff] [blame] | 892 | void ChangeNamespaceTool::fixDeclRefExpr( |
| 893 | const ast_matchers::MatchFinder::MatchResult &Result, |
| 894 | const DeclContext *UseContext, const NamedDecl *From, |
| 895 | const DeclRefExpr *Ref) { |
| 896 | SourceRange RefRange = Ref->getSourceRange(); |
| 897 | replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(), |
| 898 | RefRange.getEnd(), From); |
| 899 | } |
| 900 | |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 901 | void ChangeNamespaceTool::onEndOfTranslationUnit() { |
| 902 | // Move namespace blocks and insert forward declaration to old namespace. |
| 903 | for (const auto &FileAndNsMoves : MoveNamespaces) { |
| 904 | auto &NsMoves = FileAndNsMoves.second; |
| 905 | if (NsMoves.empty()) |
| 906 | continue; |
| 907 | const std::string &FilePath = FileAndNsMoves.first; |
| 908 | auto &Replaces = FileToReplacements[FilePath]; |
Eric Liu | cc83c66 | 2016-09-19 17:58:59 | [diff] [blame] | 909 | auto &SM = *NsMoves.begin()->SourceMgr; |
| 910 | llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 911 | auto ChangedCode = tooling::applyAllReplacements(Code, Replaces); |
| 912 | if (!ChangedCode) { |
| 913 | llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n"; |
| 914 | continue; |
| 915 | } |
| 916 | // Replacements on the changed code for moving namespaces and inserting |
| 917 | // forward declarations to old namespaces. |
| 918 | tooling::Replacements NewReplacements; |
| 919 | // Cut the changed code from the old namespace and paste the code in the new |
| 920 | // namespace. |
| 921 | for (const auto &NsMove : NsMoves) { |
| 922 | // Calculate the range of the old namespace block in the changed |
| 923 | // code. |
| 924 | const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset); |
| 925 | const unsigned NewLength = |
| 926 | Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) - |
| 927 | NewOffset; |
| 928 | tooling::Replacement Deletion(FilePath, NewOffset, NewLength, ""); |
| 929 | std::string MovedCode = ChangedCode->substr(NewOffset, NewLength); |
| 930 | std::string MovedCodeWrappedInNewNs = |
| 931 | wrapCodeInNamespace(DiffNewNamespace, MovedCode); |
| 932 | // Calculate the new offset at which the code will be inserted in the |
| 933 | // changed code. |
| 934 | unsigned NewInsertionOffset = |
| 935 | Replaces.getShiftedCodePosition(NsMove.InsertionOffset); |
| 936 | tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0, |
| 937 | MovedCodeWrappedInNewNs); |
| 938 | addOrMergeReplacement(Deletion, &NewReplacements); |
| 939 | addOrMergeReplacement(Insertion, &NewReplacements); |
| 940 | } |
| 941 | // After moving namespaces, insert forward declarations back to old |
| 942 | // namespaces. |
| 943 | const auto &FwdDeclInsertions = InsertFwdDecls[FilePath]; |
| 944 | for (const auto &FwdDeclInsertion : FwdDeclInsertions) { |
| 945 | unsigned NewInsertionOffset = |
| 946 | Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset); |
| 947 | tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0, |
| 948 | FwdDeclInsertion.ForwardDeclText); |
| 949 | addOrMergeReplacement(Insertion, &NewReplacements); |
| 950 | } |
| 951 | // Add replacements referring to the changed code to existing replacements, |
| 952 | // which refers to the original code. |
| 953 | Replaces = Replaces.merge(NewReplacements); |
Antonio Maiorano | 0d7d9c2 | 2017-01-17 00:13:32 | [diff] [blame] | 954 | auto Style = format::getStyle("file", FilePath, FallbackStyle); |
| 955 | if (!Style) { |
| 956 | llvm::errs() << llvm::toString(Style.takeError()) << "\n"; |
| 957 | continue; |
| 958 | } |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 959 | // Clean up old namespaces if there is nothing in it after moving. |
| 960 | auto CleanReplacements = |
Antonio Maiorano | 0d7d9c2 | 2017-01-17 00:13:32 | [diff] [blame] | 961 | format::cleanupAroundReplacements(Code, Replaces, *Style); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 962 | if (!CleanReplacements) { |
| 963 | llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n"; |
| 964 | continue; |
| 965 | } |
| 966 | FileToReplacements[FilePath] = *CleanReplacements; |
| 967 | } |
Eric Liu | c265b02 | 2016-12-01 17:25:55 | [diff] [blame] | 968 | |
| 969 | // Make sure we don't generate replacements for files that do not match |
| 970 | // FilePattern. |
| 971 | for (auto &Entry : FileToReplacements) |
| 972 | if (!FilePatternRE.match(Entry.first)) |
| 973 | Entry.second.clear(); |
Eric Liu | 495b211 | 2016-09-19 17:40:32 | [diff] [blame] | 974 | } |
| 975 | |
| 976 | } // namespace change_namespace |
| 977 | } // namespace clang |