Generate Bind

This commit is contained in:
2024-09-13 18:28:38 -06:00
parent 745d0fa796
commit 3e8b0e663c
5 changed files with 452 additions and 19 deletions

View File

@ -1,5 +1,6 @@
package gigaparsec
//go:generate go run ./internal/bindgen -output bind.go -max 5 -pkg gigaparsec
import (
"errors"
"fmt"
@ -183,25 +184,6 @@ func Slice[T comparable](s []T) Parser[T, []T] {
}
}
func Bind[In, A, B any](p Parser[In, A], f func(A) Parser[In, B]) Parser[In, B] {
return func(input State[In]) (Result[In, B], error) {
resultA, err := p(input)
if err != nil {
return Result[In, B]{}, err
}
if ok, consumed, msg := resultA.Failed(); ok {
return Fail[In, B](consumed, msg), nil
}
_, consumedA, valueA, next, _ := resultA.Succeeded()
resultB, err := f(valueA)(next)
if err != nil {
return Result[In, B]{}, err
}
return resultB.Consume(consumedA || resultB.Consumed()), nil
}
}
func Choose[In, Out any](p Parser[In, Out], ps ...Parser[In, Out]) Parser[In, Out] {
// TODO Check this against the Parsec paper again, and simplify it.
all := append([]Parser[In, Out]{p}, ps...)