This repository has been archived by the owner on Aug 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
104 lines (95 loc) · 2.51 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
99
100
101
102
103
104
package pqarrays
import (
"errors"
)
func parse(l *lexer) ([]*string, error) {
var parsed []*string
pchan := make(chan *string)
errchan := make(chan error)
done := make(chan struct{})
go runParse(l, pchan, errchan, done)
for {
select {
case err := <-errchan:
return parsed, err
case item := <-pchan:
parsed = append(parsed, item)
case <-done:
return parsed, nil
}
}
}
func runParse(l *lexer, parsed chan *string, err chan error, done chan struct{}) {
var state parseFunc = parseStart
for {
var e error
state, e = state(l, parsed)
if e != nil {
err <- e
break
}
if state == nil {
break
}
}
close(done)
}
type parseFunc func(*lexer, chan *string) (parseFunc, error)
func parseEOF(l *lexer, parsed chan *string) (parseFunc, error) {
tok := l.nextToken()
if tok.typ == tokenWhitespace {
return parseEOF, nil
}
if tok.typ != tokenEOF {
return nil, errors.New("expected EOF, got " + tok.String())
}
return nil, nil
}
func parseStringOrNull(l *lexer, parsed chan *string) (parseFunc, error) {
tok := l.nextToken()
if tok.typ == tokenWhitespace {
return parseStringOrNull, nil
} else if tok.typ == tokenString {
parsed <- &tok.val
return parseSeparatorOrDelim, nil
} else if tok.typ == tokenNull {
parsed <- nil
return parseSeparatorOrDelim, nil
}
return nil, errors.New("expected string, got " + tok.String())
}
func parseStringOrNullOrEnd(l *lexer, parsed chan *string) (parseFunc, error) {
tok := l.nextToken()
if tok.typ == tokenWhitespace {
return parseStringOrNullOrEnd, nil
} else if tok.typ == tokenString {
parsed <- &tok.val
return parseSeparatorOrDelim, nil
} else if tok.typ == tokenNull {
parsed <- nil
return parseSeparatorOrDelim, nil
} else if tok.typ == tokenArrayEnd {
return parseEOF, nil
}
return nil, errors.New("Expected string or end, got " + tok.String())
}
func parseSeparatorOrDelim(l *lexer, parsed chan *string) (parseFunc, error) {
tok := l.nextToken()
if tok.typ == tokenWhitespace {
return parseSeparatorOrDelim, nil
} else if tok.typ == tokenSeparator {
return parseStringOrNull, nil
} else if tok.typ == tokenArrayEnd {
return parseEOF, nil
}
return nil, errors.New("expected separator or delim, got " + tok.String())
}
func parseStart(l *lexer, parsed chan *string) (parseFunc, error) {
tok := l.nextToken()
if tok.typ == tokenWhitespace {
return parseStart, nil
} else if tok.typ == tokenArrayStart {
return parseStringOrNullOrEnd, nil
}
return nil, errors.New("expected separator or delim, got " + tok.String())
}