PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/runtime/Java/src/main/java/org/antlr/runtime/tree/BufferedTreeNodeStream.java

https://bitbucket.org/jwalton/antlr3
Java | 500 lines | 327 code | 53 blank | 120 comment | 51 complexity | 551df2424ce5cb3ac6030e8f32264e1f MD5 | raw file
  1. /*
  2. [The "BSD license"]
  3. Copyright (c) 2005-2009 Terence Parr
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions
  7. are met:
  8. 1. Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. 3. The name of the author may not be used to endorse or promote products
  14. derived from this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. package org.antlr.runtime.tree;
  27. import org.antlr.runtime.Token;
  28. import org.antlr.runtime.TokenStream;
  29. import org.antlr.runtime.misc.IntArray;
  30. import java.util.*;
  31. /** A buffered stream of tree nodes. Nodes can be from a tree of ANY kind.
  32. *
  33. * This node stream sucks all nodes out of the tree specified in
  34. * the constructor during construction and makes pointers into
  35. * the tree using an array of Object pointers. The stream necessarily
  36. * includes pointers to DOWN and UP and EOF nodes.
  37. *
  38. * This stream knows how to mark/release for backtracking.
  39. *
  40. * This stream is most suitable for tree interpreters that need to
  41. * jump around a lot or for tree parsers requiring speed (at cost of memory).
  42. * There is some duplicated functionality here with UnBufferedTreeNodeStream
  43. * but just in bookkeeping, not tree walking etc...
  44. *
  45. * TARGET DEVELOPERS:
  46. *
  47. * This is the old CommonTreeNodeStream that buffered up entire node stream.
  48. * No need to implement really as new CommonTreeNodeStream is much better
  49. * and covers what we need.
  50. *
  51. * @see CommonTreeNodeStream
  52. */
  53. public class BufferedTreeNodeStream implements TreeNodeStream {
  54. public static final int DEFAULT_INITIAL_BUFFER_SIZE = 100;
  55. public static final int INITIAL_CALL_STACK_SIZE = 10;
  56. protected class StreamIterator implements Iterator<Object> {
  57. int i = 0;
  58. @Override
  59. public boolean hasNext() {
  60. return i<nodes.size();
  61. }
  62. @Override
  63. public Object next() {
  64. int current = i;
  65. i++;
  66. if ( current < nodes.size() ) {
  67. return nodes.get(current);
  68. }
  69. return eof;
  70. }
  71. @Override
  72. public void remove() {
  73. throw new RuntimeException("cannot remove nodes from stream");
  74. }
  75. }
  76. // all these navigation nodes are shared and hence they
  77. // cannot contain any line/column info
  78. protected Object down;
  79. protected Object up;
  80. protected Object eof;
  81. /** The complete mapping from stream index to tree node.
  82. * This buffer includes pointers to DOWN, UP, and EOF nodes.
  83. * It is built upon ctor invocation. The elements are type
  84. * Object as we don't what the trees look like.
  85. *
  86. * Load upon first need of the buffer so we can set token types
  87. * of interest for reverseIndexing. Slows us down a wee bit to
  88. * do all of the if p==-1 testing everywhere though.
  89. */
  90. protected List<Object> nodes;
  91. /** Pull nodes from which tree? */
  92. protected Object root;
  93. /** IF this tree (root) was created from a token stream, track it. */
  94. protected TokenStream tokens;
  95. /** What tree adaptor was used to build these trees */
  96. TreeAdaptor adaptor;
  97. /** Reuse same DOWN, UP navigation nodes unless this is true */
  98. protected boolean uniqueNavigationNodes = false;
  99. /** The index into the nodes list of the current node (next node
  100. * to consume). If -1, nodes array not filled yet.
  101. */
  102. protected int p = -1;
  103. /** Track the last mark() call result value for use in rewind(). */
  104. protected int lastMarker;
  105. /** Stack of indexes used for push/pop calls */
  106. protected IntArray calls;
  107. public BufferedTreeNodeStream(Object tree) {
  108. this(new CommonTreeAdaptor(), tree);
  109. }
  110. public BufferedTreeNodeStream(TreeAdaptor adaptor, Object tree) {
  111. this(adaptor, tree, DEFAULT_INITIAL_BUFFER_SIZE);
  112. }
  113. public BufferedTreeNodeStream(TreeAdaptor adaptor, Object tree, int initialBufferSize) {
  114. this.root = tree;
  115. this.adaptor = adaptor;
  116. nodes = new ArrayList<Object>(initialBufferSize);
  117. down = adaptor.create(Token.DOWN, "DOWN");
  118. up = adaptor.create(Token.UP, "UP");
  119. eof = adaptor.create(Token.EOF, "EOF");
  120. }
  121. /** Walk tree with depth-first-search and fill nodes buffer.
  122. * Don't do DOWN, UP nodes if its a list (t is isNil).
  123. */
  124. protected void fillBuffer() {
  125. fillBuffer(root);
  126. //System.out.println("revIndex="+tokenTypeToStreamIndexesMap);
  127. p = 0; // buffer of nodes intialized now
  128. }
  129. public void fillBuffer(Object t) {
  130. boolean nil = adaptor.isNil(t);
  131. if ( !nil ) {
  132. nodes.add(t); // add this node
  133. }
  134. // add DOWN node if t has children
  135. int n = adaptor.getChildCount(t);
  136. if ( !nil && n>0 ) {
  137. addNavigationNode(Token.DOWN);
  138. }
  139. // and now add all its children
  140. for (int c=0; c<n; c++) {
  141. Object child = adaptor.getChild(t,c);
  142. fillBuffer(child);
  143. }
  144. // add UP node if t has children
  145. if ( !nil && n>0 ) {
  146. addNavigationNode(Token.UP);
  147. }
  148. }
  149. /** What is the stream index for node? 0..n-1
  150. * Return -1 if node not found.
  151. */
  152. protected int getNodeIndex(Object node) {
  153. if ( p==-1 ) {
  154. fillBuffer();
  155. }
  156. for (int i = 0; i < nodes.size(); i++) {
  157. Object t = nodes.get(i);
  158. if ( t==node ) {
  159. return i;
  160. }
  161. }
  162. return -1;
  163. }
  164. /** As we flatten the tree, we use UP, DOWN nodes to represent
  165. * the tree structure. When debugging we need unique nodes
  166. * so instantiate new ones when uniqueNavigationNodes is true.
  167. */
  168. protected void addNavigationNode(final int ttype) {
  169. Object navNode;
  170. if ( ttype==Token.DOWN ) {
  171. if ( hasUniqueNavigationNodes() ) {
  172. navNode = adaptor.create(Token.DOWN, "DOWN");
  173. }
  174. else {
  175. navNode = down;
  176. }
  177. }
  178. else {
  179. if ( hasUniqueNavigationNodes() ) {
  180. navNode = adaptor.create(Token.UP, "UP");
  181. }
  182. else {
  183. navNode = up;
  184. }
  185. }
  186. nodes.add(navNode);
  187. }
  188. @Override
  189. public Object get(int i) {
  190. if ( p==-1 ) {
  191. fillBuffer();
  192. }
  193. return nodes.get(i);
  194. }
  195. @Override
  196. public Object LT(int k) {
  197. if ( p==-1 ) {
  198. fillBuffer();
  199. }
  200. if ( k==0 ) {
  201. return null;
  202. }
  203. if ( k<0 ) {
  204. return LB(-k);
  205. }
  206. //System.out.print("LT(p="+p+","+k+")=");
  207. if ( (p+k-1) >= nodes.size() ) {
  208. return eof;
  209. }
  210. return nodes.get(p+k-1);
  211. }
  212. public Object getCurrentSymbol() { return LT(1); }
  213. /*
  214. public Object getLastTreeNode() {
  215. int i = index();
  216. if ( i>=size() ) {
  217. i--; // if at EOF, have to start one back
  218. }
  219. System.out.println("start last node: "+i+" size=="+nodes.size());
  220. while ( i>=0 &&
  221. (adaptor.getType(get(i))==Token.EOF ||
  222. adaptor.getType(get(i))==Token.UP ||
  223. adaptor.getType(get(i))==Token.DOWN) )
  224. {
  225. i--;
  226. }
  227. System.out.println("stop at node: "+i+" "+nodes.get(i));
  228. return nodes.get(i);
  229. }
  230. */
  231. /** Look backwards k nodes */
  232. protected Object LB(int k) {
  233. if ( k==0 ) {
  234. return null;
  235. }
  236. if ( (p-k)<0 ) {
  237. return null;
  238. }
  239. return nodes.get(p-k);
  240. }
  241. @Override
  242. public Object getTreeSource() {
  243. return root;
  244. }
  245. @Override
  246. public String getSourceName() {
  247. return getTokenStream().getSourceName();
  248. }
  249. @Override
  250. public TokenStream getTokenStream() {
  251. return tokens;
  252. }
  253. public void setTokenStream(TokenStream tokens) {
  254. this.tokens = tokens;
  255. }
  256. @Override
  257. public TreeAdaptor getTreeAdaptor() {
  258. return adaptor;
  259. }
  260. public void setTreeAdaptor(TreeAdaptor adaptor) {
  261. this.adaptor = adaptor;
  262. }
  263. public boolean hasUniqueNavigationNodes() {
  264. return uniqueNavigationNodes;
  265. }
  266. @Override
  267. public void setUniqueNavigationNodes(boolean uniqueNavigationNodes) {
  268. this.uniqueNavigationNodes = uniqueNavigationNodes;
  269. }
  270. @Override
  271. public void consume() {
  272. if ( p==-1 ) {
  273. fillBuffer();
  274. }
  275. p++;
  276. }
  277. @Override
  278. public int LA(int i) {
  279. return adaptor.getType(LT(i));
  280. }
  281. @Override
  282. public int mark() {
  283. if ( p==-1 ) {
  284. fillBuffer();
  285. }
  286. lastMarker = index();
  287. return lastMarker;
  288. }
  289. @Override
  290. public void release(int marker) {
  291. // no resources to release
  292. }
  293. @Override
  294. public int index() {
  295. return p;
  296. }
  297. @Override
  298. public void rewind(int marker) {
  299. seek(marker);
  300. }
  301. @Override
  302. public void rewind() {
  303. seek(lastMarker);
  304. }
  305. @Override
  306. public void seek(int index) {
  307. if ( p==-1 ) {
  308. fillBuffer();
  309. }
  310. p = index;
  311. }
  312. /** Make stream jump to a new location, saving old location.
  313. * Switch back with pop().
  314. */
  315. public void push(int index) {
  316. if ( calls==null ) {
  317. calls = new IntArray();
  318. }
  319. calls.push(p); // save current index
  320. seek(index);
  321. }
  322. /** Seek back to previous index saved during last push() call.
  323. * Return top of stack (return index).
  324. */
  325. public int pop() {
  326. int ret = calls.pop();
  327. seek(ret);
  328. return ret;
  329. }
  330. @Override
  331. public void reset() {
  332. p = 0;
  333. lastMarker = 0;
  334. if (calls != null) {
  335. calls.clear();
  336. }
  337. }
  338. @Override
  339. public int size() {
  340. if ( p==-1 ) {
  341. fillBuffer();
  342. }
  343. return nodes.size();
  344. }
  345. public Iterator<Object> iterator() {
  346. if ( p==-1 ) {
  347. fillBuffer();
  348. }
  349. return new StreamIterator();
  350. }
  351. // TREE REWRITE INTERFACE
  352. @Override
  353. public void replaceChildren(Object parent, int startChildIndex, int stopChildIndex, Object t) {
  354. if ( parent!=null ) {
  355. adaptor.replaceChildren(parent, startChildIndex, stopChildIndex, t);
  356. }
  357. }
  358. /** Used for testing, just return the token type stream */
  359. public String toTokenTypeString() {
  360. if ( p==-1 ) {
  361. fillBuffer();
  362. }
  363. StringBuilder buf = new StringBuilder();
  364. for (int i = 0; i < nodes.size(); i++) {
  365. Object t = nodes.get(i);
  366. buf.append(" ");
  367. buf.append(adaptor.getType(t));
  368. }
  369. return buf.toString();
  370. }
  371. /** Debugging */
  372. public String toTokenString(int start, int stop) {
  373. if ( p==-1 ) {
  374. fillBuffer();
  375. }
  376. StringBuilder buf = new StringBuilder();
  377. for (int i = start; i < nodes.size() && i <= stop; i++) {
  378. Object t = nodes.get(i);
  379. buf.append(" ");
  380. buf.append(adaptor.getToken(t));
  381. }
  382. return buf.toString();
  383. }
  384. @Override
  385. public String toString(Object start, Object stop) {
  386. System.out.println("toString");
  387. if ( start==null || stop==null ) {
  388. return null;
  389. }
  390. if ( p==-1 ) {
  391. fillBuffer();
  392. }
  393. //System.out.println("stop: "+stop);
  394. if ( start instanceof CommonTree )
  395. System.out.print("toString: "+((CommonTree)start).getToken()+", ");
  396. else
  397. System.out.println(start);
  398. if ( stop instanceof CommonTree )
  399. System.out.println(((CommonTree)stop).getToken());
  400. else
  401. System.out.println(stop);
  402. // if we have the token stream, use that to dump text in order
  403. if ( tokens!=null ) {
  404. int beginTokenIndex = adaptor.getTokenStartIndex(start);
  405. int endTokenIndex = adaptor.getTokenStopIndex(stop);
  406. // if it's a tree, use start/stop index from start node
  407. // else use token range from start/stop nodes
  408. if ( adaptor.getType(stop)==Token.UP ) {
  409. endTokenIndex = adaptor.getTokenStopIndex(start);
  410. }
  411. else if ( adaptor.getType(stop)==Token.EOF ) {
  412. endTokenIndex = size()-2; // don't use EOF
  413. }
  414. return tokens.toString(beginTokenIndex, endTokenIndex);
  415. }
  416. // walk nodes looking for start
  417. Object t;
  418. int i = 0;
  419. for (; i < nodes.size(); i++) {
  420. t = nodes.get(i);
  421. if ( t==start ) {
  422. break;
  423. }
  424. }
  425. // now walk until we see stop, filling string buffer with text
  426. StringBuilder buf = new StringBuilder();
  427. t = nodes.get(i);
  428. while ( t!=stop ) {
  429. String text = adaptor.getText(t);
  430. if ( text==null ) {
  431. text = " "+String.valueOf(adaptor.getType(t));
  432. }
  433. buf.append(text);
  434. i++;
  435. t = nodes.get(i);
  436. }
  437. // include stop node too
  438. String text = adaptor.getText(stop);
  439. if ( text==null ) {
  440. text = " "+String.valueOf(adaptor.getType(stop));
  441. }
  442. buf.append(text);
  443. return buf.toString();
  444. }
  445. }