forked from bigwhite/functrace
/
rewrite.go
134 lines (116 loc) · 2.51 KB
/
rewrite.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package generator
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"golang.org/x/tools/go/ast/astutil"
)
func hasFuncDecl(f *ast.File) bool {
if len(f.Decls) == 0 {
return false
}
for _, decl := range f.Decls {
_, ok := decl.(*ast.FuncDecl)
if ok {
return true
}
}
return false
}
func hasImport(f *ast.File, pkgName string) bool {
for _, decl := range f.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok && genDecl.Tok == token.IMPORT {
// iterate through import specs
for _, spec := range genDecl.Specs {
if importSpec, ok := spec.(*ast.ImportSpec); ok {
if importSpec.Path.Value == `"`+pkgName+`"` {
return true
}
}
}
}
}
return false
}
func Rewrite(filename string) ([]byte, error) {
fset := token.NewFileSet()
oldAST, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("error parsing %s: %w", filename, err)
}
//fmt.Printf("%#v\n", *oldAST)
if !hasFuncDecl(oldAST) {
return nil, nil
}
// add import declaration
astutil.AddImport(fset, oldAST, "github.com/pengxuan37/functrace")
//fmt.Printf("added=%#v\n", added)
// inject code into each function declaration
addDeferTraceIntoFuncDecls(oldAST)
buf := &bytes.Buffer{}
err = format.Node(buf, fset, oldAST)
if err != nil {
return nil, fmt.Errorf("error formatting new code: %w", err)
}
return buf.Bytes(), nil
}
func addDeferTraceIntoFuncDecls(f *ast.File) {
for _, decl := range f.Decls {
fd, ok := decl.(*ast.FuncDecl)
if ok {
// inject code to fd
addDeferStmt(fd)
}
}
}
func addDeferStmt(fd *ast.FuncDecl) (added bool) {
stmts := fd.Body.List
// check whether "defer functrace.Trace()()" has already exists
for _, stmt := range stmts {
ds, ok := stmt.(*ast.DeferStmt)
if !ok {
continue
}
// it is a defer stmt
ce, ok := ds.Call.Fun.(*ast.CallExpr)
if !ok {
continue
}
se, ok := ce.Fun.(*ast.SelectorExpr)
if !ok {
continue
}
x, ok := se.X.(*ast.Ident)
if !ok {
continue
}
if (x.Name == "functrace") && (se.Sel.Name == "Trace") {
// already exist , return
return false
}
}
// not found "defer functrace.Trace()()"
// add one
ds := &ast.DeferStmt{
Call: &ast.CallExpr{
Fun: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{
Name: "functrace",
},
Sel: &ast.Ident{
Name: "Trace",
},
},
},
},
}
newList := make([]ast.Stmt, len(stmts)+1)
copy(newList[1:], stmts)
newList[0] = ds
fd.Body.List = newList
return true
}