如何使用Clang-AstMatcher获取所有构造函数初始值设定项?

时间:2014-07-31 04:49:41

标签: clang

我是Clang ASTMatcher的新手。我已经阅读了一些教程并尝试了所有的初始化。

输入代码

Person(char gender) : m_gender(gender)
                      ^^^^^^^^^^^^^^^^ <= I need to get those codes.
{
    ...
}

-ast-dump输出

| |-CXXConstructorDecl 0x4678ad0 <line:9:5, col:45> col:5 Person 'void (char)'
| | |-ParmVarDecl 0x4678a10 <col:12, col:17> col:17 used gender 'char'
| | |-CXXCtorInitializer Field 0x4678dd0 'm_gender' 'int'
     ...

匹配代码

StatementMatcher CtorInitMatcher =
    clang::ast_matchers::ctorInitializer().bind("ctor_init");

...

class LoopPrinter : public MatchFinder::MatchCallback
{
public :
    virtual void run(const MatchFinder::MatchResult& result)
    {
        if (const clang::Stmt* stmt
            = result.Nodes.getNodeAs<clang::Stmt>("ctor_init"))
        {
            std::cout << "===== found: CXXCtorInit. =====" << std::endl;
            stmt->dump();
            std::cout << std::endl;
        }


    }
};

编译错误消息

我收到了错误消息:

ex03.cc:27:60: error: conversion from ‘clang::ast_matchers::internal::Matcher<clang::CXXCtorInitializer>’ to non-scalar type ‘clang::ast_matchers::StatementMatcher {aka clang::ast_matchers::internal::Matcher<clang::Stmt>}’ requested
     clang::ast_matchers::ctorInitializer().bind("ctor_init");

任何建议都会受到赞赏。

1 个答案:

答案 0 :(得分:5)

你应该尝试一下clang-query。有了它,您可以交互式查询加载的AST并轻松尝试不同的匹配器。

无论如何你想要的东西可能是这样的: constructorDecl(forEachConstructorInitializer(ctorInitializer()。结合( “ctorInitializer”)))

clang-query> set output diag
clang-query> match constructorDecl(forEachConstructorInitializer(ctorInitializer().bind("ctorInitializer")))

Match #1:
/tmp/test.cpp:3:36: note: "ctorInitializer" binds here
    Person(char gender, int age) : m_gender(gender), m_age(age)
                                   ^~~~~~~~~~~~~~~~

Match #2:
/tmp/test.cpp:3:54: note: "ctorInitializer" binds here
    Person(char gender, int age) : m_gender(gender), m_age(age)
                                                     ^~~~~~~~~~

2 Matches.