-
Notifications
You must be signed in to change notification settings - Fork 0
/
satisfy.go
34 lines (29 loc) · 1.07 KB
/
satisfy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package token
import (
"github.com/flier/gocombine/pkg/parser"
"github.com/flier/gocombine/pkg/stream"
)
// Satisfy parses a token and succeeds depending on the result of `predicate`.
func Satisfy[T stream.Token](predicate func(T) bool) parser.Func[T, T] {
return parser.Expected(func(input []T) (actual T, remaining []T, err error) {
if actual, remaining, err = stream.Uncons(input); err != nil {
// pass
} else if !predicate(actual) {
err = parser.UnexpectedToken(actual)
}
return
}, "satisfy")
}
// SatisfyMap parses a token and passes it to `predicate`. If `predicate` succeeds and returns the value.
// If `predicate` returns error the parser fails without consuming any input.
func SatisfyMap[T stream.Token, O any](predicate func(T) (O, error)) parser.Func[T, O] {
return parser.Expected(func(input []T) (out O, remaining []T, err error) {
var actual T
if actual, remaining, err = stream.Uncons(input); err != nil {
// pass
} else if out, err = predicate(actual); err != nil {
err = parser.UnexpectedToken(actual)
}
return
}, "satisfy map")
}