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 private final String name;
14 private final boolean synthetic;
15 private final List<Sequence> alternatives = new ArrayList<Sequence>();
18 * Since every cycle in a non-degenerate grammar contains at
19 * least one Union, every instance of this class must be able to
20 * display itself in both "long form" (list of the long forms of
21 * its alternatives) and "short form" (some abbreviation).
23 * @param shortForm the "short form" display; usually
24 * @param synthetic if true, this Union's "long form" is "obvious" and should not be displayed when printing the grammar
26 public Union() { this(null, false); }
27 public Union(String name) { this(name, false); }
28 public Union(String name, boolean synthetic) {
30 this.synthetic = synthetic;
33 public Iterator<Sequence> iterator() { return alternatives.iterator(); }
34 public boolean contains(Sequence s) { return alternatives.contains(s); }
36 /** adds an alternative */
37 public void add(Sequence s) {
40 // FIXME: does this make sense?
41 for(Sequence n : s.needs) add(n);
42 for(Sequence n : s.hates) add(n);
45 // Epsilon Form //////////////////////////////////////////////////////////////////////////////
48 public static Union epsilon = new Union("()");
49 static { epsilon.add(Sequence.empty); }
52 private Forest.Many epsilonForm = null;
53 Forest epsilonForm() {
54 if (epsilonForm != null) return epsilonForm;
55 epsilonForm = new Forest.Many();
56 for(Sequence s : this) {
58 if (new Walk.Cache().possiblyEpsilon(s))
59 epsilonForm.merge(s.epsilonForm());
64 // Display //////////////////////////////////////////////////////////////////////////////
66 public String getName() {
67 if (name != null) return name;
68 return "(anon_union)";
70 public String toString() {
71 if (name != null) return name;
72 StringBuffer sb = new StringBuffer();
74 bodyToString(sb, "", " | ");
78 public StringBuffer toString(StringBuffer sb) {
79 if (synthetic) return sb;
81 String before = StringUtil.pad(15, getName()) + " = ";
82 if (alternatives.size()==0) {
87 "\n" + StringUtil.pad(15, "") + " | ");
93 private void bodyToString(StringBuffer sb, String before, String between) {
95 for(Sequence s : this) {
97 // FIXME: what to do here about printing out negated sequences?
98 sb.append(first ? before : between);
100 sb.append(s.toString());