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 /** display form for the Union (ie not including the RHS) */
29 final String shortForm;
31 /** this is just a hint to use when printing out the grammar in visual form */
32 final boolean synthetic;
34 /** the actual alternatives */
35 private final List<Sequence> alternatives = new ArrayList<Sequence>();
37 public Iterator<Sequence> iterator() { return alternatives.iterator(); }
38 public boolean contains(Sequence s) { return alternatives.contains(s); }
40 /** adds an alternative */
41 public void add(Sequence s) {
44 // FIXME: does this make sense?
45 for(Sequence n : s.needs) add(n);
46 for(Sequence n : s.hates) add(n);
49 // Epsilon Form //////////////////////////////////////////////////////////////////////////////
52 public static Union epsilon = new Union("()");
53 static { epsilon.add(Sequence.empty); }
56 private Forest.Ref epsilonForm = null;
57 Forest epsilonForm() {
58 if (epsilonForm != null) return epsilonForm;
59 epsilonForm = new Forest.Ref();
60 for(Sequence s : this) {
62 if (new Walk.Cache().possiblyEpsilon(s))
63 epsilonForm.merge(s.epsilonForm());
68 // Display //////////////////////////////////////////////////////////////////////////////
70 public String toString() { return shortForm; }
71 public StringBuffer toString(StringBuffer sb) {
72 if (synthetic) return sb;
74 if (alternatives.size()==0) {
75 sb.append(StringUtil.pad(15, shortForm) + " = ");
76 } else for(Sequence s : this) {
77 sb.append(StringUtil.pad(15, first ? shortForm : "") + (first ? " = " : " | "));
79 sb.append(s.toString());