Make Regexp output a string

This commit is contained in:
Brandon Dyck 2024-09-11 14:25:49 -06:00
parent 88dad17ee3
commit ee544cd121

View File

@ -48,21 +48,21 @@ func (rr *RuneReader) Error() error {
return rr.err return rr.err
} }
func Regexp(str string) gigaparsec.Parser[byte, []byte] { func Regexp(str string) gigaparsec.Parser[byte, string] {
if !strings.HasPrefix(str, "^") && !strings.HasPrefix(str, `\A`) { if !strings.HasPrefix(str, "^") && !strings.HasPrefix(str, `\A`) {
str = "^" + str str = "^" + str
} }
re := regexp.MustCompile(str) re := regexp.MustCompile(str)
expected := fmt.Sprintf("match `%s`", str) expected := fmt.Sprintf("match `%s`", str)
return func(input gigaparsec.State[byte]) (gigaparsec.Result[byte, []byte], error) { return func(input gigaparsec.State[byte]) (gigaparsec.Result[byte, string], error) {
r := NewRuneReader(input.Cursor()) r := NewRuneReader(input.Cursor())
idx := re.FindReaderIndex(r) idx := re.FindReaderIndex(r)
err := r.Error() err := r.Error()
if err != nil && !errors.Is(err, io.EOF) { if err != nil && !errors.Is(err, io.EOF) {
return gigaparsec.Result[byte, []byte]{}, fmt.Errorf("Regexp: reader error: %w", err) return gigaparsec.Result[byte, string]{}, fmt.Errorf("Regexp: reader error: %w", err)
} }
if idx == nil { if idx == nil {
return gigaparsec.Fail[byte, []byte](false, gigaparsec.Message{ return gigaparsec.Fail[byte, string](false, gigaparsec.Message{
Pos: input.Pos(), Pos: input.Pos(),
Expected: []string{expected}, Expected: []string{expected},
// TODO Not having a Got is unsatisfactory, but how do I extract useful information? // TODO Not having a Got is unsatisfactory, but how do I extract useful information?
@ -76,9 +76,9 @@ func Regexp(str string) gigaparsec.Parser[byte, []byte] {
n, _, err := input.Cursor().Read(dst) n, _, err := input.Cursor().Read(dst)
if err != nil { if err != nil {
// If we can't access those same bytes again, something is wrong. // If we can't access those same bytes again, something is wrong.
return gigaparsec.Result[byte, []byte]{}, fmt.Errorf("Regexp: unexpected error: %w", err) return gigaparsec.Result[byte, string]{}, fmt.Errorf("Regexp: unexpected error: %w", err)
} }
next := input.At(input.Pos() + n) next := input.At(input.Pos() + n)
return gigaparsec.Succeed(true, dst, next, gigaparsec.MessageOK(input.Pos())), nil return gigaparsec.Succeed(true, string(dst), next, gigaparsec.MessageOK(input.Pos())), nil
} }
} }