Make Label a method on Parser

This commit is contained in:
Brandon Dyck 2024-09-13 11:35:13 -06:00
parent a223f18f02
commit 8e7a9760c6
2 changed files with 15 additions and 14 deletions

View File

@ -2,3 +2,4 @@ Test RuneReader
Test Regexp Test Regexp
Add SPDX tags Add SPDX tags
What's Megaparsec got that we ain't got? What's Megaparsec got that we ain't got?
Add Do parser that runs an action on the result of the previous parser.

View File

@ -125,6 +125,20 @@ func (s State[In]) At(pos uint64) State[In] {
type Parser[In, Out any] func(State[In]) (Result[In, Out], error) type Parser[In, Out any] func(State[In]) (Result[In, Out], error)
func (p Parser[In, Out]) Label(label string) Parser[In, Out] {
return func(input State[In]) (Result[In, Out], error) {
result, err := p(input)
if err != nil || result.Consumed() {
return result, err
}
if succeeded, _, value, next, msg := result.Succeeded(); succeeded {
return Succeed(false, value, next, msg.expect(label)), nil
}
_, _, msg := result.Failed()
return Fail[In, Out](false, msg.expect(label)), nil
}
}
func Return[In, Out any](value Out) Parser[In, Out] { func Return[In, Out any](value Out) Parser[In, Out] {
return func(state State[In]) (Result[In, Out], error) { return func(state State[In]) (Result[In, Out], error) {
return Succeed(false, value, state, MessageOK(state.Pos())), nil return Succeed(false, value, state, MessageOK(state.Pos())), nil
@ -246,20 +260,6 @@ 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]) (Result[In, Out], error) {
result, err := p(input)
if err != nil || result.Consumed() {
return result, err
}
if succeeded, _, value, next, msg := result.Succeeded(); succeeded {
return Succeed(false, value, next, msg.expect(l)), nil
}
_, _, msg := result.Failed()
return Fail[In, Out](false, msg.expect(l)), nil
}
}
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))