-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
135 lines (113 loc) · 2.42 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
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
package stock_parser
const (
MarketHK = "HK"
MarketUS = "US"
)
func Parse(input string, cb func(code, market, match string) string) (out string) {
parser := newParser(input)
parser.consumeNode(parser.root, cb)
if parser.out == "" {
return input
}
return parser.out
}
type rn []rune
func (r rn) str(node *node32) string {
if node == nil || int(node.begin) < 0 || int(node.end) > len(r) {
return ""
}
return string(r[node.begin:node.end])
}
type parser struct {
r rn
input string
out string
root *node32
}
func newParser(input string) *parser {
p := StockCodeParser{Buffer: input}
p.Init()
if err := p.Parse(); err != nil {
return nil
}
return &parser{
input: input,
r: rn([]rune(input)),
root: p.AST(),
}
}
func (p *parser) consumeNode(node *node32, cb func(node, market, match string) string) (out string) {
for node != nil {
code := ""
market := ""
match := ""
if node.pegRule == ruleStock {
code, market, match = p.parseStock(node)
} else if node.pegRule == ruleXLStock {
code, market, match = p.parseXLStock(node)
} else if node.pegRule == ruleFTStock {
code, market, match = p.parseFTStock(node)
}
if code != "" {
if market == "" {
market = MarketUS
}
p.out = cb(code, market, match)
}
if node.up != nil {
p.consumeNode(node.up, cb)
}
node = node.next
}
return
}
func (p *parser) parseFTStock(node *node32) (code, market, match string) {
r := p.r
match = r.str(node)
subNode := node.up
for subNode != nil {
switch subNode.pegRule {
case ruleCode:
code = r.str(subNode)
case ruleMarket:
market = r.str(subNode)
}
subNode = subNode.next
}
return
}
func (p *parser) parseXLStock(node *node32) (code, market, match string) {
r := p.r
match = r.str(node)
subNode := node.up
for subNode != nil {
switch subNode.pegRule {
case ruleUSCode, ruleACode:
code = r.str(subNode)
case ruleHKCode, ruleHSCODE:
code = r.str(subNode)
market = MarketHK
case ruleMarket, ruleCNMarket, ruleHKMarket:
market = r.str(subNode)
}
subNode = subNode.next
}
return
}
func (p *parser) parseStock(node *node32) (code, market, match string) {
r := p.r
match = r.str(node)
subNode := node.up
for subNode != nil {
switch subNode.pegRule {
case ruleCode, ruleUSCode:
code = r.str(subNode)
case ruleMarket:
market = r.str(subNode)
case ruleSuffix:
market = r.str(subNode.up)
}
subNode = subNode.next
}
return
}