1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.util.*;
6 import edu.berkeley.sbp.bind.*;
9 import java.lang.reflect.*;
11 /** <font color=blue>a tree (or node in a tree); see jargon.txt for details</font> */
12 public class Tree<NodeType>
13 extends PrintableTree<Tree<NodeType>>
14 implements Iterable<Tree<NodeType>> {
16 private final Input.Region location;
17 private final NodeType head;
18 private final Tree<NodeType>[] children;
19 private final boolean lift;
21 /** the element at the head of the tree */
22 public NodeType head() { return head; }
24 private Tree<NodeType> lifted() { return children[children.length-1]; }
26 /** the number of children the tree has */
29 ? (children.length-1)+lifted().size()
33 /** the tree's children */
34 public Iterable<Tree<NodeType>> children() { return this; }
36 /** the tree's children */
37 public Iterator<Tree<NodeType>> iterator() {
39 ? new ConcatenateIterator(new ArrayIterator(children, 0, children.length-1),
40 children[children.length-1].iterator())
41 : new ArrayIterator(children);
44 /** get the <tt>i</t>th child */
45 public Tree<NodeType> child(int i) {
46 return lift && i >= children.length-1
47 ? children[children.length-1].child(i-(children.length-1))
51 /** get the input region that this tree was parsed from */
52 public Input.Region getRegion() { return location; }
54 public Tree(Input.Region loc, NodeType head) { this(loc, head, null); }
55 public Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children) { this(loc, head, children, false); }
57 /** package-private constructor, allows setting the "lift" bit */
58 Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children, boolean lift) {
61 this.lift = lift && children != null && children.length > 0;
62 this.children = ArrayUtil.clone(children, Tree.class);
66 // PrintableTree /////////////////////////////////////////////////////////////////////////////
68 protected String headToString() { return head()==null?null:head().toString(); }
69 protected String headToJava() {
71 if (head()==null) return null;
72 if (head() instanceof ToJava) {
73 StringBuffer sb = new StringBuffer();
74 ((ToJava)head()).toJava(sb);
77 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
79 protected String left() { return "{"; }
80 protected String right() { return "}"; }
81 protected boolean ignoreSingleton() { return false; }