From a7495bde87575f8be93bba3bcc7bcd331d4982f6 Mon Sep 17 00:00:00 2001 From: Brandon Dyck Date: Tue, 10 Sep 2024 15:56:09 -0600 Subject: [PATCH] Added Label combinator --- gigaparsec.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/gigaparsec.go b/gigaparsec.go index f33f6ad..f13e9bd 100644 --- a/gigaparsec.go +++ b/gigaparsec.go @@ -21,6 +21,11 @@ type Message struct { Expected []string } +func (m Message) expect(s string) Message { + m.Expected = []string{s} + return m +} + func MessageOK(pos uint64) Message { return Message{Pos: pos} } func MessageEnd(pos uint64) Message { return Message{Pos: pos, Got: "end of input"} } @@ -189,6 +194,25 @@ func Try[In, Out any](p Parser[In, Out]) Parser[In, Out] { } } +func Label[In, Out any](p Parser[In, Out], l string) Parser[In, Out] { + return func(input State[In]) (consumed bool, reply Result[In, Out], err error) { + consumed, reply, err = p(input) + if consumed { + return + } + if err == nil { + reply.Message = reply.Message.expect(l) + return + } + var parseErr ParseError + if errors.As(err, &parseErr) { + err = ParseError(Message(parseErr).expect(l)) + return + } + return + } +} + func Map[In, Out1, Out2 any](p Parser[In, Out1], f func(Out1) Out2) Parser[In, Out2] { return Bind(p, func(out Out1) Parser[In, Out2] { return Return[In](f(out))