forked from vito/go-parse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parsec.go
500 lines (406 loc) · 9.92 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Copied from http://github.com/vito/go-parse
// A few fixes and enhancements
package parsec
import (
"container/vector"
//"fmt"
"reflect"
"unicode"
)
// Container of the input, position, and any user/parser state.
type Vessel interface {
GetState() State
SetState(State)
GetInput() Input
SetInput(Input)
GetPosition() Position
SetPosition(Position)
GetSpec() Spec
SetSpec(Spec)
Get(int) (Input, bool)
Next() (int, bool)
Pop(int)
Push(int)
}
// Specifications for the parser
type Spec struct {
CommentStart string
CommentEnd string
CommentLine string
NestedComments bool
IdentStart Parser
IdentLetter Parser
OpStart Parser
OpLetter Parser
ReservedNames []Output
ReservedOpNames []Output
CaseSensitive bool
}
// A Parser is a function that takes a vessel and returns any matches
// (Output) and whether or not the match was valid.
type Parser func(Vessel) (Output, bool)
// Input type used by vessels
type Input interface{}
// Output of Parsers
type Output interface{}
// Any value can be a vessel's state.
type State interface{}
// Position in the input.
type Position struct {
Name string
Line int
Column int
Offset int
}
// Token that satisfies a condition.
func Satisfy(check func(c int) bool) Parser {
return func(in Vessel) (Output, bool) {
target, ok := in.Next()
if ok && check(target) {
in.Pop(1)
return target, true
}
return nil, false
}
}
// Skip whitespace and comments
func Whitespace() Parser {
return Many(Any(Satisfy(unicode.IsSpace), OneLineComment(), MultiLineComment()))
}
func OneLineComment() Parser {
return func(in Vessel) (Output, bool) {
if in.GetSpec().CommentLine == "" {
return nil, false
}
return Skip(All(
Try(String(in.GetSpec().CommentLine)),
Many(Satisfy(func(c int) bool { return c != '\n' }))))(in)
}
}
func MultiLineComment() Parser {
return func(in Vessel) (Output, bool) {
spec := in.GetSpec()
return Skip(All(
String(spec.CommentStart),
InComment()))(in)
}
}
func InComment() Parser {
return func(in Vessel) (Output, bool) {
if in.GetSpec().NestedComments {
return inMulti()(in)
}
return inSingle()(in)
}
}
func inMulti() Parser {
return func(in Vessel) (Output, bool) {
spec := in.GetSpec()
startEnd := spec.CommentStart + spec.CommentEnd
return Any(
Try(String(spec.CommentEnd)),
All(MultiLineComment(), inMulti()),
All(Many1(NoneOf(startEnd)), inMulti()),
All(OneOf(startEnd), inMulti()))(in)
}
}
func inSingle() Parser {
return func(in Vessel) (Output, bool) {
spec := in.GetSpec()
startEnd := spec.CommentStart + spec.CommentEnd
return Any(
Try(String(spec.CommentEnd)),
All(Many1(NoneOf(startEnd)), inSingle()),
All(OneOf(startEnd), inSingle()))(in)
}
}
func OneOf(cs string) Parser {
return func(in Vessel) (Output, bool) {
next, ok := in.Next()
if !ok {
return nil, false
}
for _, v := range cs {
if v == next {
in.Pop(1)
return v, true
}
}
return next, false
}
}
func NoneOf(cs string) Parser {
return func(in Vessel) (Output, bool) {
next, ok := in.Next()
if !ok {
return nil, false
}
for _, v := range cs {
if v == next {
return v, false
}
}
in.Pop(1)
return next, true
}
}
func Skip(match Parser) Parser {
return func(in Vessel) (Output, bool) {
_, ok := match(in)
return nil, ok
}
}
func Token() Parser {
return func(in Vessel) (next Output, ok bool) {
next, ok = in.Next()
in.Pop(1)
return
}
}
// Match a parser and skip whitespace
func Lexeme(match Parser) Parser {
return func(in Vessel) (Output, bool) {
out, matched := match(in)
if !matched {
return nil, false
}
Whitespace()(in)
return out, true
}
}
// Match a parser 0 or more times.
func Many(match Parser) Parser {
return func(in Vessel) (Output, bool) {
matches := new(vector.Vector)
for {
out, parsed := match(in)
if !parsed {
break
}
if out != nil {
matches.Push(out)
}
}
return matches.Copy(), true
}
}
func Many1(match Parser) Parser {
return func(in Vessel) (Output, bool) {
a, ok := match(in)
if !ok {
return nil, false
}
rest, ok := Many(match)(in)
if !ok {
return nil, false
}
as := rest.(vector.Vector)
as.Insert(0, a)
return as.Copy(), true
}
}
// Match a parser seperated by another parser 0 or more times.
// Trailing delimeters are valid.
func SepBy(delim Parser, match Parser) Parser {
return func(in Vessel) (Output, bool) {
matches := new(vector.Vector)
for {
out, parsed := match(in)
if !parsed {
break
}
matches.Push(out)
_, sep := delim(in)
if !sep {
break
}
}
return matches, true
}
}
// Go through the parsers until one matches.
func Any(parsers ...Parser) Parser {
return func(in Vessel) (Output, bool) {
p := reflect.NewValue(parsers).(*reflect.SliceValue)
for i := 0; i < p.Len(); i++ {
parser := p.Elem(i).Interface().(Parser)
match, ok := parser(in)
if ok {
return match, ok
}
}
return nil, false
}
}
// Match all parsers, returning the final result. If one fails, it stops.
// NOTE: Consumes input on failure. Wrap calls in Try(...) to avoid.
func All(parsers ...Parser) Parser {
return func(in Vessel) (match Output, ok bool) {
p := reflect.NewValue(parsers).(*reflect.SliceValue)
for i := 0; i < p.Len(); i++ {
parser := p.Elem(i).Interface().(Parser)
match, ok = parser(in)
if !ok {
return
}
}
return
}
}
// Match all parsers, collecting their outputs into a vector.
// If one parser fails, the whole thing fails.
// NOTE: Consumes input on failure. Wrap calls in Try(...) to avoid.
func Collect(parsers ...Parser) Parser {
return func(in Vessel) (Output, bool) {
p := reflect.NewValue(parsers).(*reflect.SliceValue)
matches := new(vector.Vector)
for i := 0; i < p.Len(); i++ {
parser := p.Elem(i).Interface().(Parser)
match, ok := parser(in)
if !ok {
return nil, false
}
matches.Push(match)
}
return matches.Copy(), true
}
}
// Try matching begin, match, and then end.
func Between(begin Parser, end Parser, match Parser) Parser {
return func(in Vessel) (Output, bool) {
parse, ok := Try(Collect(begin, match, end))(in)
if !ok {
return nil, false
}
return parse.([]interface{})[1], true
}
}
// Lexeme parser for `match' wrapped in parens.
func Parens(match Parser) Parser { return Lexeme(Between(Symbol("("), Symbol(")"), match)) }
// Match a string and consume any following whitespace.
func Symbol(str string) Parser { return Lexeme(String(str)) }
// Match a string and pop the string's length from the input.
// NOTE: Consumes input on failure. Wrap calls in Try(...) to avoid.
func String(str string) Parser {
return func(in Vessel) (Output, bool) {
for _, v := range str {
next, ok := in.Next()
if !ok || next != v {
return nil, false
}
in.Pop(1)
}
return str, true
}
}
// Try a parse and revert the state and position if it fails.
func Try(match Parser) Parser {
return func(in Vessel) (Output, bool) {
st, pos := in.GetState(), in.GetPosition()
out, ok := match(in)
if !ok {
in.SetState(st)
in.SetPosition(pos)
}
return out, ok
}
}
func Ident() Parser {
return func(in Vessel) (name Output, ok bool) {
sp := in.GetSpec()
n, ok := sp.IdentStart(in)
if !ok {
return
}
ns, ok := Many(sp.IdentLetter)(in)
if !ok {
return
}
rest := make([]int, len(ns.([]interface{})))
for k, v := range ns.([]interface{}) {
rest[k] = v.(int)
}
return string(n.(int)) + string(rest), true
}
}
func Identifier() Parser {
return Lexeme(Try(func(in Vessel) (name Output, ok bool) {
name, ok = Ident()(in)
if !ok {
return
}
for _, v := range in.GetSpec().ReservedNames {
if v == name {
return nil, false
}
}
return name, true
}))
}
// Allows recursion by passing the parser function. Avoids infinite parser
// construction loops.
func Recur(p func() Parser) Parser {
return func(in Vessel) (Output, bool) {
return p()(in)
}
}
// Basic string vessel for parsing over a string input.
type StringVessel struct {
state State
input string
position Position
spec Spec
}
func (self *StringVessel) GetState() State { return self.state }
func (self *StringVessel) SetState(st State) { self.state = st }
func (self *StringVessel) GetInput() Input {
i := 0
for o, _ := range self.input {
if i == self.position.Offset {
return self.input[o:]
}
i++
}
return ""
}
func (self *StringVessel) Get(i int) (Input, bool) {
if len(self.input) < self.position.Offset+i {
return "", false
}
s := ""
n := 0
for _, v := range self.input {
if n >= self.position.Offset {
if n > self.position.Offset+i {
break
}
s += string(v)
}
n++
}
return s, true
}
func (self *StringVessel) Next() (int, bool) {
if len(self.input) < self.position.Offset+1 {
return 0, false
}
i := 0
for _, v := range self.input {
if i == self.position.Offset {
return int(v), true
}
i++
}
return 0, false
}
func (self *StringVessel) Pop(i int) { self.position.Offset += i }
func (self *StringVessel) Push(i int) { self.position.Offset -= i }
func (self *StringVessel) SetInput(in Input) { self.input = in.(string) }
func (self *StringVessel) GetPosition() Position {
return self.position
}
func (self *StringVessel) SetPosition(pos Position) {
self.position = pos
}
func (self *StringVessel) GetSpec() Spec { return self.spec }
func (self *StringVessel) SetSpec(sp Spec) { self.spec = sp }