bool MyASTConsumer::HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) { const Decl* D = *i; if (const FunctionDecl* FD = dyn_cast(D)) { // Get the ASTContext. ASTContext& Context = FD->getASTContext(); // Print the name of the function. llvm::outs() << "Function name: " << FD->getNameAsString() << "\n"; // Print the return type of the function. llvm::outs() << "Return type: " << FD->getReturnType().getAsString() << "\n"; // Print the location of the function. llvm::outs() << "Location: " << FD->getLocation().printToString(Context.getSourceManager()) << "\n"; } } return true; }
Expr* MyASTVisitor::VisitBinaryOperator(BinaryOperator* BO) { // Get the ASTContext. ASTContext& Context = BO->getASTContext(); // Check if the binary operator is a comparison operator. if (BO->isComparisonOp()) { // Print the location of the comparison operator. llvm::outs() << "Comparison operator location: " << BO->getOperatorLoc().printToString(Context.getSourceManager()) << "\n"; } // Return the right-hand side of the binary operator. return BO->getRHS(); }This example shows how to use ASTContext to extract information about a binary operator. It defines a VisitBinaryOperator function that takes a BinaryOperator and uses ASTContext to check if the operator is a comparison operator. If it is a comparison operator, it prints the location of the operator. Finally, the function returns the right-hand side of the binary operator. Package/Library: Clang