【问题标题】:How to match TemplateTypeParm node in Clang AST with AST_Matchers?如何将 Clang AST 中的 TemplateTypeParm 节点与 AST_Matchers 匹配?
【发布时间】:2019-11-03 17:02:54
【问题描述】:

我正在尝试获取 TypeAliasDecl 的 RHS 模板类型。

例子:

using AliasOfType = AliasedType; // AliasedType itself is a template

我可以使用 clang::ast_matchers::typeAliasDecl 在 AST 中检索 AliasOfType。我想用clang::ast_matchers:: 检索AliasedType

clang::ast_matchers::typeAliasDecl 的 AST 转储如下所示:

TypeAliasDecl 0x4fe22cf8 AliasOfType
  -SubstTemplateTypeParmType  0x4fe22cc0
   |-TemplateTypeParmType 0x4fe1a840 `AliasedType` dependent depth 0 index 0
   | `-TemplateTypeParm 0x4fe1a7f8 'AliasedType'

所以直观地说,我想匹配TemplateTypeParm,它有我之前的匹配作为祖先。但是,我还没有找到可以做到这一点的ast_matcher。有clang::ast_matchers::templateTypeParmType,但如果我尝试将任何内容作为缩小参数,例如:

templateTypeParmType(hasName("AliasedType"))

我尝试时遇到的错误是:

clang/ASTMatchers/ASTMatchersInternal.h:1347:13: error: ‘clang::ast_matchers::internal::Matcher< <template-parameter-1-1> >::Matcher(const clang::ast_matchers::internal::DynTypedMatcher&) [with T = clang::TemplateTypeParmType]’ is private within this context
 return {Matcher<T>(std::get<Is>(Params))...};

【问题讨论】:

    标签: c++ c++11 clang llvm abstract-syntax-tree


    【解决方案1】:

    你是对的,没有直接匹配器来检查类型别名的别名类型(你自己实现它并不难,但我想这应该是最后的手段)。

    但是,根据documentation,有一个匹配器has

    匹配具有匹配子 AST 节点的 AST 节点 提供匹配器。

    另一个重要的一点是,类型别名肯定会有一个TypeLoc 作为孩子。这是关于Types 和TypeLocs 之间区别的小引述(来自Internals Manual):

    我们在表示相同类型时重用 Type 节点(但为每个写入类型的实例维护单独的 TypeLocs)

    将它们放在一起,我们得到以下匹配器:

    typeAliasDecl(has(typeLoc(loc(templateTypeParmType())).bind("x")))
    

    对于这段代码sn-p:

    using NotInterestingAlias = int;
    
    template <class AliasedType> class TemplateClass {
      using AliasOfType = AliasedType;
      using AliasOfSomeOtherType = double;
    };
    
    int main() { return 0; }
    

    匹配器将产生以下输出:

    main.cpp:4:3: note: "root" binds here
      using AliasOfType = AliasedType;
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    main.cpp:4:23: note: "x" binds here
      using AliasOfType = AliasedType;
                          ^~~~~~~~~~~
    

    我希望这些信息有用。愉快地使用 Clang 进行黑客攻击!

    【讨论】:

    • 太棒了!这行得通。我将has(typeLoc(loc(templateTypeParmType())).bind("x")) 放在allOf 匹配器中,该匹配器包含在typeAliasDecl 匹配器中以获得我想要的。
    猜你喜欢
    • 2019-08-03
    • 2017-05-23
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多