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 */ 28 package org.antlr.runtime.tree; 29 30 import org.antlr.runtime.Token; 31 import org.antlr.runtime.TokenStream; 32 import org.antlr.runtime.RecognitionException; 33 34 import java.util.HashMap; 35 import java.util.Map; 36 37 /** A TreeAdaptor that works with any Tree implementation. */ 38 public abstract class BaseTreeAdaptor implements TreeAdaptor { 39 /** System.identityHashCode() is not always unique; we have to 40 * track ourselves. That's ok, it's only for debugging, though it's 41 * expensive: we have to create a hashtable with all tree nodes in it. 42 */ 43 protected Map treeToUniqueIDMap; 44 protected int uniqueNodeID = 1; 45 nil()46 public Object nil() { 47 return create(null); 48 } 49 50 /** create tree node that holds the start and stop tokens associated 51 * with an error. 52 * 53 * If you specify your own kind of tree nodes, you will likely have to 54 * override this method. CommonTree returns Token.INVALID_TOKEN_TYPE 55 * if no token payload but you might have to set token type for diff 56 * node type. 57 * 58 * You don't have to subclass CommonErrorNode; you will likely need to 59 * subclass your own tree node class to avoid class cast exception. 60 */ errorNode(TokenStream input, Token start, Token stop, RecognitionException e)61 public Object errorNode(TokenStream input, Token start, Token stop, 62 RecognitionException e) 63 { 64 CommonErrorNode t = new CommonErrorNode(input, start, stop, e); 65 //System.out.println("returning error node '"+t+"' @index="+input.index()); 66 return t; 67 } 68 isNil(Object tree)69 public boolean isNil(Object tree) { 70 return ((Tree)tree).isNil(); 71 } 72 dupTree(Object tree)73 public Object dupTree(Object tree) { 74 return dupTree(tree, null); 75 } 76 77 /** This is generic in the sense that it will work with any kind of 78 * tree (not just Tree interface). It invokes the adaptor routines 79 * not the tree node routines to do the construction. 80 */ dupTree(Object t, Object parent)81 public Object dupTree(Object t, Object parent) { 82 if ( t==null ) { 83 return null; 84 } 85 Object newTree = dupNode(t); 86 // ensure new subtree root has parent/child index set 87 setChildIndex(newTree, getChildIndex(t)); // same index in new tree 88 setParent(newTree, parent); 89 int n = getChildCount(t); 90 for (int i = 0; i < n; i++) { 91 Object child = getChild(t, i); 92 Object newSubTree = dupTree(child, t); 93 addChild(newTree, newSubTree); 94 } 95 return newTree; 96 } 97 98 /** Add a child to the tree t. If child is a flat tree (a list), make all 99 * in list children of t. Warning: if t has no children, but child does 100 * and child isNil then you can decide it is ok to move children to t via 101 * t.children = child.children; i.e., without copying the array. Just 102 * make sure that this is consistent with have the user will build 103 * ASTs. 104 */ addChild(Object t, Object child)105 public void addChild(Object t, Object child) { 106 if ( t!=null && child!=null ) { 107 ((Tree)t).addChild((Tree)child); 108 } 109 } 110 111 /** If oldRoot is a nil root, just copy or move the children to newRoot. 112 * If not a nil root, make oldRoot a child of newRoot. 113 * 114 * old=^(nil a b c), new=r yields ^(r a b c) 115 * old=^(a b c), new=r yields ^(r ^(a b c)) 116 * 117 * If newRoot is a nil-rooted single child tree, use the single 118 * child as the new root node. 119 * 120 * old=^(nil a b c), new=^(nil r) yields ^(r a b c) 121 * old=^(a b c), new=^(nil r) yields ^(r ^(a b c)) 122 * 123 * If oldRoot was null, it's ok, just return newRoot (even if isNil). 124 * 125 * old=null, new=r yields r 126 * old=null, new=^(nil r) yields ^(nil r) 127 * 128 * Return newRoot. Throw an exception if newRoot is not a 129 * simple node or nil root with a single child node--it must be a root 130 * node. If newRoot is ^(nil x) return x as newRoot. 131 * 132 * Be advised that it's ok for newRoot to point at oldRoot's 133 * children; i.e., you don't have to copy the list. We are 134 * constructing these nodes so we should have this control for 135 * efficiency. 136 */ becomeRoot(Object newRoot, Object oldRoot)137 public Object becomeRoot(Object newRoot, Object oldRoot) { 138 //System.out.println("becomeroot new "+newRoot.toString()+" old "+oldRoot); 139 Tree newRootTree = (Tree)newRoot; 140 Tree oldRootTree = (Tree)oldRoot; 141 if ( oldRoot==null ) { 142 return newRoot; 143 } 144 // handle ^(nil real-node) 145 if ( newRootTree.isNil() ) { 146 int nc = newRootTree.getChildCount(); 147 if ( nc==1 ) newRootTree = (Tree)newRootTree.getChild(0); 148 else if ( nc >1 ) { 149 // TODO: make tree run time exceptions hierarchy 150 throw new RuntimeException("more than one node as root (TODO: make exception hierarchy)"); 151 } 152 } 153 // add oldRoot to newRoot; addChild takes care of case where oldRoot 154 // is a flat list (i.e., nil-rooted tree). All children of oldRoot 155 // are added to newRoot. 156 newRootTree.addChild(oldRootTree); 157 return newRootTree; 158 } 159 160 /** Transform ^(nil x) to x and nil to null */ rulePostProcessing(Object root)161 public Object rulePostProcessing(Object root) { 162 //System.out.println("rulePostProcessing: "+((Tree)root).toStringTree()); 163 Tree r = (Tree)root; 164 if ( r!=null && r.isNil() ) { 165 if ( r.getChildCount()==0 ) { 166 r = null; 167 } 168 else if ( r.getChildCount()==1 ) { 169 r = (Tree)r.getChild(0); 170 // whoever invokes rule will set parent and child index 171 r.setParent(null); 172 r.setChildIndex(-1); 173 } 174 } 175 return r; 176 } 177 becomeRoot(Token newRoot, Object oldRoot)178 public Object becomeRoot(Token newRoot, Object oldRoot) { 179 return becomeRoot(create(newRoot), oldRoot); 180 } 181 create(int tokenType, Token fromToken)182 public Object create(int tokenType, Token fromToken) { 183 fromToken = createToken(fromToken); 184 //((ClassicToken)fromToken).setType(tokenType); 185 fromToken.setType(tokenType); 186 Tree t = (Tree)create(fromToken); 187 return t; 188 } 189 create(int tokenType, Token fromToken, String text)190 public Object create(int tokenType, Token fromToken, String text) { 191 if (fromToken == null) return create(tokenType, text); 192 fromToken = createToken(fromToken); 193 fromToken.setType(tokenType); 194 fromToken.setText(text); 195 Tree t = (Tree)create(fromToken); 196 return t; 197 } 198 create(int tokenType, String text)199 public Object create(int tokenType, String text) { 200 Token fromToken = createToken(tokenType, text); 201 Tree t = (Tree)create(fromToken); 202 return t; 203 } 204 getType(Object t)205 public int getType(Object t) { 206 return ((Tree)t).getType(); 207 } 208 setType(Object t, int type)209 public void setType(Object t, int type) { 210 throw new NoSuchMethodError("don't know enough about Tree node"); 211 } 212 getText(Object t)213 public String getText(Object t) { 214 return ((Tree)t).getText(); 215 } 216 setText(Object t, String text)217 public void setText(Object t, String text) { 218 throw new NoSuchMethodError("don't know enough about Tree node"); 219 } 220 getChild(Object t, int i)221 public Object getChild(Object t, int i) { 222 return ((Tree)t).getChild(i); 223 } 224 setChild(Object t, int i, Object child)225 public void setChild(Object t, int i, Object child) { 226 ((Tree)t).setChild(i, (Tree)child); 227 } 228 deleteChild(Object t, int i)229 public Object deleteChild(Object t, int i) { 230 return ((Tree)t).deleteChild(i); 231 } 232 getChildCount(Object t)233 public int getChildCount(Object t) { 234 return ((Tree)t).getChildCount(); 235 } 236 getUniqueID(Object node)237 public int getUniqueID(Object node) { 238 if ( treeToUniqueIDMap==null ) { 239 treeToUniqueIDMap = new HashMap(); 240 } 241 Integer prevID = (Integer)treeToUniqueIDMap.get(node); 242 if ( prevID!=null ) { 243 return prevID.intValue(); 244 } 245 int ID = uniqueNodeID; 246 treeToUniqueIDMap.put(node, new Integer(ID)); 247 uniqueNodeID++; 248 return ID; 249 // GC makes these nonunique: 250 // return System.identityHashCode(node); 251 } 252 253 /** Tell me how to create a token for use with imaginary token nodes. 254 * For example, there is probably no input symbol associated with imaginary 255 * token DECL, but you need to create it as a payload or whatever for 256 * the DECL node as in ^(DECL type ID). 257 * 258 * If you care what the token payload objects' type is, you should 259 * override this method and any other createToken variant. 260 */ createToken(int tokenType, String text)261 public abstract Token createToken(int tokenType, String text); 262 263 /** Tell me how to create a token for use with imaginary token nodes. 264 * For example, there is probably no input symbol associated with imaginary 265 * token DECL, but you need to create it as a payload or whatever for 266 * the DECL node as in ^(DECL type ID). 267 * 268 * This is a variant of createToken where the new token is derived from 269 * an actual real input token. Typically this is for converting '{' 270 * tokens to BLOCK etc... You'll see 271 * 272 * r : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ; 273 * 274 * If you care what the token payload objects' type is, you should 275 * override this method and any other createToken variant. 276 */ createToken(Token fromToken)277 public abstract Token createToken(Token fromToken); 278 } 279 280