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> */
10 public class Tree<NodeType>
11 extends PrintableTree<Tree<NodeType>>
12 implements Iterable<Tree<NodeType>> {
14 private final Input.Region location;
15 private final NodeType head;
16 private final Tree<NodeType>[] children;
17 private final boolean lift;
19 /** the element at the head of the tree */
20 public NodeType head() { return head; }
22 private Tree<NodeType> lifted() { return children[children.length-1]; }
24 /** the number of children the tree has */
27 ? (children.length-1)+lifted().size()
31 /** the tree's children */
32 public Iterable<Tree<NodeType>> children() { return this; }
34 /** the tree's children */
35 public Iterator<Tree<NodeType>> iterator() {
37 ? new ConcatenateIterator(new ArrayIterator(children, 0, children.length-1),
38 children[children.length-1].iterator())
39 : new ArrayIterator(children);
42 /** get the <tt>i</t>th child */
43 public Tree<NodeType> child(int i) {
44 return lift && i >= children.length-1
45 ? children[children.length-1].child(i-(children.length-1))
49 /** get the input region that this tree was parsed from */
50 public Input.Region getRegion() { return location; }
52 public Tree(Input.Region loc, NodeType head) { this(loc, head, null); }
53 public Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children) { this(loc, head, children, false); }
55 /** package-private constructor, allows setting the "lift" bit */
56 Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children, boolean lift) {
59 this.lift = lift && children != null && children.length > 0;
60 this.children = ArrayUtil.clone(children, Tree.class);
64 // PrintableTree /////////////////////////////////////////////////////////////////////////////
66 protected String headToString() { return head()==null?null:head().toString(); }
67 protected String headToJava() {
69 if (head()==null) return null;
70 if (head() instanceof ToJava) {
71 StringBuffer sb = new StringBuffer();
72 ((ToJava)head()).toJava(sb);
75 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
77 protected String left() { return "{"; }
78 protected String right() { return "}"; }
79 protected boolean ignoreSingleton() { return false; }