0

我正在玩 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;
};

我怎样才能得到名称,即语句本身?通过使用源管理器并从原始源代码中提取它?

4

1 回答 1

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;
};
于 2015-11-02T14:54:50.433 回答