changeset 58:24c542f42f75 draft

Remove unnecessary holds from LongestAlternative, provide some comments
author Lewin Bormann <lbo@spheniscida.de>
date Fri, 24 May 2019 00:55:38 +0200
parents 66da7e4ab989
children 25e52ca4cbac
files pcombinators/combinators.py
diffstat 1 files changed, 5 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/pcombinators/combinators.py	Fri May 24 00:53:46 2019 +0200
+++ b/pcombinators/combinators.py	Fri May 24 00:55:38 2019 +0200
@@ -144,6 +144,8 @@
 
     def parse(self, st):
         results = []
+        # We only need to remember where we started in case we need to actually
+        # come back here, i.e. if this is a strict repeat.
         hold = st.hold() if self._strict else None
         i = 0
 
@@ -195,7 +197,9 @@
         return None, st
 
 class LongestAlternative(_Alternative):
-    """Attempt all parsers and return the longest match. Result is result of best parser."""
+    """Attempt all parsers and return the longest match. Result is result of best parser.
+
+    Note: somewhat expensive due to backtracking."""
 
     def parse(self, st):
         matches = []
@@ -204,14 +208,12 @@
         for p in self._parsers:
             r, st2 = p.parse(st)
             if r is None:
-                st.reset(hold)
                 continue
             matches.append((st2.index() - initial, r))
             st = st2
             st.reset(hold)
 
         if len(matches) == 0:
-            st.reset(hold)
             return None, st
         # Stable sort!
         matches.sort(key=lambda t: t[0])