-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathascii.go
81 lines (73 loc) · 1.8 KB
/
ascii.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package pars
import (
"fmt"
"reflect"
"runtime"
"github.com/go-ascii/ascii"
)
// Parsers for matching ASCII character patterns.
var (
Null = Byte(0)
Graphic = ByteRange(32, 126)
Control = Any(ByteRange(0, 31), Byte(127))
Space = Byte(ascii.Space...)
Upper = ByteRange('A', 'Z')
Lower = ByteRange('a', 'z')
Letter = Any(Upper, Lower)
Digit = ByteRange('0', '9')
Latin = Any(Letter, Digit)
)
// Spaces will match as many spaces as possible.
func Spaces(state *State, result *Result) error {
state.Push()
c, err := Next(state)
for err == nil && ascii.IsSpace(c) {
state.Advance()
c, err = Next(state)
}
p, _ := Trail(state)
result.SetToken(p)
return nil
}
// Filter creates a Parser which will attempt to match the given ascii.Filter.
func Filter(filter ascii.Filter) Parser {
v := reflect.ValueOf(filter)
f := runtime.FuncForPC(v.Pointer())
rep := f.Name()
name := fmt.Sprintf("Filter(%s)", rep)
what := fmt.Sprintf("expected to match filter `%s`", rep)
return func(state *State, result *Result) error {
c, err := Next(state)
if err != nil {
return NewNestedError(name, err)
}
if !filter(c) {
return NewError(what, state.Position())
}
state.Advance()
result.SetToken([]byte{c})
return nil
}
}
// Word creates a Parser which will attempt to match a group of bytes which
// satisfy the given filter.
func Word(filter ascii.Filter) Parser {
v := reflect.ValueOf(filter)
f := runtime.FuncForPC(v.Pointer())
rep := f.Name()
what := fmt.Sprintf("expected word of `%s`", rep)
return func(state *State, result *Result) error {
state.Push()
c, err := Next(state)
for err == nil && filter(c) {
state.Advance()
c, err = Next(state)
}
p, _ := Trail(state)
if len(p) == 0 {
return NewError(what, state.Position())
}
result.SetToken(p)
return nil
}
}