clang ast访问者,避免遍历文件

Clang AST visitor, avoid traversing include files

本文关键字:遍历 文件 ast 访问者 clang      更新时间:2023-10-16

你好,我正在尝试实现AST Clang访问者,这是我的代码。

class ExampleVisitor : public RecursiveASTVisitor<ExampleVisitor> {
private:
    ASTContext *astContext; // used for getting additional AST info
public:
    virtual bool VisitVarDecl(VarDecl *var) 
    {
        numVariables++;
        string varName = var->getQualifiedNameAsString();
        string varType = var->getType().getAsString();
        cout << "Found variable declaration: " << varName << " of type " << varType << "n";
        APIs << varType << ", ";
        return true;
    }
    virtual bool VisitFunctionDecl(FunctionDecl *func)
    {
        numFunctions++;
        string funcName = func->getNameInfo().getName().getAsString();
        string funcType = func->getResultType().getAsString();
        cout << "Found function declaration: " << funcName << " of type " << funcType << "n";
        APIs << "nn" << funcName <<": ";
        APIs << funcType << ", ";
        return true;
    }
    virtual bool VisitStmt(Stmt *st) 
    {
        if (CallExpr *call = dyn_cast<CallExpr>(st)) 
        {
            numFuncCalls++;
            FunctionDecl *func_decl = call->getDirectCallee();
            string funcCall = func_decl->getNameInfo().getName().getAsString();
            cout << "Found function call: " << funcCall << " with arguments ";
            APIs << funcCall << ", ";
            for(int i=0, j = call->getNumArgs(); i<j; i++)
            {
                string TypeS;
                raw_string_ostream s(TypeS);
                call->getArg(i)->printPretty(s, 0, Policy);
                cout<< s.str() << ", ";
                APIs<< s.str() << ", ";
           }
            cout << "n";
        }
        return true;
    }
};

我如何避免穿越随附的标头文件,而不会丢失信息。我只是不想打印有关此文件的任何信息,但我希望Clang了解这些文件

谢谢

通过使用AST上下文,您可以获取您正在解析的代码的所有NesceCarry信息。区分主文件或标题文件中的AST节点的函数称为isInmainFile(),可以使用如下。

bool VisitVarDecl(VarDecl *var)
{
    if (astContext->getSourceManager().isInMainFile(var->getLocStart())) //checks if the node is in the main = input file.
    {
        if(var->hasLocalStorage() || var->isStaticLocal())
        {
            //var->dump(); //prints the corresponding line of the AST.
            FullSourceLoc FullLocation = astContext->getFullLoc(var->getLocStart());
            numVariables++;
            string varName = var->getQualifiedNameAsString();
            string varType = var->getType().getAsString();
            REPORT << "Variable Declaration [" << FullLocation.getSpellingLineNumber() << "," << FullLocation.getSpellingColumnNumber() << "]: " << varName << " of type " << varType << "n";
            APIs << varType << ",";
        }
    }
    return true;
}

有关如何使用AstContext的更多信息,请遵循Clang网站上的官方递归Astvisitor教程。