1 package org.hibernate.hql.ast.util; 3 4 import java.util.Iterator ; 5 import java.util.LinkedList ; 6 7 import antlr.collections.AST; 8 9 14 public class ASTParentsFirstIterator implements Iterator { 15 private AST next, current, tree; 16 private LinkedList parents = new LinkedList (); 17 18 public void remove() { 19 throw new UnsupportedOperationException ( "remove() is not supported" ); 20 } 21 22 public boolean hasNext() { 23 return next != null; 24 } 25 26 public Object 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 |