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 /** 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.Region 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.Region getRegion() { return location; }
27 public Tree(Input.Region loc, T head) { this(loc, head, null); }
28 public Tree(Input.Region 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() {
40 if (head==null) return null;
41 if (head instanceof ToJava) {
42 StringBuffer sb = new StringBuffer();
43 ((ToJava)head).toJava(sb);
46 return (head==null?"null":("\""+StringUtil.toJavaString(head.toString())+"\""));
48 protected String left() { return "{"; }
49 protected String right() { return "}"; }
50 protected boolean ignoreSingleton() { return false; }
52 public GraphViz.Node toGraphViz(GraphViz gv) {
53 if (gv.hasNode(this)) return gv.createNode(this);
54 GraphViz.Node n = gv.createNode(this);
55 n.label = head()==null ? "" : head().toString();
57 for(Tree t : this) n.edge(t, null);
60 public boolean isTransparent() { return false; }
61 public boolean isHidden() { return false; }
63 public static interface TreeFunctor<T,R> extends Functor<Iterable<Tree<T>>, R> {
66 public static class ArrayBuildingTreeFunctor<T> implements TreeFunctor<T,T[]>, ToJava {
68 public void toJava(StringBuffer sb) { sb.append("new Tree.ArrayBuildingTreeFunctor()"); }
69 public String toString() { return ""; }
71 public T[] invoke(Iterable<Tree<T>> t) {
72 ArrayList ret = new ArrayList();
74 if (tc.head() != null && tc.head() instanceof Functor)
75 ret.add(((Functor<Iterable<Tree>,Object>)tc.head()).invoke(tc.children()));
76 else if (tc.numChildren() == 0)
79 System.err.println("FIXME: don't know what to do about " + tc);
83 return (T[])ret.toArray(new Object[0]);
87 public static class BindingFunctor<T> implements TreeFunctor<T,Object>/*, ToJava*/ {
88 private Binding _binding;
89 public BindingFunctor(Binding binding) {
90 this._binding = binding;
92 public Object invoke(Iterable<Tree<T>> t) {
93 return _binding.invoke(new Object[] { t });