#includeusing namespace clang; // Create a SourceRange object for the code block starting at line 10 and ending at line 20 SourceLocation startLoc = ...; // The start of the block (e.g. line 10) SourceLocation endLoc = ...; // The end of the block (e.g. line 20) SourceRange blockRange(startLoc, endLoc); // Get the end location of the block using the getEnd function SourceLocation blockEndLoc = blockRange.getEnd(); // Use the end location to create another SourceRange object for the last statement in the block SourceRange lastStmtRange(blockEndLoc, blockEndLoc.getLocWithOffset(10)); // Offset of 10 for demo purposes // Print the end location of the block and the range of the last statement llvm::errs() << "Block end location: " << blockEndLoc.getSpellingLineNumber() << "\n"; llvm::errs() << "Last statement range: " << lastStmtRange.getBegin().getSpellingLineNumber() << "-" << lastStmtRange.getEnd().getSpellingLineNumber() << "\n";
#includeIn this example, we create a Clang tool that analyzes C++ code and prints information about each function. We use the getSourceRange function to get the SourceRange object representing the range of each function and then use the getEnd function to print the line number of the end of each function. This example uses the CommonOptionsParser class to parse command-line arguments and the ASTConsumer and ASTFrontendAction classes to handle the AST.#include #include #include #include #include using namespace clang; using namespace clang::tooling; class FunctionInfoPrinter : public ASTConsumer { public: virtual void HandleTranslationUnit(ASTContext &context) override { for (const auto &decl : context.getTranslationUnitDecl()->decls()) { if (auto func = dyn_cast (decl)) { SourceRange range = func->getSourceRange(); llvm::errs() << "Function: " << func->getNameAsString() << " (" << range.getBegin().getSpellingLineNumber() << "-" << range.getEnd().getSpellingLineNumber() << ")\n"; } } } }; class FunctionInfoAction : public ASTFrontendAction { public: virtual std::unique_ptr CreateASTConsumer(CompilerInstance &instance, StringRef file) override { return std::make_unique (); } }; int main(int argc, const char **argv) { CommonOptionsParser options(argc, argv); ClangTool tool(options.getCompilations(), options.getSourcePathList()); return tool.run(newFrontendActionFactory ().get()); }