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 ihead;
18 private final Tree<NodeType>[] children;
19 private final boolean lift;
21 private Tree<NodeType> lifted() { return children[children.length-1]; }
23 /** the number of children the tree has */
26 ? (children.length-1)+lifted().size()
30 /** the element at the head of the tree */
31 public NodeType head() { return ihead; }
32 public NodeType getHead() { return ihead; }
34 /** the tree's children */
35 public Iterable<Tree<NodeType>> children() { return this; }
37 /** the tree's children */
38 public Iterator<Tree<NodeType>> iterator() {
40 ? new ConcatenateIterator(new ArrayIterator(children, 0, children.length-1),
41 children[children.length-1].iterator())
42 : new ArrayIterator(children);
45 /** get the <tt>i</t>th child */
46 public Tree<NodeType> child(int i) {
47 return lift && i >= children.length-1
48 ? children[children.length-1].child(i-(children.length-1))
52 /** get the input region that this tree was parsed from */
53 public Input.Region getRegion() { return location; }
55 public Tree(Input.Region loc, NodeType head) { this(loc, head, null); }
56 public Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children) { this(loc, head, children, false); }
58 /** package-private constructor, allows setting the "lift" bit */
59 Tree(Input.Region loc, NodeType head, Tree<NodeType>[] children, boolean lift) {
62 this.lift = lift && children != null && children.length > 0;
63 this.children = ArrayUtil.clone(children, Tree.class);
67 // PrintableTree /////////////////////////////////////////////////////////////////////////////
69 protected String headToString() { return head()==null?null:head().toString(); }
70 protected String headToJava() {
72 if (head()==null) return null;
73 if (head() instanceof ToJava) {
74 StringBuffer sb = new StringBuffer();
75 ((ToJava)head()).toJava(sb);
78 return (head()==null?"null":("\""+StringUtil.toJavaString(head().toString())+"\""));
80 protected String left() { return "{"; }
81 protected String right() { return "}"; }
82 protected boolean ignoreSingleton() { return false; }