Move Map and Run onto Parser, and document stuff
This commit is contained in:
+15
-12
@@ -194,6 +194,7 @@ func (p Parser[In, Out]) Label(label string) Parser[In, Out] {
|
||||
}
|
||||
}
|
||||
|
||||
// Where creates a parser that fails if pred does not hold.
|
||||
func (p Parser[In, Out]) Where(pred func(Out) bool) Parser[In, Out] {
|
||||
return func(s State[In]) (Result[In, Out], error) {
|
||||
result, err := p(s)
|
||||
@@ -205,13 +206,15 @@ func (p Parser[In, Out]) Where(pred func(Out) bool) Parser[In, Out] {
|
||||
}
|
||||
}
|
||||
|
||||
type ParseError Message
|
||||
|
||||
func (pe ParseError) Error() string {
|
||||
return Message(pe).String()
|
||||
// Map creates a parser that converts the output of p from Out1 to Out2.
|
||||
func (p Parser[In, Out]) Map[Out2 any](f func(Out) Out2) Parser[In, Out2] {
|
||||
return Bind(p, func(out Out) Parser[In, Out2] {
|
||||
return Return[In](f(out))
|
||||
})
|
||||
}
|
||||
|
||||
func Run[In, Out any](p Parser[In, Out], r ReaderAt[In]) (out Out, err error) {
|
||||
// Run executes a parser on r and returns the result.
|
||||
func (p Parser[In, Out]) Run(r ReaderAt[In]) (out Out, err error) {
|
||||
start := MakeState(r)
|
||||
result, err := p(start)
|
||||
if err != nil {
|
||||
@@ -226,6 +229,12 @@ func Run[In, Out any](p Parser[In, Out], r ReaderAt[In]) (out Out, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type ParseError Message
|
||||
|
||||
func (pe ParseError) Error() string {
|
||||
return Message(pe).String()
|
||||
}
|
||||
|
||||
// Return creates a parser that always succeeds and returns value without consuming any input.
|
||||
func Return[In, Out any](value Out) Parser[In, Out] {
|
||||
return func(state State[In]) (Result[In, Out], error) {
|
||||
@@ -355,13 +364,6 @@ func Try[In, Out any](p Parser[In, Out]) Parser[In, Out] {
|
||||
}
|
||||
}
|
||||
|
||||
// Map creates a parser that converts the output of p from Out1 to 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 Return[In](f(out))
|
||||
})
|
||||
}
|
||||
|
||||
func end[In any](s State[In]) (Result[In, struct{}], error) {
|
||||
_, _, err := s.Read([]In{})
|
||||
if errors.Is(err, io.EOF) {
|
||||
@@ -424,6 +426,7 @@ func Lazy[In, Out any](p func() Parser[In, Out]) Parser[In, Out] {
|
||||
}
|
||||
}
|
||||
|
||||
// Bracket parses p, flanked by left and right.
|
||||
func Bracket[In, Out, LOut, ROut any](left Parser[In, LOut], p Parser[In, Out], right Parser[In, ROut]) Parser[In, Out] {
|
||||
return Seq3(left, p, right, func(_ LOut, val Out, _ ROut) Out { return val })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user