/
parse.go
136 lines (119 loc) · 2.42 KB
/
parse.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
package parse
import (
"io"
"github.com/jimmyfrasche/etlite/internal/ast"
"github.com/jimmyfrasche/etlite/internal/token"
)
//Tokens converts a stream of tokens into a stream of Nodes.
func Tokens(from <-chan token.Value) (to <-chan ast.Node) {
out := make(chan ast.Node)
p := newParser(from, out)
go p.parse()
return out
}
type parser struct {
in <-chan token.Value
out chan<- ast.Node
last token.Value
}
func newParser(tokens <-chan token.Value, nodes chan<- ast.Node) *parser {
p := &parser{
in: tokens,
out: nodes,
}
return p
}
func (p *parser) parse() {
defer func() {
if x := recover(); x != nil {
if err, ok := x.(error); ok && err != io.EOF { //EOF is done so we skip
astErr, ok := x.(*ast.Error)
if !ok {
panic(x) //not an ast error, pass it along
}
p.out <- astErr //send ast error before closing
}
}
close(p.out)
}()
for {
t, ok := <-p.in
if !ok {
return
}
p.last = t
p.out <- p.parseETL(t)
}
}
func (p *parser) next() token.Value {
t, ok := <-p.in
if !ok {
panic(&ast.Error{
Token: p.last,
Err: io.ErrUnexpectedEOF,
})
}
p.last = t
if !t.Valid() {
panic(&ast.Error{
Token: t,
})
}
return t
}
func (p *parser) expect(k token.Kind) token.Value {
t := p.next()
if t.Kind == k {
return t
}
panic(p.unexpected(t))
}
func (p *parser) expectLitOrStr() token.Value {
t := p.next()
if t.Kind == token.Literal || t.Kind == token.String {
return t
}
panic(p.unexpected(t))
}
func (p *parser) expectLit(s string) token.Value {
t := p.expect(token.Literal)
if !t.Literal(s) {
panic(p.unexpected(t))
}
return t
}
func (p *parser) cantBe(ks ...token.Kind) token.Value {
t := p.next()
for _, k := range ks {
if t.Kind == k {
panic(p.unexpected(t))
}
}
return t
}
func astName(ts ...token.Value) ast.Name {
n, err := ast.MakeName(ts)
if err != nil {
panic(err)
}
return n
}
//name reads an (optionally qualified) name and collects the list of tokens
//for further analysis.
func (p *parser) name(t token.Value) (next token.Value, tokens []token.Value, name ast.Name) {
if t.Kind != token.Literal && t.Kind != token.String {
panic(p.unexpected(t))
}
tokens = make([]token.Value, 1, 3)
tokens[0] = t
t = p.next()
if !t.Literal(".") {
//not namespaced, just return
return t, tokens, astName(tokens...)
}
tokens = tokens[:3]
tokens[1] = t
t = p.expectLitOrStr()
tokens[2] = t
return p.next(), tokens, astName(tokens...)
}