Added Run convenience function

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

View File

@ -1,7 +1,7 @@
Add a convenient way to run parsers
Add repetition parsers to avoid some recursion Add repetition parsers to avoid some recursion
Think about not requiring so much Pos() when making messages Think about not requiring so much Pos() when making messages
Rename Seq2 to Seq Rename Seq2 to Seq
Document Seq Document Seq
Should MakeState be private now that there's Run?
Add SPDX tags Add SPDX tags
What's Megaparsec got that we ain't got? What's Megaparsec got that we ain't got?

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. // Return creates a parser that always succeeds and returns value without consuming any input.
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) {