6b295a5b18b7b66f4b1b9367cc21b1951f60c979
[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     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 Iterator<Tree<T>> iterator()    { return new ArrayIterator(children); }
20     public Tree<T>           child(int i)  { return children[i]; }
21
22     public       Token.Location    getLocation() { return location; }
23
24     public Tree(Token.Location loc, T head)                   { this(loc, head, null); }
25     public Tree(Token.Location loc, T head, Tree<T>[] children) {
26         this.location = loc;
27         this.head = head;
28         Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
29         if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
30         this.children = children2;
31     }
32
33     /** since Tree instances are immutable, we can cache this to make pretty-printing MUCH faster */
34     public String toString() {
35         if (toString!=null) return toString;
36         return toString = super.toString();
37     }
38     private String toString = null;
39
40     protected String headToString() { return head==null?null:head.toString(); }
41     protected String headToJava()   { return head==null?null:StringUtil.toJavaString(head+""); }
42 }