Added Run convenience function

This commit is contained in:
2024-09-18 13:01:44 -06:00
parent 4455c34735
commit be245b258c
2 changed files with 22 additions and 1 deletions

View File

@ -165,6 +165,27 @@ func (p Parser[In, Out]) Label(label string) Parser[In, Out] {
}
}
type ParseError Message
func (pe ParseError) Error() string {
return Message(pe).String()
}
func Run[In, Out any](p Parser[In, Out], c cursor.Cursor[In]) (out Out, err error) {
start := MakeState(c)
result, err := p(start)
if err != nil {
err = fmt.Errorf("Run: %w", err)
return
}
if failed, _, msg := result.Failed(); failed {
err = ParseError(msg)
return
}
_, _, out, _, _ = result.Succeeded()
return
}
// 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) {