JavaCC技术手册之JJTree参考文档

         不知道大家了解Lucence这个项目么,一个开源的搜索引擎。不过想看懂很难,因为需要很多相关的知识,我这里就翻译了一篇文档,JavaCC技术手册之JJTree参考文档,Lucence在一些主要的文法分析中用到了JavaCC,而JJTree是JavaCC的一个预处理。下面就是翻译:

JavaCC技术手册:JJTree参考文档 [翻译:Kevin Wang]

简洁

    JJTreeJavaCC源代码的不同地方嵌入语法树构建动作,可以理解为JavaCC的预处理工具。通过运行JavaCC创建解析器生成JJTree输出文件。这篇文档描述了如何使用JJTree,以及如何从中分离你的解析器。

    JJTree默认为每个非终结符生成代码来创建语法分析树节点。这种行为可以被修改以便于一些非终结符不生成节点或者因为一部分内容扩充而生成一个节点。

       JJTree已经定义了一个所有语法分析树节点必须实现的接口Node,这个接口定义诸如:设置节点的父节点、增加子节点、重新获得子节点 等操作方法。

       JJTree(为想要更多条件)可以设置 simple multi”两种模式之一。在“simple[单一]模式下语法分析树节点都是“SimpleNode”这个具体类型。而在“multi[多个]模式下语法分析树节点类型取决于节点的名字。如果你不为“Node”接口提供实现JJTree会为你生成一些基于“SimpleNode”的样品实现,你可以修改这个实现以适应需求。

       虽然JavaCC是一个从顶至下的解析器(LL(K)  通常我们只要用LL(1)即可 ),但是JJTree构造语法树过程却是从底至上构建的。为此使用堆栈,当他们被创建后它可以把节点压入堆栈中。当它找到一个父节点时,从堆栈中弹出子节点并且将其添加到父节点下,最后把新的父节点压入堆栈。堆栈是开放的意味着你可以使用内部语法行为对其访问:入堆栈,出堆栈,另外不管你有多么的适应请熟练使用它的内容。更多的重要信息请参看下面“节点作用域和用户行为”章节的介绍。

       JJTree提供2种基本节点种类定义,可以依据造句法的缩写使其使用起来更方便。

1、  明确节点:一个以指定子节点数创建的节点。其中许多节点可以被弹出堆栈成为新节点的子节点,然后把这个新节点压入栈。你可以像这样定义一个明确节点:

        #ADefiniteNode(INTEGER EXPRESSION)

   虽然INTEGER是目前为止使用最多的表达式,但明确节点参数“EXPRESSION”可以使用任何INTEGER 表达式。

2、  条件节点:当且仅当条件值为True时,带着所有被压入节点区域内部的子节点创建条件节点。如果条件值为False节点不会被创建,所有的子节点将残留在节点堆栈中。你可以像这样定义一个条件节点:

#ConditionalNode(BOOLEAN EXPRESSION)

       一个条件节点描述符“EXPRESSION”可以使用任何BOOLEAN 表达式。下边有2个常用的条件节点内容需要记忆:

                1、不确定节点

                      #IndefiniteNode #IndefiniteNode(true) 的简写

          2大节点

              #GTNode(>1) #GTNode(jjtree.arity() > 1) 的简写

 

       JJTree源代码中,当简写的不确定节点表达跟着一个括号表达式时,可能导致歧义。在那种情况下简写必须用完全写法替代。例如:

            ( ... ) #N ( a() ) 

       上面表达式逻辑不清,你必须明确的使用条件式:

          ( ... ) #N(true) ( a() )

       注意:节点描述符表达式不能有副作用,JJTree并没有指定表达式将被计算多少次。

       默认情况下JJTree把每一个非终结符作为一个不确定节点对待,从它的产生式的名                  

字衍生出节点名字。也可以用下面的语法给他一个不同的名字:

          void P1() #MyNode : { ... } { ... }

当解析器识别出了一个P1非终结符,它先定义一个节点,并在堆栈中进行标记,以便于一些由扩展P1非终结符而构建和入栈的分析树节点被弹出并成为 MyNode节点的子节点。

       如果想要使某个产生式禁止创建节点,你可以使用下面的语法:

           void P2() #void : { ... } { ... }

    这样,一些根据非终结符入栈作为P2扩展的语法分析树节点会留在堆栈中,会被将来的产生式弹出作为其子节点,non-decorated[非包装]节点你也可以通过使用NODE_DEFAULT_VOID选项使之成为默认行为。

               void P3() : {}
               {
                   P4() ( P5() )+ P6()
               }

    这个例子中,一个不确定的节点P3被启动并标记堆栈,然后是1P4节点,1个或多个P5节点和1P6节点被解析。被入堆栈的任何节点都会被弹出成为P3的子节点。你可以更深一步的定制生成树:

                 void P3() : {}
               {
                       P4() ( P5() )+ #ListOfP5s P6()
                       我认为这里是P4() ( P5() ) #ListOfP5s + P6()
     
     
                }

       现在P3节点会有一个P4节点、一个ListOfP5s节点和一个P6节点作为子节点#Name结构表示一个后缀操作符,它的区域直接就是前面的扩展单元。

 

节点作用域和用户行为

    每个节点都有其作用域。这个作用域内的用户行为可以通过使用特殊标志符“jjtThis”来访问已被创建的节点。这个标志符被隐含的声明为节点的正确类型,这样此节点的一些字段、方法可以轻易的被访问。

一个作用域就是前面一个节点定义的扩展单位。这可能是一个括号表达式。当产生式符号被定义(或者是隐含定义的默认节点),它的作用域就是包括声明块在内的整个产生式的右侧。

你可以使用一个包括“jjtThis”扩展引用左侧的表达式。例如:

       ... ( jjtThis.my_foo = foo() ) #Baz ...

这里“jjtThis”引用了一个含有“my_foo”字段的“Baz”节点。foo() 产生式解析的结果是被赋给“my_foo”。

    节点作用域内用户的最终行为不同于所有的其他行为。当代码执行过程中,子节点已经被从堆栈中弹出并被添加给这个被压入堆栈的节点。这些孩子节点可以通过诸如这个节点的方法jjtGetChild().进行访问。除了最终用户行为之外的用户行为仅能访问堆栈中的子节点。此节点的方法对那些没有被赋给这个节点的孩子节点是无效的。

    一个条件计算结果为False的条件表达式条件节点既不能被得到以添加到堆栈中,其孩子节点也不能被添加。条件节点作用域内的最终用户行为可以通过调用方法nodeCreated()决定此节点是否被创建。如果节点条件被满足、节点被创建、并且被压入堆栈的话结果返回True,否则返回False

 

异常处理

       一个由节点作用域内扩展抛出却没有在节点作用域内捕获的异常将由JJTree自行处理。当这种情况发生时,那些再节点作用域内被压入堆栈的节点会被弹出堆栈并被抛弃。之后一个异常会被重新抛出。

       这样做的意图是使分析其可以进行错误校验并且使节点堆栈继续处于一个可知的状态。

       注意:一般JJTree 不能识别出此异常是否由节点作用于内用户行为抛出的。这样的异常有可能被不正确的处理。

 

节点范围钩子

如果NODE_SCOPE_HOOK选项被置为TrueJJTree会在每个节点作用域的入口和出口处调用用户自定义的2个解析器方法。这些方法必须有下面的形式:

        void jjtreeOpenNodeScope(Node n)
        void jjtreeCloseNodeScope(Node n)

如果解析器是静态的,那么这些方法也必须被声明成静态的。他们都以当前节点作为被调用的参数。

       一种用途是这些功能将用来存储节点的首尾标记符以便于输入可以很容易的被重现。例如:

               void jjtreeOpenNodeScope(Node n)
                {
                     ((MySimpleNode)n).first_token = getToken(1);
                }

  
  
   
    
  
  
               void jjtreeCloseNodeScope(Node n)
               {
                     ((MySimpleNode)n).last_token = getToken(0);
                }

       基于SimpleNodeMySimpleNode类中有下面2个额外的字段:

               Token first_token, last_token;

       另外一个用途是用于将解析器对象自身存储于节点以便于状态可以被解析器提供的所有节点所共享。

节点的生存周期

一个节点的建立经历了一个很好被确定的序列步骤。下面是从节点自身的透视图观察的序列。

1、创建节点需要一个独特的整形参量。这个参数确定了节点的种类,这在单一模式中有其有用。JJTree自动生成了一个声明了有效常量的类 parserTreeConstants.java 常量的名字取决于JJT前缀加文件中节点名字的大写字符串。用字符“.”代替字符“_ 。为方便起见,在同一个文件中维护了一个被称为jjtNodeName[]的字符串数组,它遍历了节点的未修改名字的常量。

2、节点的方法jjtOpen()被调用

3、如果NODE_SCOPE_HOOK选项被设置为True,那么用户自定义的方openNodeScope()将被调用并且以此节点为参数。这个方法可以初始化节点的字段或者调用节点的方法。例如,他可以存储节点的首标记符。

4、如果一个节点被解析时抛出了一个未捕获的异常,节点将被抛弃。JJTree将不再对其进行引用。虽然用户自定义的节点作用域钩子closeNodeHook()将不再调用此节点作为参数,但节点不会被关闭

5、另外,如果一个条件节点的条件计算值为False,节点将被抛弃。虽然用户自定义节点作用域钩子closeNodeHook()可能调用此节点作为参数,但节点不会被关闭。

6、另外,一个明确节点通过整形表达式制定的所有孩子节点或者在一个条件节点作用域内被压入堆栈的所有节点被赋给此节点。他们的添加次序并没有被确定。

7、节点的方法jjtClose()被调用。

8、节点被压入堆栈。

9、如果NODE_SCOPE_HOOK选项被设置为True,则用户自定义方法closenNodeScope()将被调用并且以此节点作为参数。

10、如果节点不是根节点,他将作为其他节点的字节点被添加并且它的jjtSetParent()方法被调用。

 

访问者支持

       JJTree为访问者提供了一些基本的设计模式。如果VISITOR选项被设置为TrueJJTree将会在生成所有节点类时插入jjtAccept()方法,并且生成一个以此节点为参数而被实现的访问者接口。[public Object visit(具体Node,Object)]

       访问者接口的名字由解析器名字加Visitor来构造。每当JJTree运行时接口会被生成,以便于他可以准确地表现解析其所使用的那些节点。如果实现类不能被新节点更新将会产生编译时错误。只是一个特性。

 

选项

       JJTree在命令行或者JavaCC选项声明中提供了下面这些选项:

       BUILD_NODE_FILES (default: true)

       SimpleNode以及语法中使用的其它节点创建样本实现。

       MULTI (default: false)

       创建多模式解析树。此选项默认为False,生成一个单一模式解析树。

       NODE_DEFAULT_VOID (default: false)

       此选项设置为True时,不在使每个非包装产生式定义一个节点,取而代之为空。

       NODE_FACTORY (default: false)

       用下面的方式使用一个工厂方法创建一个节点:

       public static Node jjtCreate(int id)

NODE_PACKAGE (default: "")

    被放进生成节点类里的包。默认为解析器的包。

    NODE_PREFIX (default: "AST")

    在多模式中,前缀用来从节点标志符构造节点类名字。默认前缀为 AST

    NODE_SCOPE_HOOK (default: false)

       在节点作用域入口和出口处插入调用用户自定义的解析方法。参见:节点作用域钩子。

       NODE_USES_PARSER (default: false)

       JJTree会使用一个选择的形式将解析对象传给构造函数。例如:

  public static Node MyNode.jjtCreate(MyParser p, int id);

        MyNode(MyParser p, int id);

       STATIC (default: true)

       为静态解析器生成代码。选项默认为True。这必须一致的通过等效的JavaCC选项被使用。选项的值发布于JavaCC的源码中。

       VISITOR (default: false)

       在节点类中插入jjtAccept()方法,为语法中使用的每个节点类型产生一个访问者实现。

VISITOR_EXCEPTION (default: "")

       如果这个选项被设置,它将使用jjtAccept()visit()方法的形式。注意:这个选项将会在以后的某个JJTree版本中删除。如果不影响你请不要使用它。

       JJTREE_OUTPUT_DIRECTORY (default: use value of OUTPUT_DIRECTORY)

       默认情况下,在全局OUTPUT_DIRECTORY设置中指定JJTree生成的输出目录。明确的设置这个选项允许用户从树文件中分离解析器。

 

JJTree 状态

       JJTree通过解析器对象中的jjtree字段保持它的状态。你可以使用它的一些方法来操作节点堆栈。

      final class JJTreeState {
      /* Call this to reinitialize the node stack.  */
      void reset();

  
  
   
    
  
  
      /* Return the root node of the AST. */
      Node rootNode();

  
  
   
    
  
  
      /* Determine whether the current node was actually closed and
         pushed */
      boolean nodeCreated();

  
  
   
    
  
  
      /* Return the number of nodes currently pushed on the node
         stack in the current node scope. */
      int arity();

  
  
   
    
  
  
      /* Push a node on to the stack. */
      void pushNode(Node n);

  
  
   
    
  
  
      /* Return the node on the top of the stack, and remove it from the
         stack.  */
      Node popNode();

  
  
   
    
  
  
      /* Return the node currently on the top of the stack. */
      Node peekNode();
     }

 

节点对象

       所有的AST节点必须实现这个接口。它为构建节点间父子关系提供了基本的操作。

        public interface Node {
      /** This method is called after the node has been made the current
        node.  It indicates that child nodes can now be added to it. */
      public void jjtOpen();

  
  
   
    
  
  
      /** This method is called after all the child nodes have been
        added. */
      public void jjtClose();

  
  
   
    
  
  
      /** This pair of methods are used to inform the node of its
        parent. */
      public void jjtSetParent(Node n);
      public Node jjtGetParent();

  
  
   
    
  
  
      /** This method tells the node to add its argument to the node's
        list of children.  */
      public void jjtAddChild(Node n, int i);

  
  
   
    
  
  
      /** This method returns a child node.  The children are numbered
         from zero, left to right. */
      public Node jjtGetChild(int i);

  
  
   
    
  
  
      /** Return the number of children the node has. */
      int jjtGetNumChildren();
    }

       SimpleNode类实现了Node接口,如果他不存在,那么JJTree会自动生成。你可以把这个类作为你自己节点实现的一个模板或者超类,或者你可以修改它以适应需求。SimpleNode为递归清理的节点和它的字节点额外提供了一个根本操作。你可以像这样的行为使用:

        {
            ((SimpleNode)jjtree.rootNode()).dump(">");
        }

方法dump()的字符串参数被添加以暗示树的层级。

    如果VISITOR选项被设置,那么另一个有效的方法被生成:

        {
           public void childrenAccept(MyParserVisitor visitor);
        }

       它轮流遍历节点的子节点,要求他们接受访问者。这对preorder and postorder[前序和后续]遍历可能是有用的。

 

例子

       JJTree发布了一些单一模式的例子其中包含解析数学表达式的文法。更多详细信息参见examples/JJTreeExamples/README

       还有一个利用JJTree构建的解释单一语言的程序解释器。更多详细信息参见examples/Interpreter/README

       一个关于HTML 3.2的文法也被发布了。更多信息参见examples/HTMLGrammars/RobsHTML/README

    一个使用访问者支持的例子的信息请参见examples/VTransformer/README

------------如下是英文原文---------------------------

JavaCC [tm]: JJTree Reference Documentation

Introduction

JJTree is a preprocessor for JavaCC [tm] that inserts parse tree building actions at various places in the JavaCC source. The output of JJTree is run through JavaCC to create the parser. This document describes how to use JJTree, and how you can interface your parser to it.

By default JJTree generates code to construct parse tree nodes for each nonterminal in the language. This behavior can be modified so that some nonterminals do not have nodes generated, or so that a node is generated for a part of a production's expansion.

JJTree defines a Java interface Node that all parse tree nodes must implement. The interface provides methods for operations such as setting the parent of the node, and for adding children and retrieving them.

JJTree operates in one of two modes, simple and multi (for want of better terms). In simple mode each parse tree node is of concrete type SimpleNode; in multi mode the type of the parse tree node is derived from the name of the node. If you don't provide implementations for the node classes JJTree will generate sample implementations based on SimpleNode for you. You can then modify the implementations to suit.

Although JavaCC is a top-down parser, JJTree constructs the parse tree from the bottom up. To do this it uses a stack where it pushes nodes after they have been created. When it finds a parent for them, it pops the children from the stack and adds them to the parent, and finally pushes the new parent node itself. The stack is open, which means that you have access to it from within grammar actions: you can push, pop and otherwise manipulate its contents however you feel appropriate. See Node Scopes and User Actions below for more important information.

JJTree provides decorations for two basic varieties of nodes, and some syntactic shorthand to make their use convenient.

  1. A definite node is constructed with a specific number of children. That many nodes are popped from the stack and made the children of the new node, which is then pushed on the stack itself. You notate a definite node like this:

    #ADefiniteNode(INTEGER EXPRESSION)

    A definite node descriptor expression can be any integer expression, although literal integer constants are by far the most common expressions.

  2. A conditional node is constructed with all of the children that were pushed on the stack within its node scope if and only if its condition evaluates to true. If it evaluates to false, the node is not constructed, and all of the children remain on the node stack. You notate a conditional node like this:

    #ConditionalNode(BOOLEAN EXPRESSION)

    A conditional node descriptor expression can be any boolean expression. There are two common shorthands for conditional nodes:

    1. Indefinite nodes

      #IndefiniteNode is short for #IndefiniteNode(true)

    2. Greater-than nodes

      #GTNode(>1) is short for #GTNode(jjtree.arity() > 1)

    The indefinite node shorthand (1) can lead to ambiguities in the JJTree source when it is followed by a parenthesized expansion. In those cases the shorthand must be replaced by the full expression. For example:

    	  ( ... ) #N ( a() ) 

    is ambiguous; you have to use the explicit condition:

     ( ... ) #N(true) ( a()
    	  ) 

WARNING: node descriptor expression should not have side-effects. JJTree doesn't specify how many times the expression will be evaluated.

By default JJTree treats each nonterminal as an indefinite node and derives the name of the node from the name of its production. You can give it a different name with the following syntax:

    void P1() #MyNode : { ... } { ... }
	  

When the parser recognizes a P1 nonterminal it begins an indefinite node. It marks the stack, so that any parse tree nodes created and pushed on the stack by nonterminals in the expansion for P1 will be popped off and made children of the node MyNode.

If you want to suppress the creation of a node for a production you can use the following syntax:

    void P2() #void : { ... } { ... }
	  

Now any parse tree nodes pushed by nonterminals in the expansion of P2 will remain on the stack, to be popped and made children of a production further up the tree. You can make this the default behavior for non-decorated nodes by using the NODE_DEFAULT_VOID option.

    
    void P3() : {}
    {
        P4() ( P5() )+ P6()
    }
    

In this example, an indefinite node P3 is begun, marking the stack, and then a P4 node, one or more P5 nodes and a P6 node are parsed. Any nodes that they push are popped and made the children of P3. You can further customize the generated tree:

    void P3() : {}
    {
        P4() ( P5() )+ #ListOfP5s P6()
    }
    

Now the P3 node will have a P4 node, a ListOfP5s node and a P6 node as children. The #Name construct acts as a postfix operator, and its scope is the immediately preceding expansion unit.

Node Scopes and User Actions

Each node is associated with a node scope. User actions within this scope can access the node under construction by using the special identifier jjtThis to refer to the node. This identifier is implicitly declared to be of the correct type for the node, so any fields and methods that the node has can be easily accessed.

A scope is the expansion unit immediately preceding the node decoration. This can be a parenthesized expression. When the production signature is decorated (perhaps implicitly with the default node), the scope is the entire right hand side of the production including its declaration block.

You can also use an expression involving jjtThis on the left hand side of an expansion reference. For example:

    ... ( jjtThis.my_foo = foo() ) #Baz ...
	  

Here jjtThis refers to a Baz node, which has a field called my_foo. The result of parsing the production foo() is assigned to that my_foo.

The final user action in a node scope is different from all the others. When the code within it executes, the node's children have already been popped from the stack and added to the node, which has itself been pushed onto the stack. The children can now be accessed via the node's methods such as jjtGetChild().

User actions other than the final one can only access the children on the stack. They have not yet been added to the node, so they aren't available via the node's methods.

A conditional node that has a node descriptor expression that evaluates to false will not get added to the stack, nor have children added to it. The final user action within a conditional node scope can determine whether the node was created or not by calling the nodeCreated() method. This returns true if the node's condition was satisfied and the node was created and pushed on the node stack, and false otherwise.

Exception handling

An exception thrown by an expansion within a node scope that is not caught within the node scope is caught by JJTree itself. When this occurs, any nodes that have been pushed on to the node stack within the node scope are popped and thrown away. Then the exception is rethrown.

The intention is to make it possible for parsers to implement error recovery and continue with the node stack in a known state.

WARNING: JJTree currently cannot detect whether exceptions are thrown from user actions within a node scope. Such an exception will probably be handled incorrectly.

Node Scope Hooks

If the NODE_SCOPE_HOOK option is set to true, JJTree generates calls to two user-defined parser methods on the entry and exit of every node scope. The methods must have the following signatures:

    void jjtreeOpenNodeScope(Node n)
    void jjtreeCloseNodeScope(Node n)
    

If the parser is STATIC then these methods will have to be declared as static as well. They are both called with the current node as a parameter.

One use for these functions is to store the node's first and last tokens so that the input can be easily reproduced again. For example:

    void jjtreeOpenNodeScope(Node n)
    {
      ((MySimpleNode)n).first_token = getToken(1);
    }

    void jjtreeCloseNodeScope(Node n)
    {
      ((MySimpleNode)n).last_token = getToken(0);
    }
    

where MySimpleNode is based on SimpleNode and has the following additional fields:

    Token first_token, last_token;
    

Another use might be to store the parser object itself in the node so that state that should be shared by all nodes produced by that parser can be provided. For example, the parser might maintain a symbol table.

The Life Cycle of a Node

A node goes through a well determined sequence of steps as it is built. This is that sequence viewed from the perspective of the node itself:

  1. the node's constructor is called with a unique integer parameter. This parameter identifies the kind of node and is especially useful in simple mode. JJTree automatically generates a file called parserTreeConstants.java that declares valid constants. The names of constants are derived by prepending JJT to the uppercase names of nodes, with dot symbols (".") replaced by underscore symbols ("_"). For convenience, an array of Strings called jjtNodeName[] that maps the constants to the unmodified names of nodes is maintained in the same file.
  2. the node's jjtOpen() method is called.
  3. if the option NODE_SCOPE_HOOK is set, the user-defined parser method openNodeScope() is called and passed the node as its parameter. This method can initialize fields in the node or call its methods. For example, it might store the node's first token in the node.
  4. if an unhandled exception is thrown while the node is being parsed then the node is abandoned. JJTree will never refer to it again. It will not be closed, and the user-defined node scope hook closeNodeHook() will not be called with it as a parameter.
  5. otherwise, if the node is conditional and its conditional expression evaluates to false then the node is abandoned. It will not be closed, although the user-defined node scope hook closeNodeHook() might be called with it as a parameter.
  6. otherwise, all of the children of the node as specified by the integer expression of a definite node, or all the nodes that were pushed on the stack within a conditional node scope are added to the node. The order they are added is not specified.
  7. the node's jjtClose() method is called.
  8. the node is pushed on the stack.
  9. if the option NODE_SCOPE_HOOK is set, the user-defined parser method closenNodeScope() is called and passed the node as its parameter.
  10. if the node is not the root node, it is added as a child of another node and its jjtSetParent() method is called.

Visitor Support

JJTree provides some basic support for the visitor design pattern. If the VISITOR option is set to true JJTree will insert an jjtAccept() method into all of the node classes it generates, and also generate a visitor interface that can be implemented and passed to the nodes to accept.

The name of the visitor interface is constructed by appending Visitor to the name of the parser. The interface is regenerated every time that JJTree is run, so that it accurately represents the set of nodes used by the parser. This will cause compile time errors if the implementation class has not been updated for the new nodes. This is a feature.

Options

JJTree supports the following options on the command line and in the JavaCC options statement:

BUILD_NODE_FILES (default: true)
Generate sample implementations for SimpleNode and any other nodes used in the grammar.
MULTI (default: false)
Generate a multi mode parse tree. The default for this is false, generating a simple mode parse tree.
NODE_DEFAULT_VOID (default: false)
Instead of making each non-decorated production an indefinite node, make it void instead.
NODE_FACTORY (default: false)
Use a factory method with following signature to construct nodes:
public static Node jjtCreate(int id)
NODE_PACKAGE (default: "")
The package to generate the node classes into. The default for this is the parser package.
NODE_PREFIX (default: "AST")
The prefix used to construct node class names from node identifiers in multi mode. The default for this is AST.
NODE_SCOPE_HOOK (default: false)
Insert calls to user-defined parser methods on entry and exit of every node scope. See Node Scope Hooks above.
NODE_USES_PARSER (default: false)
JJTree will use an alternate form of the node construction routines where it passes the parser object in. For example,
 public static Node MyNode.jjtCreate(MyParser p, int id);
	  MyNode(MyParser p, int id); 
STATIC (default: true)
Generate code for a static parser. The default for this is true. This must be used consistently with the equivalent JavaCC options. The value of this option is emitted in the JavaCC source.
VISITOR (default: false)
Insert a jjtAccept() method in the node classes, and generate a visitor implementation with an entry for every node type used in the grammar.
VISITOR_EXCEPTION (default: "")
If this option is set, it is used in the signature of the generated jjtAccept() methods and the visit() methods. Note: this option will be removed in a later version of JJTree. Don't use it if that bothers you.
JJTREE_OUTPUT_DIRECTORY (default: use value of OUTPUT_DIRECTORY)
By default, JJTree generates its output in the directory specified in the global OUTPUT_DIRECTORY setting. Explicitly setting this option allows the user to separate the parser from the tree files.

JJTree state

JJTree keeps its state in a parser class field called jjtree. You can use methods in this member to manipulate the node stack.

    final class JJTreeState {
      /* Call this to reinitialize the node stack.  */
      void reset();

      /* Return the root node of the AST. */
      Node rootNode();

      /* Determine whether the current node was actually closed and
	 pushed */
      boolean nodeCreated();

      /* Return the number of nodes currently pushed on the node
         stack in the current node scope. */
      int arity();

      /* Push a node on to the stack. */
      void pushNode(Node n);

      /* Return the node on the top of the stack, and remove it from the
	 stack.  */
      Node popNode();

      /* Return the node currently on the top of the stack. */
      Node peekNode();
    }
    

Node Objects

    /* All AST nodes must implement this interface.  It provides basic
       machinery for constructing the parent and child relationships
       between nodes. */

    public interface Node {
      /** This method is called after the node has been made the current
	node.  It indicates that child nodes can now be added to it. */
      public void jjtOpen();

      /** This method is called after all the child nodes have been
	added. */
      public void jjtClose();

      /** This pair of methods are used to inform the node of its
	parent. */
      public void jjtSetParent(Node n);
      public Node jjtGetParent();

      /** This method tells the node to add its argument to the node's
	list of children.  */
      public void jjtAddChild(Node n, int i);

      /** This method returns a child node.  The children are numbered
	 from zero, left to right. */
      public Node jjtGetChild(int i);

      /** Return the number of children the node has. */
      int jjtGetNumChildren();
    }
    

The class SimpleNode implements the Node interface, and is automatically generated by JJTree if it doesn't already exist. You can use this class as a template or superclass for your node implementations, or you can modify it to suit. SimpleNode additionally provides a rudimentary mechanism for recursively dumping the node and its children. You might use this is in action like this:

    
    {
        ((SimpleNode)jjtree.rootNode()).dump(">");
    }

    

The String parameter to dump() is used as padding to indicate the tree hierarchy.

Another utility method is generated if the VISITOR options is set:

    {
        public void childrenAccept(MyParserVisitor visitor);
    }
    

This walks over the node's children in turn, asking them to accept the visitor. This can be useful when implementing preorder and postorder traversals.

Examples

JJTree is distributed with some simple examples containing a grammar that parses arithmetic expressions. See the file examples/JJTreeExamples/README for further details.

There is also an interpreter for a simple language that uses JJTree to build the program representation. See the file examples/Interpreter/README for more information.

A grammar for HTML 3.2 is also included in the distribution. See examples/HTMLGrammars/RobsHTML/README to find out more.

Information about an example using the visitor support is in examples/VTransformer/README.

 

本人英文水平太差,就当学习了,希望大家支持。

 

       

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值