/
func.go
95 lines (79 loc) · 1.9 KB
/
func.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 cgo
import (
"go/ast"
"go/types"
"strings"
)
// FuncWrapper is a wrapper for a Function
type Func struct {
*types.Func
BoundRecv *Named
}
func NewFunc(fun *types.Func) *Func {
return &Func{Func: fun, BoundRecv: nil}
}
func NewBoundFunc(fun *types.Func, boundRecv *Named) *Func {
return &Func{Func: fun, BoundRecv: boundRecv}
}
// Underlying returns the underlying type
func (f Func) Underlying() types.Type {
return f.Type()
}
func (f Func) Signature() *types.Signature {
sig, _ := f.Underlying().(*types.Signature)
return sig
}
func (f Func) IsExportable() bool {
if !f.Exported() {
return false
}
for _, v := range allVars(&f) {
if !ShouldGenerate(v) {
return false
}
}
return true
}
// Underlying returns the string representation of the type (types.Type)
func (f Func) String() string {
return f.FullName() + ": " + types.TypeString(f.Underlying(), nil)
}
func MainFunc() *ast.FuncDecl {
return &ast.FuncDecl{
Name: &ast.Ident{
Name: "main",
},
Type: &ast.FuncType{},
Body: &ast.BlockStmt{},
}
}
// ToAst returns the go/ast representation of the CGo wrapper of the Func type
func (f Func) ToAst() []ast.Decl {
return []ast.Decl{
FuncAst(&f),
}
}
func (f Func) ExportName() string {
return f.CName()
}
func (f Func) PackagePath() string {
return f.Pkg().Path()
}
func (f Func) CName() string {
splitNames := strings.Split(f.Name(), ".")
pkgName := PkgPathAliasFromString(f.PackagePath())
if f.BoundRecv == nil {
return strings.Join([]string{pkgName, splitNames[len(splitNames)-1]}, "_")
} else {
boundName := f.BoundRecv.CShortName()
return strings.Join([]string{pkgName, boundName, splitNames[len(splitNames)-1]}, "_")
}
}
func (f Func) AliasedGoName() ast.Expr {
splitNames := strings.Split(f.Name(), ".")
pkgName := PkgPathAliasFromString(f.PackagePath())
return &ast.SelectorExpr{
X: NewIdent(pkgName),
Sel: NewIdent(splitNames[len(splitNames)-1]),
}
}