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> {
14 * Since every cycle in a non-degenerate grammar contains at
15 * least one Union, every instance of this class must be able to
16 * display itself in both "long form" (list of the long forms of
17 * its alternatives) and "short form" (some abbreviation).
19 * @param shortForm the "short form" display; usually
20 * @param synthetic if true, this Union's "long form" is "obvious" and should not be displayed when printing the grammar
22 public Union(String shortForm) { this(shortForm, false); }
23 public Union(String shortForm, boolean synthetic) {
24 this.shortForm = shortForm;
25 this.synthetic = synthetic;
28 final String shortForm;
29 final boolean synthetic;
30 private final List<Sequence> alternatives = new ArrayList<Sequence>();
32 public Iterator<Sequence> iterator() { return alternatives.iterator(); }
33 public boolean contains(Sequence s) { return alternatives.contains(s); }
35 /** adds an alternative */
36 public void add(Sequence s) {
39 // FIXME: does this make sense?
40 for(Sequence n : s.needs) add(n);
41 for(Sequence n : s.hates) add(n);
44 // Epsilon Form //////////////////////////////////////////////////////////////////////////////
47 public static Union epsilon = new Union("()");
48 static { epsilon.add(Sequence.empty); }
51 private Forest.Ref epsilonForm = null;
52 Forest epsilonForm() {
53 if (epsilonForm != null) return epsilonForm;
54 epsilonForm = new Forest.Ref();
55 for(Sequence s : this) {
57 if (new Walk.Cache().possiblyEpsilon(s))
58 epsilonForm.merge(s.epsilonForm());
63 // Display //////////////////////////////////////////////////////////////////////////////
65 public String toString() { return shortForm; }
66 public StringBuffer toString(StringBuffer sb) {
67 if (synthetic) return sb;
69 if (alternatives.size()==0) {
70 sb.append(StringUtil.pad(15, shortForm) + " = ");
71 } else for(Sequence s : this) {
72 // FIXME: what to do here about printing out negated sequences?
73 sb.append(StringUtil.pad(15, first ? shortForm : "") + (first ? " = " : " | "));
75 sb.append(s.toString());