-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
124 lines (110 loc) · 2.27 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
package annotation
import (
"errors"
"strings"
"strconv"
"github.com/alecthomas/participle"
)
type attrValue struct {
Str *string `parser:"@String"`
RStr *string `parser:"| @RawString"`
I *int `parser:"| @Int"`
F *float64 `parser:"| @Float"`
VTrue bool `parser:"| @'true'"`
VFalse bool `parser:"| @'false'"`
}
// value is a helper struct for the parser to parse `parameter="value"` pairs.
type value struct {
Key string `parser:"@Ident'='"`
Value *attrValue `parser:"@@"`
}
// ann is the struct that is used to parse parameters in comments.
type ann struct {
Name string `parser:"'@' @Ident'('"`
Values []*value `parser:"[@@{','@@}]')'"`
}
// Parse finds an ann in a string.
func Parse(s string) (*Annotation, error) {
s = prepareString(s)
if !strings.HasPrefix(s, "@") {
return nil, errors.New("annotation not found in string")
}
a := &ann{}
err := parse(a, s)
if err != nil {
return nil, err
}
ant := NewAnnotation(a.Name)
for _, v := range a.Values {
ant.Set(v.Key, *v.Value)
}
return &ant, err
}
// parse is a helper function that builds the parser.
func parse(a interface{}, s string) (err error) {
p, err := participle.Build(a)
if err != nil {
return err
}
if err := p.ParseString(s, a); err != nil {
return err
}
return
}
func prepareString(s string) string {
return strings.TrimSpace(s)
}
func (v attrValue) String() string {
switch v.Type() {
case STRING:
return *v.Str
case INT:
return strconv.Itoa(*v.I)
case FLOAT:
return strconv.FormatFloat(*v.F, 'f', 4, 64)
case BOOL:
if v.VTrue {
return "true"
}
return "false"
default:
return ""
}
}
func (v attrValue) Int() int {
switch v.Type() {
case INT:
return *v.I
case FLOAT:
return int(*v.F)
default:
i, _ := strconv.ParseInt(v.String(), 10, strconv.IntSize)
return int(i)
}
}
func (v attrValue) Float() float64 {
switch v.Type() {
case FLOAT:
return *v.F
case INT:
return float64(*v.I)
default:
f, _ := strconv.ParseFloat(v.String(), 64)
return f
}
}
func (v attrValue) Bool() bool {
return v.VTrue
}
func (v attrValue) Type() ValueType {
if v.I != nil {
return INT
} else if v.F != nil {
return FLOAT
} else if v.VTrue || v.VFalse {
return BOOL
} else if v.Str != nil {
return STRING
}
return UNKNOWN
}