13 #include "clang/ASTMatchers/ASTMatchFinder.h" 14 #include "clang/ASTMatchers/ASTMatchers.h" 15 #include "clang/Lex/Lexer.h" 20 using namespace ast_matchers;
23 : SourceMgr(SourceMgr) {}
26 ast_matchers::internal::Matcher<NamespaceDecl>, innerMatcher) {
27 return innerMatcher.matches(*Node.getNamespace(), Finder, Builder);
33 const std::vector<std::string> &Abbreviations) {
35 if (!Function || !Function->hasBody())
38 if (AddedAliases[Function].count(Namespace.str()) != 0)
46 const auto *ExistingAlias = selectFirst<NamedDecl>(
48 match(functionDecl(hasBody(compoundStmt(has(declStmt(
49 has(namespaceAliasDecl(hasTargetNamespace(hasName(Namespace)))
53 if (ExistingAlias !=
nullptr) {
54 AddedAliases[Function][Namespace.str()] = ExistingAlias->getName().str();
58 for (
const auto &Abbreviation : Abbreviations) {
59 DeclarationMatcher ConflictMatcher = namedDecl(hasName(Abbreviation));
60 const auto HasConflictingChildren =
61 !match(findAll(ConflictMatcher), *Function, Context).empty();
62 const auto HasConflictingAncestors =
63 !match(functionDecl(hasAncestor(decl(has(ConflictMatcher)))), *Function,
66 if (HasConflictingAncestors || HasConflictingChildren)
69 std::string Declaration =
70 (llvm::Twine(
"\nnamespace ") + Abbreviation +
" = " + Namespace +
";")
73 Lexer::getLocForEndOfToken(Function->getBody()->getLocStart(), 0,
74 SourceMgr, Context.getLangOpts());
75 AddedAliases[Function][Namespace.str()] = Abbreviation;
76 return FixItHint::CreateInsertion(Loc, Declaration);
83 const Stmt &Statement,
84 StringRef Namespace)
const {
86 auto FunctionAliases = AddedAliases.find(Function);
87 if (FunctionAliases != AddedAliases.end()) {
88 if (FunctionAliases->second.count(Namespace) != 0) {
89 return FunctionAliases->second.find(Namespace)->getValue();
92 return Namespace.str();
SourceLocation Loc
'#' location in the include directive
NamespaceAliaser(const SourceManager &SourceMgr)
std::string getNamespaceName(ASTContext &Context, const Stmt &Statement, llvm::StringRef Namespace) const
const FunctionDecl * getSurroundingFunction(ASTContext &Context, const Stmt &Statement)
llvm::Optional< FixItHint > createAlias(ASTContext &Context, const Stmt &Statement, llvm::StringRef Namespace, const std::vector< std::string > &Abbreviations)
AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace, ast_matchers::internal::Matcher< NamespaceDecl >, innerMatcher)