fn_inserter.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. #include "clang/Lex/Lexer.h"
  7. namespace cam = ::clang::ast_matchers;
  8. namespace Carbon {
  9. FnInserter::FnInserter(std::map<std::string, Replacements>& in_replacements,
  10. cam::MatchFinder* finder)
  11. : Matcher(in_replacements) {
  12. finder->addMatcher(
  13. cam::functionDecl(cam::anyOf(cam::hasTrailingReturn(),
  14. cam::returns(cam::asString("void"))),
  15. cam::unless(cam::anyOf(cam::cxxConstructorDecl(),
  16. cam::cxxDestructorDecl())))
  17. .bind(Label),
  18. this);
  19. }
  20. void FnInserter::run(const cam::MatchFinder::MatchResult& result) {
  21. const auto* decl = result.Nodes.getNodeAs<clang::FunctionDecl>(Label);
  22. if (!decl) {
  23. llvm::report_fatal_error(std::string("getNodeAs failed for ") + Label);
  24. }
  25. auto& sm = *(result.SourceManager);
  26. auto lang_opts = result.Context->getLangOpts();
  27. // For names like "Class::Method", replace up to "Class" not "Method".
  28. clang::NestedNameSpecifierLoc qual_loc = decl->getQualifierLoc();
  29. clang::SourceLocation name_begin_loc =
  30. qual_loc.hasQualifier() ? qual_loc.getBeginLoc() : decl->getLocation();
  31. auto range =
  32. clang::CharSourceRange::getCharRange(decl->getBeginLoc(), name_begin_loc);
  33. // In order to handle keywords like "virtual" in "virtual auto Foo() -> ...",
  34. // scan the replaced text and only drop auto/void entries.
  35. llvm::SmallVector<llvm::StringRef> split;
  36. clang::Lexer::getSourceText(range, sm, lang_opts)
  37. .split(split, ' ', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  38. std::string new_text = "fn ";
  39. for (llvm::StringRef t : split) {
  40. if (t != "auto" && t != "void") {
  41. new_text += t.str() + " ";
  42. }
  43. }
  44. AddReplacement(*(result.SourceManager), range, new_text);
  45. }
  46. } // namespace Carbon