-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc_decl.go
87 lines (75 loc) · 2.09 KB
/
func_decl.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
package gorefactor
import (
"github.com/dave/dst"
"github.com/dave/dst/dstutil"
)
// HasFieldInFuncDeclParams checks if the declaration params of the function, contains the given field
func HasFieldInFuncDeclParams(df *dst.File, funcName string, field *dst.Field) (ret bool) {
pre := func(c *dstutil.Cursor) bool {
node := c.Node()
switch node.(type) {
case *dst.FuncDecl:
if nn := node.(*dst.FuncDecl); nn.Name.Name == funcName {
funcType := nn.Type
for _, ff := range funcType.Params.List {
if nodesEqual(ff, field) {
ret = true
}
}
return false
}
}
return true
}
dstutil.Apply(df, pre, nil)
return
}
// DeleteFieldFromFuncDeclParams deletes any field, in the declaration params of the function,
// that is semantically equal to given field
func DeleteFieldFromFuncDeclParams(df *dst.File, funcName string, field *dst.Field) (modified bool) {
pre := func(c *dstutil.Cursor) bool {
node := c.Node()
switch node.(type) {
case *dst.FuncDecl:
if nn := node.(*dst.FuncDecl); nn.Name.Name == funcName {
funcType := nn.Type
var newList []*dst.Field
for _, ff := range funcType.Params.List {
if !nodesEqual(ff, field) {
newList = append(newList, ff)
} else {
modified = true
}
}
funcType.Params.List = newList
return false
}
}
return true
}
dstutil.Apply(df, pre, nil)
return
}
// AddFieldToFuncDeclParams adds given field, to the declaration params of the function, in the given position
func AddFieldToFuncDeclParams(df *dst.File, funcName string, field *dst.Field, pos int) (modified bool) {
pre := func(c *dstutil.Cursor) bool {
node := c.Node()
switch node.(type) {
case *dst.FuncDecl:
nn := node.(*dst.FuncDecl)
if nn.Name.Name == funcName {
funcType := nn.Type
fieldList := funcType.Params.List
pos = normalizePos(pos, len(fieldList))
funcType.Params.List = append(
fieldList[:pos],
append([]*dst.Field{dst.Clone(field).(*dst.Field)}, fieldList[pos:]...)...)
modified = true
return false
}
}
return true
}
dstutil.Apply(df, pre, nil)
return
}