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