-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconst.go
83 lines (67 loc) · 1.52 KB
/
const.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
// Package easyparser provides a Go module parser for AST
package easyparser
import (
"go/constant"
"go/types"
"sort"
"strconv"
tstypes "github.com/go-generalize/go-easyparser/types"
)
type constCandidate struct {
Key string
Value interface{}
}
func (p *Parser) addCandidates(typ, key string, val interface{}) {
arr, ok := p.consts[typ]
if !ok {
arr = make([]constCandidate, 0, 10)
}
p.consts[typ] = append(arr, constCandidate{
Key: key,
Value: val,
})
}
func (p *Parser) parseConst(c *types.Const) {
if !c.Exported() {
return
}
key := c.Name()
switch c.Val().Kind() {
case constant.Int:
v, err := strconv.ParseInt(c.Val().ExactString(), 10, 64)
if err != nil {
return
}
p.addCandidates(c.Type().String(), key, v)
case constant.Float:
v, err := strconv.ParseFloat(c.Val().ExactString(), 64)
if err != nil {
return
}
p.addCandidates(c.Type().String(), key, v)
case constant.String:
unquoted, err := strconv.Unquote(c.Val().ExactString())
if err != nil {
return
}
p.addCandidates(c.Type().String(), key, unquoted)
}
}
func (p *Parser) sortConst() {
for _, v := range p.types {
switch v := v.(type) {
case *tstypes.String:
sort.Slice(v.RawEnum, func(i int, j int) bool {
return v.RawEnum[i].Key < v.RawEnum[j].Key
})
sort.Strings(v.Enum)
case *tstypes.Number:
sort.Slice(v.RawEnum, func(i int, j int) bool {
return v.RawEnum[i].Key < v.RawEnum[j].Key
})
sort.Slice(v.Enum, func(i int, j int) bool {
return v.Enum[i] < v.Enum[j]
})
}
}
}