Understanding ANTLR Grammar Files

Are you confused by all the different sections of an Antlr grammar file, wondering what each one does ? Well lets take another look at them, this time using Antlr Studio.

Believe it or not but Antlr grammar files are built to be as close to your java source files as possible. What, you don't see any similarities between your java files and antlr grammars? Well, let me show you...

Grammar


 

Everything you put in the header section of the grammar file is placed right on top of all the java files generated by Antlr. Think of this at the absolute top of your java files, you generally use this section to put the package definition. You can even place some imports that are common in all the generated files.

The action section below that is unique for every grammar you specify in the file. This is placed right before the actual class specification. For example here we want to import the ArrayList and MyClass for the CalcParser only.

Then we have the grammar specification, which even looks like a class declaration.

Below that is the options section , where you can specify the options for the grammar. You can press Ctrl+Space in Antlr Studio to see which options are available.

The tokens section is used to specify 'imaginary' tokens which are not declared in the lexer. These are generally used in TreeParsers to specify 'imaginary nodes.

Another action section. This one puts its stuff 'inside' the class definition. You generally use it to define some custom methods for your parser.

RULES

A rule definition inside an antlr grammar corresponds to a method definition in the generated java file.

As you can see , here again we can do everything with a rule , that can be done with a function.We can specify arguments for the rule ,as shown above (int a), even a return value and the exceptions thrown by the rule.

The options section allows us to specify some rule specific options.

We can specify custom exception handlers in the exception section.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值