fn_inserter.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "migrate_cpp/cpp_refactoring/fn_inserter.h"
  5. #include "clang/ASTMatchers/ASTMatchers.h"
  6. namespace cam = ::clang::ast_matchers;
  7. namespace Carbon {
  8. static constexpr char Label[] = "FnInserter";
  9. void FnInserter::Run() {
  10. const auto& decl = GetNodeAsOrDie<clang::FunctionDecl>(Label);
  11. // For names like "Class::Method", replace up to "Class" not "Method".
  12. clang::NestedNameSpecifierLoc qual_loc = decl.getQualifierLoc();
  13. clang::SourceLocation name_begin_loc =
  14. qual_loc.hasQualifier() ? qual_loc.getBeginLoc() : decl.getLocation();
  15. auto range =
  16. clang::CharSourceRange::getCharRange(decl.getBeginLoc(), name_begin_loc);
  17. // In order to handle keywords like "virtual" in "virtual auto Foo() -> ...",
  18. // scan the replaced text and only drop auto/void entries.
  19. llvm::SmallVector<llvm::StringRef> split;
  20. GetSourceText(range).split(split, ' ', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  21. std::string new_text = "fn ";
  22. for (llvm::StringRef t : split) {
  23. if (t != "auto" && t != "void") {
  24. new_text += t.str() + " ";
  25. }
  26. }
  27. AddReplacement(range, new_text);
  28. }
  29. void FnInserterFactory::AddMatcher(cam::MatchFinder* finder,
  30. cam::MatchFinder::MatchCallback* callback) {
  31. finder->addMatcher(
  32. cam::functionDecl(cam::anyOf(cam::hasTrailingReturn(),
  33. cam::returns(cam::asString("void"))),
  34. cam::unless(cam::anyOf(cam::cxxConstructorDecl(),
  35. cam::cxxDestructorDecl())))
  36. .bind(Label),
  37. callback);
  38. }
  39. } // namespace Carbon