-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
116 lines (102 loc) · 2.19 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
package zc
import (
"unicode"
"github.com/blackchip-org/scan"
)
const (
TokenValue = "value"
TokenName = "name"
)
type valueRule struct{}
func (r valueRule) Eval(s *scan.Scanner) bool {
if !IsValuePrefix(s.This, s.Next) {
return false
}
s.Type = TokenValue
s.Keep()
scan.While(s, scan.Not(scan.IsSpace), s.Keep)
return true
}
type slashValueRule struct{}
func (r slashValueRule) Eval(s *scan.Scanner) bool {
if s.This != '/' {
return false
}
s.Type = TokenValue
s.Skip()
scan.While(s, scan.Not(scan.IsSpace), s.Keep)
return true
}
var rules = scan.NewRuleSet(
scan.SkipSpaceRule,
scan.StrDoubleQuoteRule.
WithType(TokenValue).
WithOptionalTerminator(true),
scan.StrSingleQuoteRule.WithType(TokenValue).
WithType(TokenValue).
WithOptionalTerminator(true),
scan.NewStrRule('[', ']').
WithType(TokenValue).
WithOptionalTerminator(true).
WithNesting(true),
valueRule{},
slashValueRule{},
scan.NewWhileRule(scan.Not(scan.IsSpace), TokenName),
).WithNoMatchFunc(scan.UnexpectedUntil(scan.IsSpace))
func ScanWords(line string) []scan.Token {
s := scan.NewScannerFromString("", line)
runner := scan.NewRunner(s, rules)
return runner.All()
}
func isDecoration(r rune) bool {
if r == ',' || r == '_' || r == ' ' {
return true
}
// Currency symbols
if unicode.Is(unicode.Sc, r) {
return true
}
return false
}
func isAltExponent(s *scan.Scanner) bool {
return (s.This == 'x' || s.This == '×') && s.Next == '1' && s.Peek(2) == '0'
}
func PreParseInt(str string) string {
s := scan.NewScannerFromString("", str)
for s.HasMore() {
switch {
case isDecoration(s.This):
s.Skip()
default:
s.Keep()
}
}
return s.Emit().Val
}
func PreParseDecimal(str string) string {
s := scan.NewScannerFromString("", str)
for s.HasMore() {
switch {
case isDecoration(s.This):
s.Skip()
case isAltExponent(s):
scan.Repeat(s.Skip, 3)
s.Val.WriteRune('e')
default:
s.Keep()
}
}
return s.Emit().Val
}
func IsValuePrefix(ch rune, next rune) bool {
switch {
case unicode.IsDigit(ch):
return true
// Currency symbols
case unicode.Is(unicode.Sc, ch):
return true
case (ch == '-' || ch == '+' || ch == '.') && unicode.IsDigit(next):
return true
}
return false
}