gpt4 book ai didi

c++ - Clang AST 访问者,避免遍历包含文件

转载 作者:太空狗 更新时间:2023-10-29 20:54:48 25 4
gpt4 key购买 nike

你好,我正在尝试实现一个 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 << "\n\n" << 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 上下文,您可以获得正在解析的代码的所有必需信息。区分主文件或头文件中的 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 教程。

关于c++ - Clang AST 访问者,避免遍历包含文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com