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 /** <font color=blue>a tree (or node in a tree); see jargon.txt for details</font> */
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); }
56 /** package-private constructor, allows setting the "lift" bit */
57 Tree(Input.Region loc, T head, Tree<T>[] children, boolean lift) {
60 this.lift = lift && children != null && children.length > 0;
61 this.children = ArrayUtil.clone(children, Tree.class);
65 // PrintableTree /////////////////////////////////////////////////////////////////////////////
67 protected String headToString() { return head()==null?null:head().toString(); }
68 protected String headToJava() {
70 if (head()==null) return null;
71 if (head() instanceof ToJava) {
72 StringBuffer sb = new StringBuffer();
73 ((ToJava)head()).toJava(sb);
76 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
78 protected String left() { return "{"; }
79 protected String right() { return "}"; }
80 protected boolean ignoreSingleton() { return false; }
83 // ToGraphViz /////////////////////////////////////////////////////////////////////////////
85 public GraphViz.Node toGraphViz(GraphViz gv) {
86 if (gv.hasNode(this)) return gv.createNode(this);
87 GraphViz.Node n = gv.createNode(this);
88 n.label = head()==null ? "" : head().toString();
89 for(Tree t : this) n.edge(t, null);
92 public boolean isTransparent() { return false; }
93 public boolean isHidden() { return false; }