add slow epsilon-ness checker as static method in Element
[sbp.git] / src / edu / berkeley / sbp / Element.java
index c94adbd..a37e960 100644 (file)
@@ -1,24 +1,46 @@
+// (C) 2006-2007 all rights reserved; see LICENSE file for BSD-style license
+
 package edu.berkeley.sbp;
-import edu.berkeley.sbp.util.*;
-import edu.berkeley.sbp.*;
-import edu.berkeley.sbp.*;
-import java.io.*;
 import java.util.*;
-import java.lang.reflect.*;
-import java.lang.ref.*;
 
-/** the root superclass for all components of the grammar (terminals, nonterminals, literals, etc) */
-public abstract class Element {
+/**
+ *  <font color=green>
+ *  the root superclass for all components of the grammar (terminals,
+ *  nonterminals, literals, etc)
+ *  </font>
+ */
+public abstract class Element implements SequenceOrElement {
+
+    /** sorry, you can't make up new, custom elements */
+    Element() { }
 
-    /** if this element always matches exactly one token, return a topology covering exactly those possible tokens, otherwise <tt>null</tt> */
-    abstract Topology toAtom();
+    /** a more verbose version of toString() for displaying whole grammars */
+    abstract StringBuffer toString(StringBuffer sb);
 
-    Forest epsilonForm() { throw new Error("no epsilon form: " + this); }
-    final boolean possiblyEpsilon(Walk.Cache cache) {
-        Boolean ret = cache==null ? null : cache.possiblyEpsilon.get(this);
-        if (ret != null) return ret.booleanValue();
-        ret = new Walk.PossiblyEpsilon().walk(this) ? Boolean.TRUE : Boolean.FALSE;
-        if (cache != null) cache.possiblyEpsilon.put(this, ret);
-        return ret;
+    /** a slow and inefficient epsilon-ness checker used when constructing parse trees (see Union.epsilonForm()) */
+    public static boolean possiblyEpsilon(SequenceOrElement e) {
+        if (e instanceof Atom) return false;
+        if (e instanceof Sequence) {
+            Sequence s = (Sequence)e;
+            for(Sequence.Pos p = s.firstp(); !p.isLast(); p = p.next())
+                if (!possiblyEpsilon(p.element()))
+                    return false;
+            return true;
+        }
+        if (e instanceof Union) {
+            Union u = (Union)e;
+            if (u.visiting) return true;
+            try {
+                u.visiting = true;
+                for(Sequence s : u)
+                    if (possiblyEpsilon(s))
+                        return true;
+                return false;
+            } finally {
+                u.visiting = false;
+            }
+        }
+        throw new Error();
     }
+    boolean visiting = false;
 }