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
?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With