PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/jwalton/antlr3
Java | 397 lines | 276 code | 33 blank | 88 comment | 53 complexity | d129b1a38332ccc550e53c3543b43467 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 java.util.ArrayList;
  28. import java.util.List;
  29. /** A generic tree implementation with no payload. You must subclass to
  30. * actually have any user data. ANTLR v3 uses a list of children approach
  31. * instead of the child-sibling approach in v2. A flat tree (a list) is
  32. * an empty node whose children represent the list. An empty, but
  33. * non-null node is called "nil".
  34. */
  35. public abstract class BaseTree implements Tree {
  36. protected List<Object> children;
  37. public BaseTree() {
  38. }
  39. /** Create a new node from an existing node does nothing for BaseTree
  40. * as there are no fields other than the children list, which cannot
  41. * be copied as the children are not considered part of this node.
  42. */
  43. public BaseTree(Tree node) {
  44. }
  45. @Override
  46. public Tree getChild(int i) {
  47. if ( children==null || i>=children.size() ) {
  48. return null;
  49. }
  50. return (Tree)children.get(i);
  51. }
  52. /** Get the children internal List; note that if you directly mess with
  53. * the list, do so at your own risk.
  54. */
  55. public List<? extends Object> getChildren() {
  56. return children;
  57. }
  58. public Tree getFirstChildWithType(int type) {
  59. for (int i = 0; children!=null && i < children.size(); i++) {
  60. Tree t = (Tree) children.get(i);
  61. if ( t.getType()==type ) {
  62. return t;
  63. }
  64. }
  65. return null;
  66. }
  67. @Override
  68. public int getChildCount() {
  69. if ( children==null ) {
  70. return 0;
  71. }
  72. return children.size();
  73. }
  74. /** Add t as child of this node.
  75. *
  76. * Warning: if t has no children, but child does
  77. * and child isNil then this routine moves children to t via
  78. * t.children = child.children; i.e., without copying the array.
  79. */
  80. @Override
  81. public void addChild(Tree t) {
  82. //System.out.println("add child "+t.toStringTree()+" "+this.toStringTree());
  83. //System.out.println("existing children: "+children);
  84. if ( t==null ) {
  85. return; // do nothing upon addChild(null)
  86. }
  87. BaseTree childTree = (BaseTree)t;
  88. if ( childTree.isNil() ) { // t is an empty node possibly with children
  89. if ( this.children!=null && this.children == childTree.children ) {
  90. throw new RuntimeException("attempt to add child list to itself");
  91. }
  92. // just add all of childTree's children to this
  93. if ( childTree.children!=null ) {
  94. if ( this.children!=null ) { // must copy, this has children already
  95. int n = childTree.children.size();
  96. for (int i = 0; i < n; i++) {
  97. Tree c = (Tree)childTree.children.get(i);
  98. this.children.add(c);
  99. // handle double-link stuff for each child of nil root
  100. c.setParent(this);
  101. c.setChildIndex(children.size()-1);
  102. }
  103. }
  104. else {
  105. // no children for this but t has children; just set pointer
  106. // call general freshener routine
  107. this.children = childTree.children;
  108. this.freshenParentAndChildIndexes();
  109. }
  110. }
  111. }
  112. else { // child is not nil (don't care about children)
  113. if ( children==null ) {
  114. children = createChildrenList(); // create children list on demand
  115. }
  116. children.add(t);
  117. childTree.setParent(this);
  118. childTree.setChildIndex(children.size()-1);
  119. }
  120. // System.out.println("now children are: "+children);
  121. }
  122. /** Add all elements of kids list as children of this node */
  123. public void addChildren(List<? extends Tree> kids) {
  124. for (int i = 0; i < kids.size(); i++) {
  125. Tree t = kids.get(i);
  126. addChild(t);
  127. }
  128. }
  129. @Override
  130. public void setChild(int i, Tree t) {
  131. if ( t==null ) {
  132. return;
  133. }
  134. if ( t.isNil() ) {
  135. throw new IllegalArgumentException("Can't set single child to a list");
  136. }
  137. if ( children==null ) {
  138. children = createChildrenList();
  139. }
  140. children.set(i, t);
  141. t.setParent(this);
  142. t.setChildIndex(i);
  143. }
  144. /** Insert child t at child position i (0..n-1) by shifting children
  145. i+1..n-1 to the right one position. Set parent / indexes properly
  146. but does NOT collapse nil-rooted t's that come in here like addChild.
  147. */
  148. public void insertChild(int i, Object t) {
  149. if (i < 0 || i >= getChildCount()) {
  150. throw new IndexOutOfBoundsException(i+" out or range");
  151. }
  152. children.add(i, t);
  153. // walk others to increment their child indexes
  154. // set index, parent of this one too
  155. this.freshenParentAndChildIndexes(i);
  156. }
  157. @Override
  158. public Object deleteChild(int i) {
  159. if ( children==null ) {
  160. return null;
  161. }
  162. Tree killed = (Tree)children.remove(i);
  163. // walk rest and decrement their child indexes
  164. this.freshenParentAndChildIndexes(i);
  165. return killed;
  166. }
  167. /** Delete children from start to stop and replace with t even if t is
  168. * a list (nil-root tree). num of children can increase or decrease.
  169. * For huge child lists, inserting children can force walking rest of
  170. * children to set their childindex; could be slow.
  171. */
  172. @Override
  173. public void replaceChildren(int startChildIndex, int stopChildIndex, Object t) {
  174. /*
  175. System.out.println("replaceChildren "+startChildIndex+", "+stopChildIndex+
  176. " with "+((BaseTree)t).toStringTree());
  177. System.out.println("in="+toStringTree());
  178. */
  179. if ( children==null ) {
  180. throw new IllegalArgumentException("indexes invalid; no children in list");
  181. }
  182. int replacingHowMany = stopChildIndex - startChildIndex + 1;
  183. int replacingWithHowMany;
  184. BaseTree newTree = (BaseTree)t;
  185. List<Object> newChildren;
  186. // normalize to a list of children to add: newChildren
  187. if ( newTree.isNil() ) {
  188. newChildren = newTree.children;
  189. }
  190. else {
  191. newChildren = new ArrayList<Object>(1);
  192. newChildren.add(newTree);
  193. }
  194. replacingWithHowMany = newChildren.size();
  195. int numNewChildren = newChildren.size();
  196. int delta = replacingHowMany - replacingWithHowMany;
  197. // if same number of nodes, do direct replace
  198. if ( delta == 0 ) {
  199. int j = 0; // index into new children
  200. for (int i=startChildIndex; i<=stopChildIndex; i++) {
  201. BaseTree child = (BaseTree)newChildren.get(j);
  202. children.set(i, child);
  203. child.setParent(this);
  204. child.setChildIndex(i);
  205. j++;
  206. }
  207. }
  208. else if ( delta > 0 ) { // fewer new nodes than there were
  209. // set children and then delete extra
  210. for (int j=0; j<numNewChildren; j++) {
  211. children.set(startChildIndex+j, newChildren.get(j));
  212. }
  213. int indexToDelete = startChildIndex+numNewChildren;
  214. for (int c=indexToDelete; c<=stopChildIndex; c++) {
  215. // delete same index, shifting everybody down each time
  216. children.remove(indexToDelete);
  217. }
  218. freshenParentAndChildIndexes(startChildIndex);
  219. }
  220. else { // more new nodes than were there before
  221. // fill in as many children as we can (replacingHowMany) w/o moving data
  222. for (int j=0; j<replacingHowMany; j++) {
  223. children.set(startChildIndex+j, newChildren.get(j));
  224. }
  225. int numToInsert = replacingWithHowMany-replacingHowMany;
  226. for (int j=replacingHowMany; j<replacingWithHowMany; j++) {
  227. children.add(startChildIndex+j, newChildren.get(j));
  228. }
  229. freshenParentAndChildIndexes(startChildIndex);
  230. }
  231. //System.out.println("out="+toStringTree());
  232. }
  233. /** Override in a subclass to change the impl of children list */
  234. protected List<Object> createChildrenList() {
  235. return new ArrayList<Object>();
  236. }
  237. @Override
  238. public boolean isNil() {
  239. return false;
  240. }
  241. /** Set the parent and child index values for all child of t */
  242. @Override
  243. public void freshenParentAndChildIndexes() {
  244. freshenParentAndChildIndexes(0);
  245. }
  246. public void freshenParentAndChildIndexes(int offset) {
  247. int n = getChildCount();
  248. for (int c = offset; c < n; c++) {
  249. Tree child = getChild(c);
  250. child.setChildIndex(c);
  251. child.setParent(this);
  252. }
  253. }
  254. public void freshenParentAndChildIndexesDeeply() {
  255. freshenParentAndChildIndexesDeeply(0);
  256. }
  257. public void freshenParentAndChildIndexesDeeply(int offset) {
  258. int n = getChildCount();
  259. for (int c = offset; c < n; c++) {
  260. BaseTree child = (BaseTree)getChild(c);
  261. child.setChildIndex(c);
  262. child.setParent(this);
  263. child.freshenParentAndChildIndexesDeeply();
  264. }
  265. }
  266. public void sanityCheckParentAndChildIndexes() {
  267. sanityCheckParentAndChildIndexes(null, -1);
  268. }
  269. public void sanityCheckParentAndChildIndexes(Tree parent, int i) {
  270. if ( parent!=this.getParent() ) {
  271. throw new IllegalStateException("parents don't match; expected "+parent+" found "+this.getParent());
  272. }
  273. if ( i!=this.getChildIndex() ) {
  274. throw new IllegalStateException("child indexes don't match; expected "+i+" found "+this.getChildIndex());
  275. }
  276. int n = this.getChildCount();
  277. for (int c = 0; c < n; c++) {
  278. CommonTree child = (CommonTree)this.getChild(c);
  279. child.sanityCheckParentAndChildIndexes(this, c);
  280. }
  281. }
  282. /** BaseTree doesn't track child indexes. */
  283. @Override
  284. public int getChildIndex() {
  285. return 0;
  286. }
  287. @Override
  288. public void setChildIndex(int index) {
  289. }
  290. /** BaseTree doesn't track parent pointers. */
  291. @Override
  292. public Tree getParent() {
  293. return null;
  294. }
  295. @Override
  296. public void setParent(Tree t) {
  297. }
  298. /** Walk upwards looking for ancestor with this token type. */
  299. @Override
  300. public boolean hasAncestor(int ttype) { return getAncestor(ttype)!=null; }
  301. /** Walk upwards and get first ancestor with this token type. */
  302. @Override
  303. public Tree getAncestor(int ttype) {
  304. Tree t = this;
  305. t = t.getParent();
  306. while ( t!=null ) {
  307. if ( t.getType()==ttype ) return t;
  308. t = t.getParent();
  309. }
  310. return null;
  311. }
  312. /** Return a list of all ancestors of this node. The first node of
  313. * list is the root and the last is the parent of this node.
  314. */
  315. @Override
  316. public List<? extends Tree> getAncestors() {
  317. if ( getParent()==null ) return null;
  318. List<Tree> ancestors = new ArrayList<Tree>();
  319. Tree t = this;
  320. t = t.getParent();
  321. while ( t!=null ) {
  322. ancestors.add(0, t); // insert at start
  323. t = t.getParent();
  324. }
  325. return ancestors;
  326. }
  327. /** Print out a whole tree not just a node */
  328. @Override
  329. public String toStringTree() {
  330. if ( children==null || children.isEmpty() ) {
  331. return this.toString();
  332. }
  333. StringBuilder buf = new StringBuilder();
  334. if ( !isNil() ) {
  335. buf.append("(");
  336. buf.append(this.toString());
  337. buf.append(' ');
  338. }
  339. for (int i = 0; children!=null && i < children.size(); i++) {
  340. Tree t = (Tree)children.get(i);
  341. if ( i>0 ) {
  342. buf.append(' ');
  343. }
  344. buf.append(t.toStringTree());
  345. }
  346. if ( !isNil() ) {
  347. buf.append(")");
  348. }
  349. return buf.toString();
  350. }
  351. @Override
  352. public int getLine() {
  353. return 0;
  354. }
  355. @Override
  356. public int getCharPositionInLine() {
  357. return 0;
  358. }
  359. /** Override to say how a node (not a tree) should look as text */
  360. @Override
  361. public abstract String toString();
  362. }