[antlr-interest] Re: Line number information for AST
antlrlist
antlrlist at yahoo.com
Thu Oct 2 10:05:10 PDT 2003
<hiteshk25 at y...> wrote:
>
> Hi,
>
> How to get line number, which says token of AST
> node belong to that line.
>
> with regards,
> Hitesh.
Hi Hitesh!
The key is this: in ANTLR, AST nodes are completely different from
tokens. ASTs are (normally) instances of antlr.CommonAST, while
tokens are (normally) instances of antlr.CommonToken. These are
completely different classes (no inheritance neither composition
between them). They just "look" similar, because both have a "type"
attribute and a "text" attribute. CommonType can even be initialized
with a Token, but don't let this dissapoint you: only type and text
are copied. This is where similarities end: AST nodes don't have
file line or columns!
Putting aside the design reasons for this implementation, let me
reformulate your question:
How do I *add* line and column to the AST nodes?
This is easy: you can subclass antlr.CommonAST and add your own line
and column attributes. Then override the initialize() methods so
they copy line and column from the tokens, and add get and set
methods.
Finally, you'll have to make your parser use your new AST node class
instead of antlr.CommonAST... but I'll let you guess how to do it :)
...
I was joking :D! Use options ASTLabelType
(http://www.antlr.org/doc/options.html#_bb13) and
Parser.setASTNodeType
(http://www.antlr.org/javadoc/antlr/Parser.html#setASTNodeType
(java.lang.String))
However, if you want to make your life easier, you can use my lib,
antlraux (http://antlraux.sf.net). It has a class, LexInfoAST
(http://antlraux.sourceforge.net/javadoc/antlraux/util/LexInfoAST.htm
l) that will match your needs perfectly (it even includes filename
O_O)
Cya!
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list