Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang - how to retrieve "Expr" as string?

I am using Clang/libtooling (ASTComsumer with a Matcher) to visit ALL return statements (ReturnStmt). I need to extract the expression that comes after the keyword return in a string form so that I can put that in a macro that I am replacing return statement with.

For example, I want to replace the following line:

return somefunc() + 1;

with

FUNCTION_EXIT(somefunc() + 1); // FUNCTION_EXIT is a C macro

The macro will return from the function after doing some logging.

I am using ReturnStmt::getRetValue() that returns an Expr and tried to get it in string form (so that it can be passed to the macro), but I haven't found a way yet. Is there a way to stringify Expr?

like image 205
DLight Avatar asked Mar 06 '23 18:03

DLight


1 Answers

Clang has a strict separation of concerns between the abstract syntax tree (AST) and the actual source code. The component that converts between these is the Lexer. To get the raw source for an Expr e:

const string text = Lexer::getSourceText(e.getSourceRange(), source_manager, opt);

Note that the SourceManager and LangOptions are available from the ASTContext. If the code you're parsing has macros then things get more complicated because you have to care about spelling location versus expansion location; SourceManager has a bunch of different functions to convert between these.

Good luck!

like image 111
RedSpikeyThing Avatar answered Mar 31 '23 07:03

RedSpikeyThing