1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.util.*;
7 import java.lang.reflect.*;
9 /** a tree (or node in a tree); see jargon.txt for details */
10 public class Tree<T> {
14 final Token.Location location;
16 public T head() { return head; }
17 public int numChildren() { return children.length; }
18 public Iterable<Tree<T>> children() { return new ArrayIterator(children); }
19 public Tree<T> child(int i) { return children[i]; }
21 public Token.Location getLocation() { return location; }
23 public Tree(Token.Location loc, T head) { this(loc, head, null); }
24 public Tree(Token.Location loc, T head, Tree<T>[] children) {
27 Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
28 if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
29 this.children = children2;
32 /** append Java code to <tt>sb</tt> which evaluates to this instance */
33 public void toJava(StringBuffer sb) {
34 sb.append("new Tree(null, ");
35 sb.append(head==null ? "null" : "\"" + StringUtil.toJavaString(head+"") + "\"");
36 sb.append(", new Tree[] { ");
37 for(int i=0; i<children.length; i++) {
38 if (children[i]==null) sb.append("null");
39 else children[i].toJava(sb);
40 if (i<children.length-1) sb.append(",\n ");
45 public String toString() {
46 StringBuffer ret = new StringBuffer();
47 for(int i=0; i<children.length; i++) {
48 String q = children[i]==null ? "null" : children[i].toString();
49 if (q.length() > 0) { ret.append(q); ret.append(" "); }
51 String tail = ret.toString().trim();
52 String h = (head!=null && !head.toString().equals("")) ? (tail.length() > 0 ? head+":" : head+"") : "";
53 if (tail.length() > 0) tail = "{" + tail + "}";