【问题标题】:How can I get the name of a statement in Clang LibTooling?如何在 Clang LibTooling 中获取语句的名称?
【发布时间】:2015-11-02 14:09:27
【问题描述】:

我在玩 LibTooling:我想做的是输出源文件中所有变量的所有位置。

为了查找所有出现的变量,我重载了 RecursiveASTVisitor 和方法“bool VisitStmt(Stmt)”(见下文),但现在我不知道如何输出变量的名称。目前,我的代码只输出“DeclRefExpr”,但我想要类似“myNewVariable”或我在输入文件中定义的任何内容。

class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor>
{
public:
    explicit MyASTVisitor(ASTContext *Context_passed) : Context(Context_passed) {}

    bool VisitStmt(Stmt *sta)
    {
        FullSourceLoc FullLocation = Context->getFullLoc(sta->getLocStart());
        SourceManager &srcMgr = Context->getSourceManager();
        if
        (
            FullLocation.isValid() &&
            strcmp(sta->getStmtClassName(), "DeclRefExpr") == 0
        )
        {
            // Print function name
            printf("stm: %-23s at %3u:%-3u in %-15s\n",
                sta->getStmtClassName(),
                FullLocation.getSpellingLineNumber(),
                FullLocation.getSpellingColumnNumber(),
                srcMgr.getFilename(FullLocation).data());
        }
        return true;
    }

private:
    ASTContext *Context;
};

如何获取名称,即语句本身?通过使用源管理器并从原始源代码中提取它?

【问题讨论】:

    标签: clang libtooling


    【解决方案1】:

    使用 getFoundDecl() 方法可以获取“NamedDecl”类的实例,然后使用 getNameAsString() 方法可以将名称作为字符串获取,所以现在的代码如下所示:

    class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor>
    {
    public:
        explicit MyASTVisitor(ASTContext *Context_passed) : Context(Context_passed) {}
    
        bool VisitDeclRefExpr(DeclRefExpr *sta)
        {
            FullSourceLoc FullLocation = Context->getFullLoc(sta->getLocStart());
            SourceManager &srcMgr = Context->getSourceManager();
            if ( FullLocation.isValid() )
            {
                // Print function or variable name
                printf("stm: %-23s at %3u:%-3u in %-15s\n",
                    (sta->getFoundDecl())->getNameAsString().c_str(),
                    FullLocation.getSpellingLineNumber(),
                    FullLocation.getSpellingColumnNumber(),
                    srcMgr.getFilename(FullLocation).data());
            }
            return true;
        }
    
    private:
        ASTContext *Context;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多