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>>,
17 final Input.Location location;
19 public T head() { return head; }
20 public int numChildren() { return children.length; }
21 public Iterable<Tree<T>> children() { return new ArrayIterator(children); }
22 public Iterator<Tree<T>> iterator() { return new ArrayIterator(children); }
23 public Tree<T> child(int i) { return children[i]; }
25 public Input.Location getLocation() { return location; }
27 public Tree(Input.Location loc, T head) { this(loc, head, null); }
28 public Tree(Input.Location loc, T head, Tree<T>[] children) {
32 Tree<T>[] children2 = children==null ? new Tree[0] : new Tree[children.length];
33 if (children != null) System.arraycopy(children, 0, children2, 0, children.length);
34 this.children = children2;
37 protected String headToString() { return head==null?null:head.toString(); }
38 protected String headToJava() {
39 if (head==null) return null;
40 if (head instanceof ToJava) {
41 StringBuffer sb = new StringBuffer();
42 ((ToJava)head).toJava(sb);
45 return head==null?"null":("\""+StringUtil.toJavaString(head.toString())+"\"");
47 protected String left() { return "{"; }
48 protected String right() { return "}"; }
49 protected boolean ignoreSingleton() { return false; }
51 public GraphViz.Node toGraphViz(GraphViz gv) {
52 if (gv.hasNode(this)) return gv.createNode(this);
53 GraphViz.Node n = gv.createNode(this);
54 n.label = head()==null ? "" : head().toString();
56 for(Tree t : this) n.edge(t, null);
59 public boolean isTransparent() { return false; }
60 public boolean isHidden() { return false; }
62 public static interface TreeFunctor<T,R> extends Functor<Iterable<Tree<T>>, R> {
65 public static class ArrayBuildingTreeFunctor<T> implements TreeFunctor<T,T[]>, ToJava {
67 public void toJava(StringBuffer sb) { sb.append("new Tree.ArrayBuildingTreeFunctor()"); }
68 public String toString() { return ""; }
70 public T[] invoke(Iterable<Tree<T>> t) {
71 ArrayList ret = new ArrayList();
73 if (tc.head() != null && tc.head() instanceof Functor)
74 ret.add(((Functor<Iterable<Tree>,Object>)tc.head()).invoke(tc.children()));
75 else if (tc.numChildren() == 0)
78 System.err.println("FIXME: don't know what to do about " + tc);
82 return (T[])ret.toArray(new Object[0]);