Question

Is there any way to find the line number where a code block ends

Example: for the following input

21) synchronized(Lock.class){
22)      a.getAndIncrement(); //some code
23)       
24) }

the corresponding AST is

             synchronized
                 PARENTESIZED_EXPR
                    EXPR
                       .
                          Lock
                          class
                 BLOCK_SCOPE
                    EXPR
                       METHOD_CALL
                          .
                             g
                             getAndIncrement
                          ARGUMENT_LIST

for the above code given the CommonTree is there any way to retrieve the line number where the "synchronized" block ends. The output for the above code should be 24(as the synchronized block ends at line number 24).

Was it helpful?

Solution

Yes, through the following technique:

  1. Make sure the } does not get omitted from the AST.
    • If you are using the rewrite operator ->, this means the } token needs to appear on the right hand side.
    • If you are using the AST operators ^ and !, this means you can't use the ! operator on your } token.
  2. Find the CommonTree corresponding to the } token, and call getLine() on the token to get the line number.

Edit: Here is the current block rule in the grammar:

block
    :   LCURLY blockStatement* RCURLY
        ->  ^(BLOCK_SCOPE[$LCURLY, "BLOCK_SCOPE"] blockStatement*)
    ;

As you can see, the rewrite rule does not include the RCURLY token, so information about the position of the end of the block is omitted. The rule can be modified to include the token:

block
    :   LCURLY blockStatement* RCURLY
        ->  ^(BLOCK_SCOPE[$LCURLY, "BLOCK_SCOPE"] blockStatement* RCURLY)
    ;

Note that this requires updating the corresponding in the tree grammar as well.

block
    :   ^(BLOCK_SCOPE blockStatement* RCURLY)
    ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top