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.
如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
作者:分布式编程
出处:https://zthinker.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。