cats-parse icon indicating copy to clipboard operation
cats-parse copied to clipboard

idea for safe repetition on Parser0

Open johnynek opened this issue 3 years ago • 0 comments

We don't allow p.rep on a p: Parser0[_] because if you parse nothing and that is valid, at parse time you would loop infinitely not making progress.

Another idea could be:

def safeRep: Parser0[(NonEmptyList[A], Boolean)] =
  (Parser.index, this, Parser.index)
    .tupled
    .flatMap {
      case (s, a, e) =>
         if (s == e) {
           // No progress, stop
           Parser.pure((NonEmptyList(a, Nil), false))
         }
         else safeRep.?.map {
           case None => (NonEmptyList(a, Nil), true)
           case Some((tail, r)) => (a :: tail, r)
         }
     }

the boolean tells if the last item made progress or not.

johnynek avatar Jan 03 '22 01:01 johnynek