-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsec.go
105 lines (86 loc) · 1.68 KB
/
parsec.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
99
100
101
102
103
104
105
package parsec
type Parser interface {
Parse(input string) (bool, string)
}
type notC struct {
raw Parser
}
func NOT(p Parser) Parser {
return notC{p}
}
func (c notC) Parse(input string) (bool, string) {
p := Parser(c.raw)
succ, _ := p.Parse(input)
if succ {
return false, input
}
return true, input
}
func OR(ps ...Parser) Parser {
return orC(ps)
}
type orC []Parser
func (c orC) Parse(input string) (bool, string) {
for _, p := range c {
succ, remain := p.Parse(input)
if succ {
return succ, remain
}
}
return false, input
}
func SEQ(ps ...Parser) Parser {
return seqC(ps)
}
type seqC []Parser
func (c seqC) Parse(input string) (bool, string) {
var succ bool
remain := input
for _, p := range c {
succ, remain = p.Parse(remain)
if !succ {
return false, input
}
continue
}
return true, remain
}
type Literal string
func (s Literal) Parse(input string) (bool, string) {
if len(input) >= len(s) && input[:len(s)] == string(s) {
return true, input[len(s):]
}
return false, input
}
type Byte byte
func (s Byte) Parse(input string) (bool, string) {
if len(input) > 0 && input[0] == byte(s) {
return true, input[1:]
}
return false, input
}
func Range(start, end byte) Parser {
return rangeLit{start, end}
}
type rangeLit struct {
start byte
end byte
}
func (r rangeLit) Parse(input string) (bool, string) {
if len(input) > 0 {
if input[0] >= r.start && input[0] <= r.end {
return true, input[1:]
}
}
return false, input
}
type WhiteSpace struct{}
func (w WhiteSpace) Parse(input string) (bool, string) {
var succ bool
remain := input
for len(remain) > 0 && remain[0] == ' ' {
succ = true
remain = remain[1:]
}
return succ, remain
}