5

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?

1 Answer 1

9

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!

2
  • 1
    Just a note, I believe we need to do CharSourceRange::getCharRange() on the source range to work for getSourceText, and there's no implicit conversion between StringRef and string. otherwise this is how I did it as well :) Oct 14, 2020 at 1:28
  • I don't know the difference between getCharRange and getTokenRange, but in my case, the latter works for me. Some identifiers are missing if I use getCharRange.
    – zsrkmyn
    Jun 2, 2021 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.