1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.bind.*;
7 import java.lang.reflect.*;
9 /** a tree (or node in a tree); see jargon.txt for details */
11 extends PrintableTree<Tree<T>>
12 implements Iterable<Tree<T>>,
15 private final Input.Region location;
17 private final Tree<T>[] children;
18 private final boolean lift;
20 public T head() { return head; }
22 private Tree<T> lifted() { return children[children.length-1]; }
24 public int numChildren() {
26 ? (children.length-1)+lifted().numChildren()
29 public Iterable<Tree<T>> children() { return this; }
30 public Iterator<Tree<T>> iterator() {
32 ? new ConcatenateIterator(new ArrayIterator(children, 0, children.length-1),
33 children[children.length-1].iterator())
34 : new ArrayIterator(children);
37 public Tree<T> child(int i) {
38 return lift && i >= children.length-1
39 ? children[children.length-1].child(i-(children.length-1))
43 public Input.Region getRegion() { return location; }
45 public Tree(Input.Region loc, T head) { this(loc, head, null); }
46 public Tree(Input.Region loc, T head, Tree<T>[] children) { this(loc, head, children, false); }
47 public Tree(Input.Region loc, T head, Tree<T>[] children, boolean lift) {
50 this.lift = lift && children != null && children.length > 0;
51 this.children = ArrayUtil.clone(children, Tree.class);
55 // PrintableTree /////////////////////////////////////////////////////////////////////////////
57 protected String headToString() { return head()==null?null:head().toString(); }
58 protected String headToJava() {
60 if (head()==null) return null;
61 if (head() instanceof ToJava) {
62 StringBuffer sb = new StringBuffer();
63 ((ToJava)head()).toJava(sb);
66 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
68 protected String left() { return "{"; }
69 protected String right() { return "}"; }
70 protected boolean ignoreSingleton() { return false; }
73 // ToGraphViz /////////////////////////////////////////////////////////////////////////////
75 public GraphViz.Node toGraphViz(GraphViz gv) {
76 if (gv.hasNode(this)) return gv.createNode(this);
77 GraphViz.Node n = gv.createNode(this);
78 n.label = head()==null ? "" : head().toString();
80 for(Tree t : this) n.edge(t, null);
83 public boolean isTransparent() { return false; }
84 public boolean isHidden() { return false; }
87 // TreeFunctor /////////////////////////////////////////////////////////////////////////////
89 public static interface TreeFunctor<T,R> extends Functor<Iterable<Tree<T>>, R> { }