Files
carbon-lang/migrate_cpp/cpp_refactoring/fn_inserter.cpp
T
Jon Meow 4f1b2198ff Refactor Matcher code to reduce per-Matcher boilerplate (#615)
This is in part to eliminate the "sm" and "lang_opts" variables that received comment, but also cuts back on the use of auto.
2021-07-08 12:42:24 -07:00

47 lines
1.7 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "migrate_cpp/cpp_refactoring/fn_inserter.h"
#include "clang/ASTMatchers/ASTMatchers.h"
namespace cam = ::clang::ast_matchers;
namespace Carbon {
static constexpr char Label[] = "FnInserter";
void FnInserter::Run() {
const auto& decl = GetNodeAsOrDie<clang::FunctionDecl>(Label);
// For names like "Class::Method", replace up to "Class" not "Method".
clang::NestedNameSpecifierLoc qual_loc = decl.getQualifierLoc();
clang::SourceLocation name_begin_loc =
qual_loc.hasQualifier() ? qual_loc.getBeginLoc() : decl.getLocation();
auto range =
clang::CharSourceRange::getCharRange(decl.getBeginLoc(), name_begin_loc);
// In order to handle keywords like "virtual" in "virtual auto Foo() -> ...",
// scan the replaced text and only drop auto/void entries.
llvm::SmallVector<llvm::StringRef> split;
GetSourceText(range).split(split, ' ', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
std::string new_text = "fn ";
for (llvm::StringRef t : split) {
if (t != "auto" && t != "void") {
new_text += t.str() + " ";
}
}
AddReplacement(range, new_text);
}
auto FnInserterFactory::GetAstMatcher() -> cam::DeclarationMatcher {
return cam::functionDecl(cam::anyOf(cam::hasTrailingReturn(),
cam::returns(cam::asString("void"))),
cam::unless(cam::anyOf(cam::cxxConstructorDecl(),
cam::cxxDestructorDecl())))
.bind(Label);
}
} // namespace Carbon