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.*;
11 * <font color=green>an element which can produce one of several alternatives</font>.
14 * Unlike the other Elements, Union is not immutable once
15 * constructed. To simulate this desirable feature, it is immutable
16 * <i>once examined</i> by taking its iterator or calling contains().
18 public class Union extends Element implements Iterable<Sequence> {
20 private final String name;
21 private final boolean synthetic;
22 private boolean viewed = false;
24 private final List<Sequence> alternatives = new ArrayList<Sequence>();
26 public Union(String name) { this(name, false); }
29 * Since every cycle in a non-degenerate grammar contains at
30 * least one Union, every instance of this class must be able to
31 * display itself in both "long form" (list of the long forms of
32 * its alternatives) and "short form" (some name).
34 * @param shortForm the "short form" display; for display purposes only
35 * @param synthetic if true, this Union's "long form" is "obvious" and should not be displayed when printing the grammar
37 public Union(String name, boolean synthetic) {
39 this.synthetic = synthetic;
42 public boolean contains(Sequence s) {
44 return alternatives.contains(s);
47 /** iterator over this Union's Sequences */
48 public Iterator<Sequence> iterator() {
50 return alternatives.iterator();
53 /** adds an alternative */
54 public void add(Sequence s) {
56 throw new RuntimeException("attempt to add a Sequence to a Union that has already been examined");
57 if (alternatives.contains(s)) return;
62 // Epsilon Form //////////////////////////////////////////////////////////////////////////////
65 private Forest.Many epsilonForm = null;
66 Forest epsilonForm() {
67 if (epsilonForm != null) return epsilonForm;
68 epsilonForm = new Forest.Many();
69 for(Sequence s : this) {
71 if (new Walk.Cache().possiblyEpsilon(s))
72 epsilonForm.merge(s.epsilonForm());
78 // Display //////////////////////////////////////////////////////////////////////////////
80 public String getName() {
81 if (name != null) return name;
82 return "(anon_union)";
84 public String toString() {
86 if (name != null) return name;
87 StringBuffer sb = new StringBuffer();
89 bodyToString(sb, "", " | ");
94 /** display this union in long/expanded form */
95 public StringBuffer toString(StringBuffer sb) {
97 if (synthetic) return sb;
99 String before = StringUtil.pad(15, getName()) + " = ";
100 if (alternatives.size()==0) {
105 "\n" + StringUtil.pad(15, "") + " | ");
111 private void bodyToString(StringBuffer sb, String before, String between) {
113 boolean first = true;
114 for(Sequence s : this) {
115 // FIXME: what to do here about printing out negated sequences?
116 sb.append(first ? before : between);
118 sb.append(s.toString());