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); }
20 public Token.Location getLocation() { return location; }
22 public Tree(Token.Location loc, T head) { this(loc, head, null); }
23 public Tree(Token.Location loc, T head, Tree<T>[] children) {
26 Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
27 if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
28 this.children = children2;
31 /** append Java code to <tt>sb</tt> which evaluates to this instance */
32 public void toJava(StringBuffer sb) {
33 sb.append("new Tree(null, ");
34 sb.append(head==null ? "null" : "\"" + StringUtil.toJavaString(head+"") + "\"");
35 sb.append(", new Tree[] { ");
36 for(int i=0; i<children.length; i++) {
37 if (children[i]==null) sb.append("null");
38 else children[i].toJava(sb);
39 if (i<children.length-1) sb.append(",\n ");
44 public String toString() {
45 StringBuffer ret = new StringBuffer();
46 for(int i=0; i<children.length; i++) {
47 String q = children[i]==null ? "null" : children[i].toString();
48 if (q.length() > 0) { ret.append(q); ret.append(" "); }
50 String tail = ret.toString().trim();
51 String h = (head!=null && !head.toString().equals("")) ? (tail.length() > 0 ? head+":" : head+"") : "";
52 if (tail.length() > 0) tail = "{" + tail + "}";