-
Notifications
You must be signed in to change notification settings - Fork 38
/
util.go
73 lines (63 loc) · 1.54 KB
/
util.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
// This file contains utility and helper methods for the transpiler.
package transpiler
import (
goast "go/ast"
"reflect"
)
func isNil(stmt goast.Node) bool {
if stmt == nil {
return true
}
return reflect.ValueOf(stmt).IsNil()
}
func convertDeclToStmt(decls []goast.Decl) (stmts []goast.Stmt) {
for i := range decls {
if decls[i] != nil {
stmts = append(stmts, &goast.DeclStmt{Decl: decls[i]})
}
}
return
}
func combinePreAndPostStmts(
pre []goast.Stmt,
post []goast.Stmt,
newPre []goast.Stmt,
newPost []goast.Stmt) ([]goast.Stmt, []goast.Stmt) {
pre = append(pre, nilFilterStmts(newPre)...)
post = append(post, nilFilterStmts(newPost)...)
return pre, post
}
// nilFilterDecl - remove nil decls from slice
func nilFilterDecl(decls []goast.Decl) (out []goast.Decl) {
for _, decl := range decls {
if isNil(decl) {
panic("Found nil decl")
}
}
return decls
}
// nilFilterStmts - remove nil stmt from slice
func nilFilterStmts(stmts []goast.Stmt) (out []goast.Stmt) {
for _, stmt := range stmts {
if isNil(stmt) {
panic("Found nil stmt")
}
}
return stmts
}
// combineStmts - combine elements to slice
func combineStmts(preStmts []goast.Stmt, stmt goast.Stmt, postStmts []goast.Stmt) (stmts []goast.Stmt) {
stmts = make([]goast.Stmt, 0, 1+len(preStmts)+len(postStmts))
preStmts = nilFilterStmts(preStmts)
if preStmts != nil {
stmts = append(stmts, preStmts...)
}
if !isNil(stmt) {
stmts = append(stmts, stmt)
}
postStmts = nilFilterStmts(postStmts)
if postStmts != nil {
stmts = append(stmts, postStmts...)
}
return
}