[cfe-dev] Problem with retrieving the BinaryOperator RHS end location

Richard Smith via cfe-dev cfe-dev at lists.llvm.org
Wed May 1 13:35:00 PDT 2019


On Wed, 1 May 2019 at 07:05, Nat! via cfe-dev <cfe-dev at lists.llvm.org> wrote:
>
> I am just trying to print the whole BinaryOperator statement text
> verbatim, but I can not get the end of the statement location.
>
>
> ```
>
> bool VisitBinaryOperator(BinaryOperator  *Stmt) {
>          const char       *startBuf;
>          const char       *endBuf;
>          SourceManager    *SM;
>
>          SM = &TheRewriter.getSourceMgr(); // based on Rewriter
>          startBuf = SM->getCharacterData( Stmt->getLHS()->getBeginLoc());
>          endBuf   = SM->getCharacterData( Stmt->getRHS()->getEndLoc());
>          fprintf( stderr, "write: \"%.*s\"\n", (int) (endBuf -
> startBuf), startBuf);
>          return( true);
> }
>
> ```
>
>
> For an input of:
>
> ```
>
> void   x( void)
> {
>     void  (*y)(void);
>
>     y = x;
> }
>
> ```
>
>
> I get
>
> ```
>
> write: "y = "
>
> ```
>
>
> This is the dump of the AST:
>
> ```
>
> FunctionDecl 0x19d3bd8 </home/src/srcL/llvm-clang-samples/y.m:1:1,
> line:6:1> line:1:8 referenced x 'void (void)'
> `-CompoundStmt 0x19d3ec8 <line:2:1, line:6:1>
>    |-DeclStmt 0x19d3e38 <line:3:4, col:20>
>    | `-VarDecl 0x19d3dd8 <col:4, col:19> col:12 used y 'void (*)(void)'
>    `-BinaryOperator 0x19d3ea8 <line:5:4, col:8> 'void (*)(void)' '='
>      |-DeclRefExpr 0x19d3e50 <col:4> 'void (*)(void)' lvalue Var
> 0x19d3dd8 'y' 'void (*)(void)'
>      `-ImplicitCastExpr 0x19d3e90 <col:8> 'void (*)(void)'
> <FunctionToPointerDecay>
>        `-DeclRefExpr 0x19d3e70 <col:8> 'void (void)' Function 0x19d3bd8
> 'x' 'void (void)'
> ```
>
> This is my first foray into clang rewriting...

See http://clang.llvm.org/docs/InternalsManual.html#sourcerange-and-charsourcerange

The "EndLoc" of an AST node is generally the location of the final
token (generally, SourceRanges are ranges of tokens, inclusive of both
endpoints), so you need to expand the end of the region by the length
of the last token.



More information about the cfe-dev mailing list