/
func_lit.go
72 lines (61 loc) · 1.57 KB
/
func_lit.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
package gorefactor
import (
"github.com/dave/dst"
"github.com/dave/dst/dstutil"
)
// AddStmtToFuncLitBody add statement to anonymous function body
func AddStmtToFuncLitBody(df *dst.File, scope Scope, stmt dst.Stmt, pos int) (modified bool) {
pre := func(c *dstutil.Cursor) bool {
node := c.Node()
switch node.(type) {
case *dst.FuncLit:
if !scope.IsInScope() {
return true
}
nn := node.(*dst.FuncLit)
stmtList := nn.Body.List
pos = normalizePos(pos, len(stmtList))
nn.Body.List = append(
stmtList[:pos],
append([]dst.Stmt{dst.Clone(stmt).(dst.Stmt)}, stmtList[pos:]...)...)
modified = true
default:
scope.TryEnterScope(node)
}
return true
}
post := func(c *dstutil.Cursor) bool {
scope.TryLeaveScope(c.Node())
return true
}
dstutil.Apply(df, pre, post)
return
}
// AddFieldToFuncLitParams add statement to anonymous function params
func AddFieldToFuncLitParams(df *dst.File, scope Scope, field *dst.Field, pos int) (modified bool) {
pre := func(c *dstutil.Cursor) bool {
node := c.Node()
switch node.(type) {
case *dst.FuncLit:
if !scope.IsInScope() {
return true
}
nn := node.(*dst.FuncLit)
fieldList := nn.Type.Params.List
pos = normalizePos(pos, len(fieldList))
nn.Type.Params.List = append(
fieldList[:pos],
append([]*dst.Field{dst.Clone(field).(*dst.Field)}, fieldList[pos:]...)...)
modified = true
default:
scope.TryEnterScope(node)
}
return true
}
post := func(c *dstutil.Cursor) bool {
scope.TryLeaveScope(c.Node())
return true
}
dstutil.Apply(df, pre, post)
return
}