1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.util.*;
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>>,
18 final Input.Location location;
20 public T head() { return head; }
21 public int numChildren() { return children.length; }
22 public Iterable<Tree<T>> children() { return new ArrayIterator(children); }
23 public Iterator<Tree<T>> iterator() { return new ArrayIterator(children); }
24 public Tree<T> child(int i) { return children[i]; }
25 public Object label(int i) { return labels[i]; }
27 public Input.Location getLocation() { return location; }
29 public Tree(Input.Location loc, T head) { this(loc, head, null); }
30 public Tree(Input.Location loc, T head, Tree<T>[] children) { this(loc, head, children, null); }
31 public Tree(Input.Location loc, T head, Tree<T>[] children, Object[] labels) {
35 Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
36 if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
37 this.children = children2;
39 Object[] labels2 = labels==null ? new Object[0] : new Object[labels.length];
40 if (labels != null) System.arraycopy(labels, 0, labels2, 0, labels.length);
41 this.labels = labels2;
44 protected String headToString() { return head==null?null:head.toString(); }
45 protected String headToJava() {
46 if (head==null) return null;
47 if (head instanceof ToJava) {
48 StringBuffer sb = new StringBuffer();
49 ((ToJava)head).toJava(sb);
52 return head==null?"null":("\""+StringUtil.toJavaString(head.toString())+"\"");
54 protected String left() { return "{"; }
55 protected String right() { return "}"; }
56 protected boolean ignoreSingleton() { return false; }
58 public GraphViz.Node toGraphViz(GraphViz gv) {
59 if (gv.hasNode(this)) return gv.createNode(this);
60 GraphViz.Node n = gv.createNode(this);
61 n.label = head()==null ? "" : head().toString();
63 for(Tree t : this) n.edge(t, null);
66 public boolean isTransparent() { return false; }
67 public boolean isHidden() { return false; }
69 public static interface TreeFunctor<T,R> extends Functor<Iterable<Tree<T>>, R> {
72 public static class ArrayBuildingTreeFunctor<T> implements TreeFunctor<T,T[]>, ToJava {
74 public void toJava(StringBuffer sb) { sb.append("new Tree.ArrayBuildingTreeFunctor()"); }
75 public String toString() { return ""; }
77 public T[] invoke(Iterable<Tree<T>> t) {
78 ArrayList ret = new ArrayList();
80 if (tc.head() != null && tc.head() instanceof Functor)
81 ret.add(((Functor<Iterable<Tree>,Object>)tc.head()).invoke(tc.children()));
82 else if (tc.numChildren() == 0)
85 System.err.println("FIXME: don't know what to do about " + tc);
89 return (T[])ret.toArray(new Object[0]);