1/*
2 [The "BSD license"]
3 Copyright (c) 2005-2009 Terence Parr
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 1. Redistributions of source code must retain the above copyright
10     notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright
12     notice, this list of conditions and the following disclaimer in the
13     documentation and/or other materials provided with the distribution.
14 3. The name of the author may not be used to endorse or promote products
15     derived from this software without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28package org.antlr.runtime.misc;
29
30import org.antlr.runtime.Token;
31
32import java.util.NoSuchElementException;
33
34/** A lookahead queue that knows how to mark/release locations
35 *  in the buffer for backtracking purposes. Any markers force the FastQueue
36 *  superclass to keep all tokens until no more markers; then can reset
37 *  to avoid growing a huge buffer.
38 */
39public abstract class LookaheadStream<T> extends FastQueue<T> {
40    public static final int UNINITIALIZED_EOF_ELEMENT_INDEX = Integer.MAX_VALUE;
41
42    /** Absolute token index. It's the index of the symbol about to be
43	 *  read via LT(1). Goes from 0 to numtokens.
44     */
45    protected int currentElementIndex = 0;
46
47    protected T prevElement;
48
49    /** Track object returned by nextElement upon end of stream;
50     *  Return it later when they ask for LT passed end of input.
51     */
52    public T eof = null;
53
54    /** Track the last mark() call result value for use in rewind(). */
55    protected int lastMarker;
56
57    /** tracks how deep mark() calls are nested */
58    protected int markDepth = 0;
59
60    public void reset() {
61        super.reset();
62        currentElementIndex = 0;
63        p = 0;
64        prevElement=null;
65    }
66
67    /** Implement nextElement to supply a stream of elements to this
68     *  lookahead buffer.  Return eof upon end of the stream we're pulling from.
69     */
70    public abstract T nextElement();
71
72    public abstract boolean isEOF(T o);
73
74    /** Get and remove first element in queue; override FastQueue.remove();
75     *  it's the same, just checks for backtracking.
76     */
77    public T remove() {
78        T o = elementAt(0);
79        p++;
80        // have we hit end of buffer and not backtracking?
81        if ( p == data.size() && markDepth==0 ) {
82            // if so, it's an opportunity to start filling at index 0 again
83            clear(); // size goes to 0, but retains memory
84        }
85        return o;
86    }
87
88    /** Make sure we have at least one element to remove, even if EOF */
89    public void consume() {
90        syncAhead(1);
91        prevElement = remove();
92        currentElementIndex++;
93    }
94
95    /** Make sure we have 'need' elements from current position p. Last valid
96     *  p index is data.size()-1.  p+need-1 is the data index 'need' elements
97     *  ahead.  If we need 1 element, (p+1-1)==p must be < data.size().
98     */
99    protected void syncAhead(int need) {
100        int n = (p+need-1) - data.size() + 1; // how many more elements we need?
101        if ( n > 0 ) fill(n);                 // out of elements?
102    }
103
104    /** add n elements to buffer */
105    public void fill(int n) {
106        for (int i=1; i<=n; i++) {
107            T o = nextElement();
108            if ( isEOF(o) ) eof = o;
109            data.add(o);
110        }
111    }
112
113    /** Size of entire stream is unknown; we only know buffer size from FastQueue */
114    public int size() { throw new UnsupportedOperationException("streams are of unknown size"); }
115
116    public T LT(int k) {
117		if ( k==0 ) {
118			return null;
119		}
120		if ( k<0 ) return LB(-k);
121		//System.out.print("LT(p="+p+","+k+")=");
122        syncAhead(k);
123        if ( (p+k-1) > data.size() ) return eof;
124        return elementAt(k-1);
125	}
126
127    public int index() { return currentElementIndex; }
128
129	public int mark() {
130        markDepth++;
131        lastMarker = p; // track where we are in buffer not absolute token index
132        return lastMarker;
133	}
134
135	public void release(int marker) {
136		// no resources to release
137	}
138
139	public void rewind(int marker) {
140        markDepth--;
141        seek(marker); // assume marker is top
142        // release(marker); // waste of call; it does nothing in this class
143    }
144
145	public void rewind() {
146        seek(lastMarker); // rewind but do not release marker
147    }
148
149    /** Seek to a 0-indexed position within data buffer.  Can't handle
150     *  case where you seek beyond end of existing buffer.  Normally used
151     *  to seek backwards in the buffer. Does not force loading of nodes.
152     *  Doesn't see to absolute position in input stream since this stream
153     *  is unbuffered. Seeks only into our moving window of elements.
154     */
155    public void seek(int index) { p = index; }
156
157    protected T LB(int k) {
158        if ( k==1 ) return prevElement;
159        throw new NoSuchElementException("can't look backwards more than one token in this stream");
160    }
161}