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
20     public       Token.Location    getLocation() { return location; }
21
22     public Tree(Token.Location loc, T head)                   { this(loc, head, null); }
23     public Tree(Token.Location loc, T head, Tree<T>[] children) {
24         this.location = loc;
25         this.head = head;
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;
29     }
30
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        ");
40         }
41         sb.append("})");
42     }
43
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(" "); }
49         }
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 + "}";
53         return h + tail;
54     }
55
56
57 }