/
utils.go
95 lines (86 loc) · 2.57 KB
/
utils.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
package errhell
import (
"fmt"
"go/ast"
"go/token"
"strconv"
"strings"
)
var marker = "try"
func checkErr(err error) {
if err != nil {
panic(err)
}
}
var returnStack []*ast.FieldList
var errVarNameStack []int
func genErrVarName() string {
curr := errVarNameStack[len(errVarNameStack)-1]
ret := fmt.Sprintf("_err%d", curr)
curr++
errVarNameStack[len(errVarNameStack)-1] = curr
return ret
}
// matchMarker will extract the number N which in the pattern $(marker)N.
// empty N returns 1.
func matchMarker(name string) int {
if name == marker {
return 1
}
if !strings.HasPrefix(name, marker) {
return 0
}
i, err := strconv.Atoi(name[len(marker):])
if err != nil {
return 0
}
return i
}
// extractTypes flattens multiple names belongs to one type.
func extractTypes(list []*ast.Field) []ast.Expr {
ret := []ast.Expr{}
for _, f := range list {
if len(f.Names) == 0 {
ret = append(ret, f.Type)
continue
}
for range f.Names {
ret = append(ret, f.Type)
}
}
return ret
}
var zeroValueForBasicType = map[string]ast.Expr{
"bool": &ast.Ident{Name: "false"},
"string": &ast.BasicLit{Kind: token.STRING, Value: `""`},
"int": &ast.BasicLit{Kind: token.INT, Value: "0"},
"int8": &ast.BasicLit{Kind: token.INT, Value: "0"},
"int16": &ast.BasicLit{Kind: token.INT, Value: "0"},
"int32": &ast.BasicLit{Kind: token.INT, Value: "0"},
"int64": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uint": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uint8": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uint16": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uint32": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uint64": &ast.BasicLit{Kind: token.INT, Value: "0"},
"uintptr": &ast.BasicLit{Kind: token.INT, Value: "0"},
"byte": &ast.BasicLit{Kind: token.INT, Value: "0"},
"rune": &ast.BasicLit{Kind: token.INT, Value: "0"},
"float32": &ast.BasicLit{Kind: token.INT, Value: "0"},
"float64": &ast.BasicLit{Kind: token.INT, Value: "0"},
"complex64": &ast.BasicLit{Kind: token.INT, Value: "0"},
"complex128": &ast.BasicLit{Kind: token.INT, Value: "0"},
}
// zeroValueLiteralForType returns an expression of zero value of the given type
// which could be written as valid source code. Return nil if not support this
// type.
func zeroValueLiteralForType(tp ast.Expr) ast.Expr {
switch v := tp.(type) {
case *ast.Ident:
return zeroValueForBasicType[v.Name]
case *ast.StarExpr, *ast.FuncType, *ast.ChanType, *ast.ArrayType,
*ast.MapType, *ast.InterfaceType:
return &ast.Ident{Name: "nil"}
}
return nil
}