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 /** the element at the head of the tree */
21 public T head() { return head; }
23 private Tree<T> lifted() { return children[children.length-1]; }
25 /** the number of children the tree has */
26 public int numChildren() {
28 ? (children.length-1)+lifted().numChildren()
32 /** the tree's children */
33 public Iterable<Tree<T>> children() { return this; }
35 /** the tree's children */
36 public Iterator<Tree<T>> iterator() {
38 ? new ConcatenateIterator(new ArrayIterator(children, 0, children.length-1),
39 children[children.length-1].iterator())
40 : new ArrayIterator(children);
43 /** get the <tt>i</t>th child */
44 public Tree<T> child(int i) {
45 return lift && i >= children.length-1
46 ? children[children.length-1].child(i-(children.length-1))
50 /** get the input region that this tree was parsed from */
51 public Input.Region getRegion() { return location; }
53 public Tree(Input.Region loc, T head) { this(loc, head, null); }
54 public Tree(Input.Region loc, T head, Tree<T>[] children) { this(loc, head, children, false); }
55 Tree(Input.Region loc, T head, Tree<T>[] children, boolean lift) {
58 this.lift = lift && children != null && children.length > 0;
59 this.children = ArrayUtil.clone(children, Tree.class);
63 // PrintableTree /////////////////////////////////////////////////////////////////////////////
65 protected String headToString() { return head()==null?null:head().toString(); }
66 protected String headToJava() {
68 if (head()==null) return null;
69 if (head() instanceof ToJava) {
70 StringBuffer sb = new StringBuffer();
71 ((ToJava)head()).toJava(sb);
74 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
76 protected String left() { return "{"; }
77 protected String right() { return "}"; }
78 protected boolean ignoreSingleton() { return false; }
81 // ToGraphViz /////////////////////////////////////////////////////////////////////////////
83 public GraphViz.Node toGraphViz(GraphViz gv) {
84 if (gv.hasNode(this)) return gv.createNode(this);
85 GraphViz.Node n = gv.createNode(this);
86 n.label = head()==null ? "" : head().toString();
88 for(Tree t : this) n.edge(t, null);
91 public boolean isTransparent() { return false; }
92 public boolean isHidden() { return false; }
95 // TreeFunctor /////////////////////////////////////////////////////////////////////////////
97 public static interface TreeFunctor<T,R> extends Functor<Iterable<Tree<T>>, R> { }