cats-parse
cats-parse copied to clipboard
idea for safe repetition on Parser0
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.