Retrieve Line Numbers and Column Numbers in your ANTLR AST

We know that you can easily get the line numbers and column numbers information from the lexer token, via the properties: line & pos.

When facing an Abstract Syntax Tree (AST), the rules may be rewritten so that the tree node tokens are in different order. Then how to retrieve the line numbers?

This is very important in language execution, because users will definitely need information about which line caused the issue.

The answer is simple: Retrieve the information from underlying lexer tokens. In a tree grammar rule, there may be multiple tokens. So it’s up to you to decide which token to look into. A naive method may be to look into the first token of  a tree node, using the start property.

There is another method. You can check it out at Recovering line and column numbers in your Antlr AST.

This entry was posted in antlr. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.