[antlr-interest] Line number help
F Reig
fermin.reig at gmail.com
Fri Nov 10 10:50:53 PST 2006
On 7/21/06, Walter Schilling <walter.schilling at computer.org> wrote:
> Good afternoon.
>
> I am having some difficulty developing a Java analysis tool when it
> comes to line numberings and I want to see if there is a better way to
> handle what I need done. In specific, I desire two bits of information
> from my tree parser, the starting line / column location for a construct
> and the ending line / column location for a construct. Per one of the
> older FAQ answers in the antlr documentation, I have extended the
> CommonAST class to include line numbers and locations. However, if I
> have a rule such as:
>
> expression
> : #(EXPR expr)
> ;
>
> the line number and column number within the AST are always zero. I
> suspect this has to do with the way they are constructed in the parser.
> As an interim measure, I have developed routines which walk the
> expression structure to find the starting and ending line numbers, but
> is there any easy way of appending this information right into the EXPR
> node? That is, any way short of modifying each and every rule where I
> create such a tree structure when parsing the code?
>
> Thanks,
>
> Walt Schilling
I've had to fix the same problem with my grammar today. I ended up
defining a method like this:
private void setLineCol(AST t, LineColAST child) {
((LineColAST)t).setLine(child.getLine());
((LineColAST)t).setCol(child.getCol());
}
This is for C#. Then, in my grammar, I replace rules like this one:
expression
: start:exp
{## = #([EXPR,"EXPR"], #expression); }
;
by this
expression
: start:exp
{## = #([EXPR,"EXPR"], #expression); setLineCol(##, #start); }
;
I noticed this is how it is done in the grammar for SDL 2000,
available at the antlr website, so I'm doing the same.
I hope that helps
Fermin
More information about the antlr-interest
mailing list