-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
98 lines (84 loc) · 1.61 KB
/
parser.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package git
import (
"strings"
"unicode"
)
type parser func(string) (string, []string)
type combinator func(string) (string, string)
func separatedPair(first, sep, second combinator) parser {
return func(s string) (string, []string) {
out := make([]string, 0, 2)
str, ret := first(s)
out = append(out, ret)
str, _ = sep(str)
str, ret = second(str)
out = append(out, ret)
return str, out
}
}
func tag(tag string) combinator {
return func(s string) (string, string) {
if strings.HasPrefix(s, tag) {
return s[len(tag):], tag
}
return s, ""
}
}
func ws() combinator {
return func(s string) (string, string) {
for i, c := range s {
if !unicode.IsSpace(c) {
return s[i:], s[:i]
}
}
return s, ""
}
}
func until(delim string) combinator {
return func(s string) (string, string) {
if i := strings.Index(s, delim); i > -1 {
return s[i:], s[:i]
}
return s, ""
}
}
func line() combinator {
return func(s string) (string, string) {
if i := strings.Index(s, "\n"); i > 0 {
j := i
if j > 1 && s[j-1] == '\r' {
j = j - 1
}
if len(s) == i {
return "", s[:j]
}
return s[i+1:], s[:j]
}
return s, ""
}
}
type condition func(string) int
func alphanumeric(str string) int {
for i, b := range str {
if unicode.IsLetter(b) || unicode.IsNumber(b) {
return i
}
}
return -1
}
func lineEnding(str string) int {
for i, b := range str {
if b == '\r' || b == '\n' {
return i
}
}
return -1
}
func takeUntil(cond condition) combinator {
return func(s string) (string, string) {
if i := cond(s); i != -1 {
return s[i:], s[:i]
}
return s, s
}
}