00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 package org.antlr.runtime.misc;
00029
00030 import org.antlr.runtime.Token;
00031
00032 import java.util.NoSuchElementException;
00033
00039 public abstract class LookaheadStream<T> extends FastQueue<T> {
00040 public static final int UNINITIALIZED_EOF_ELEMENT_INDEX = Integer.MAX_VALUE;
00041
00045 protected int currentElementIndex = 0;
00046
00047 protected T prevElement;
00048
00052 public T eof = null;
00053
00055 protected int lastMarker;
00056
00058 protected int markDepth = 0;
00059
00060 public void reset() {
00061 super.reset();
00062 currentElementIndex = 0;
00063 p = 0;
00064 prevElement=null;
00065 }
00066
00070 public abstract T nextElement();
00071
00072 public abstract boolean isEOF(T o);
00073
00077 public T remove() {
00078 T o = elementAt(0);
00079 p++;
00080
00081 if ( p == data.size() && markDepth==0 ) {
00082
00083 clear();
00084 }
00085 return o;
00086 }
00087
00089 public void consume() {
00090 syncAhead(1);
00091 prevElement = remove();
00092 currentElementIndex++;
00093 }
00094
00099 protected void syncAhead(int need) {
00100 int n = (p+need-1) - data.size() + 1;
00101 if ( n > 0 ) fill(n);
00102 }
00103
00105 public void fill(int n) {
00106 for (int i=1; i<=n; i++) {
00107 T o = nextElement();
00108 if ( isEOF(o) ) eof = o;
00109 data.add(o);
00110 }
00111 }
00112
00114 public int size() { throw new UnsupportedOperationException("streams are of unknown size"); }
00115
00116 public T LT(int k) {
00117 if ( k==0 ) {
00118 return null;
00119 }
00120 if ( k<0 ) return LB(-k);
00121
00122 syncAhead(k);
00123 if ( (p+k-1) > data.size() ) return eof;
00124 return elementAt(k-1);
00125 }
00126
00127 public int index() { return currentElementIndex; }
00128
00129 public int mark() {
00130 markDepth++;
00131 lastMarker = p;
00132 return lastMarker;
00133 }
00134
00135 public void release(int marker) {
00136
00137 }
00138
00139 public void rewind(int marker) {
00140 markDepth--;
00141 seek(marker);
00142
00143 }
00144
00145 public void rewind() {
00146 seek(lastMarker);
00147 }
00148
00155 public void seek(int index) { p = index; }
00156
00157 protected T LB(int k) {
00158 if ( k==1 ) return prevElement;
00159 throw new NoSuchElementException("can't look backwards more than one token in this stream");
00160 }
00161 }