checkpoint
[sbp.git] / src / edu / berkeley / sbp / Tree.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.util.*;
5 import java.io.*;
6 import java.util.*;
7 import java.lang.reflect.*;
8
9 /** a tree (or node in a tree); see jargon.txt for details */
10 public class Tree<T> {
11
12     final T           head;
13           Tree<T>[]   children;
14     final Token.Location    location;
15
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]; }
20
21     public       Token.Location    getLocation() { return location; }
22
23     public Tree(Token.Location loc, T head)                   { this(loc, head, null); }
24     public Tree(Token.Location loc, T head, Tree<T>[] children) {
25         this.location = loc;
26         this.head = head;
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;
30     }
31
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        ");
41         }
42         sb.append("})");
43     }
44
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(" "); }
50         }
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 + "}";
54         return h + tail;
55     }
56
57
58 }