zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    软件性能测试
    我为何转来博客园
    【5】查询练习:DISTINCT、Between...and...、in、order by、count
    第5章:pandas入门【3】汇总和计算描述
    【4】建点表,填点数
    【3】数据库三大设计范式
    【2】约束
    【1】基本操作
    第5章:pandas入门【2】基本功能
    第5章:pandas入门【1】Series与DataFrame
  • 原文地址:https://www.cnblogs.com/daichangya/p/12959168.html
Copyright © 2011-2022 走看看