-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmust.go
111 lines (92 loc) · 1.96 KB
/
must.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
package builtin
import (
"fmt"
"go/ast"
"go/token"
"golang.org/x/tools/go/ast/astutil"
"github.com/rocketlaunchr/igo/common"
)
func replaceMustFunc(c *astutil.Cursor, arg1 *ast.CallExpr, arg2 ast.Expr) {
// Assignment
res1 := ast.NewIdent(common.RandSeq(6))
res2 := ast.NewIdent(common.RandSeq(6))
ass := &ast.AssignStmt{
Lhs: []ast.Expr{
res1,
res2,
},
Tok: token.DEFINE,
Rhs: []ast.Expr{
arg1,
},
}
var panicCall ast.Expr
if arg2 == nil {
panicCall = res2
} else {
panicCall = &ast.CallExpr{
Fun: arg2,
Args: []ast.Expr{
res2,
},
}
}
// Error to panic
ifStmt := &ast.IfStmt{
Cond: &ast.BinaryExpr{
X: res2,
Op: token.NEQ,
Y: ast.NewIdent("nil"),
},
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: ast.NewIdent("panic"),
Args: []ast.Expr{
panicCall,
},
},
},
},
},
}
insert := []ast.Stmt{ass, ifStmt}
row := current().idx
node := current().ref
c.Replace(res1)
switch n := node.(type) {
case *ast.BlockStmt:
n.List = append(n.List[:row], append(insert, n.List[row:]...)...)
case *ast.CommClause:
n.Body = append(n.Body[:row], append(insert, n.Body[row:]...)...)
case *ast.CaseClause:
n.Body = append(n.Body[:row], append(insert, n.Body[row:]...)...)
}
updateIdx(len(insert))
}
func isMustFunc(call *ast.CallExpr) (bool, *ast.CallExpr, ast.Expr) {
// Check name
t1, ok := call.Fun.(*ast.Ident)
if !ok {
return false, nil, nil
}
if t1.Name != "must" {
return false, nil, nil
}
if len(call.Args) == 0 {
panic("missing arguments to must")
} else if len(call.Args) > 2 {
panic("too many arguments to must")
}
// Is the first arg a function call?
t2, ok := call.Args[0].(*ast.CallExpr)
if !ok {
panic(fmt.Sprintf("invalid operation: must (first argument has type %T, expecting function call)", call.Args[0]))
}
if len(call.Args) == 1 {
return true, t2, nil
} else {
return true, t2, call.Args[1]
}
}