KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > hql > ast > util > ASTParentsFirstIterator


1 // $Id: ASTParentsFirstIterator.java,v 1.1 2005/07/12 20:27:17 steveebersole Exp $
2
package org.hibernate.hql.ast.util;
3
4 import java.util.Iterator JavaDoc;
5 import java.util.LinkedList JavaDoc;
6
7 import antlr.collections.AST;
8
9 /**
10  * Depth first iteration of an ANTLR AST.
11  *
12  * @author josh Sep 25, 2004 7:44:39 AM
13  */

14 public class ASTParentsFirstIterator implements Iterator JavaDoc {
15     private AST next, current, tree;
16     private LinkedList JavaDoc parents = new LinkedList JavaDoc();
17
18     public void remove() {
19         throw new UnsupportedOperationException JavaDoc( "remove() is not supported" );
20     }
21
22     public boolean hasNext() {
23         return next != null;
24     }
25
26     public Object JavaDoc next() {
27         return nextNode();
28     }
29
30     public ASTParentsFirstIterator(AST tree) {
31         this.tree = next = tree;
32     }
33
34     public AST nextNode() {
35         current = next;
36         if ( next != null ) {
37             AST child = next.getFirstChild();
38             if ( child == null ) {
39                 AST sibling = next.getNextSibling();
40                 if ( sibling == null ) {
41                     AST parent = pop();
42                     while ( parent != null && parent.getNextSibling() == null )
43                         parent = pop();
44                     next = ( parent != null ) ? parent.getNextSibling() : null;
45                 }
46                 else {
47                     next = sibling;
48                 }
49             }
50             else {
51                 if ( next != tree ) {
52                     push( next );
53                 }
54                 next = child;
55             }
56         }
57         return current;
58     }
59
60     private void push(AST parent) {
61         parents.addFirst( parent );
62     }
63
64     private AST pop() {
65         if ( parents.size() == 0 ) {
66             return null;
67         }
68         else {
69             return ( AST ) parents.removeFirst();
70         }
71     }
72
73 }
74
Popular Tags