Added Label combinator

This commit is contained in:
Brandon Dyck 2024-09-10 15:56:09 -06:00
parent adc85b5572
commit a7495bde87

View File

@ -21,6 +21,11 @@ type Message struct {
Expected []string 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 MessageOK(pos uint64) Message { return Message{Pos: pos} }
func MessageEnd(pos uint64) Message { return Message{Pos: pos, Got: "end of input"} } 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] { 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 Bind(p, func(out Out1) Parser[In, Out2] {
return Return[In](f(out)) return Return[In](f(out))