1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.*;
7 import java.lang.reflect.*;
8 import java.lang.ref.*;
10 /** an element which can produce one of several alternatives */
11 public class Union extends Element implements Iterable<Sequence> {
13 final String shortForm;
14 final boolean synthetic;
15 private final List<Sequence> alternatives = new ArrayList<Sequence>();
17 public Iterator<Sequence> iterator() { return alternatives.iterator(); }
19 void reachable(HashSet<Sequence.Position> h) { for(Sequence s : alternatives) s.reachable(h); }
21 /** adds an alternative */
22 public void add(Sequence s) { alternatives.add(s); }
25 * Since every cycle in a non-degenerate grammar contains at
26 * least one Union, every instance of this class must be able to
27 * display itself in both "long form" (list of the long forms of
28 * its alternatives) and "short form" (some abbreviation).
30 * @param shortForm the "short form" display; usually
31 * @param synthetic if true, this Union's "long form" is "obvious" and should not be displayed when printing the grammar
33 public Union(String shortForm) { this(shortForm, false); }
34 public Union(String shortForm, boolean synthetic) {
35 this.shortForm = shortForm;
36 this.synthetic = synthetic;
39 public static Union epsilon = new Union("()");
40 static { epsilon.add(Sequence.empty); }
42 private Forest.Ref epsilonForm = null;
43 Forest epsilonForm() {
44 if (epsilonForm != null) return epsilonForm;
45 epsilonForm = new Forest.Ref();
46 for(Sequence s : this)
47 if (s.possiblyEpsilon(null))
48 epsilonForm.merge(s.epsilonForm());
52 // Display //////////////////////////////////////////////////////////////////////////////
54 public String toString() { return shortForm; }
55 private static String pad(int i,String s) { return s.length() >= i ? s : pad(i-1,s)+" "; }
56 public void toString(StringBuffer sb) {
57 if (synthetic) return;
59 if (alternatives.size()==0) {
60 sb.append(pad(15, shortForm) + "::= ");
61 } else for(Sequence s : this) {
62 sb.append(pad(15, first ? shortForm : "") + (first ? "::= " : " | "));
64 sb.append(s.toString());
70 // SubUnion //////////////////////////////////////////////////////////////////////////////
72 /** FIXME this is kind of a hack */
73 public class Subset extends Union {
74 private final Set<Sequence> exclude;
75 public Subset(String shortForm, Set<Sequence> exclude) { super(shortForm, true); this.exclude = exclude; }
76 public Iterator<Sequence> iterator() {
77 final Iterator<Sequence> it = Union.this.iterator();
78 return new Iterator<Sequence>() {
79 private Sequence next = it.hasNext() ? it.next() : null;
80 public boolean hasNext() { return next != null; }
81 public Sequence next() {
84 next = it.hasNext() ? it.next() : null;
85 } while (next != null && (next instanceof Sequence) && exclude.contains((Sequence)next));
88 public void remove() { throw new Error(); }