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> extends PrintableTree<Tree<T>> implements Iterable<Tree<T>> {
11
12     final T           head;
13           Tree<T>[]   children;
14           Object[]    labels;
15     final Input.Location    location;
16
17     public T                 head()        { return head; }
18     public int               numChildren() { return children.length; }
19     public Iterable<Tree<T>> children()    { return new ArrayIterator(children); }
20     public Iterator<Tree<T>> iterator()    { return new ArrayIterator(children); }
21     public Tree<T>           child(int i)  { return children[i]; }
22     public Object            label(int i)  { return labels[i]; }
23
24     public Input.Location    getLocation() { return location; }
25
26     public Tree(Input.Location loc, T head)                   { this(loc, head, null); }
27     public Tree(Input.Location loc, T head, Tree<T>[] children) { this(loc, head, children, null); }
28     public Tree(Input.Location loc, T head, Tree<T>[] children, Object[] labels) {
29         this.location = loc;
30         this.head = head;
31
32         Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
33         if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
34         this.children = children2;
35
36         Object[] labels2 = labels==null ? new Object[0] : new Object[labels.length];
37         if (labels != null) System.arraycopy(labels, 0, labels2, 0, labels.length);
38         this.labels = labels2;
39     }
40
41     protected String headToString() { return head==null?null:head.toString(); }
42     protected String headToJava()   { return head==null?null:StringUtil.toJavaString(head+""); }
43     protected String left()   { return "{"; }
44     protected String right()  { return "}"; }
45     protected boolean ignoreSingleton() { return false; }
46 }