KickJava   Java API By Example, From Geeks To Geeks.

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


1 // $Id: ASTIterator.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 ASTIterator implements Iterator JavaDoc {
15     private AST next, current;
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 ASTIterator(AST tree) {
31         next = tree;
32         down();
33     }
34
35     public AST nextNode() {
36         current = next;
37         if ( next != null ) {
38             AST nextSibling = next.getNextSibling();
39             if ( nextSibling == null ) {
40                 next = pop();
41             }
42             else {
43                 next = nextSibling;
44                 down();
45             }
46         }
47         return current;
48     }
49
50     private void down() {
51         while ( next != null && next.getFirstChild() != null ) {
52             push( next );
53             next = next.getFirstChild();
54         }
55     }
56
57     private void push(AST parent) {
58         parents.addFirst( parent );
59     }
60
61     private AST pop() {
62         if ( parents.size() == 0 ) {
63             return null;
64         }
65         else {
66             return ( AST ) parents.removeFirst();
67         }
68     }
69
70 }
71
Popular Tags