package main import fmt go ast go parser go token os go format func ma

 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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"go/format"
)
func main() {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, os.Args[1], nil, parser.ParseComments)
makeChanger(file)
if err != nil {
fmt.Println(err)
return
} else {
ast.Fprint(os.Stdout, fset, file, nil)
format.Node(os.Stdout, fset, file)
}
}
func makeChanger(file *ast.File) {
ast.Inspect(file, func(node ast.Node) bool {
if GenDecl, ok := node.(*ast.GenDecl); ok && GenDecl.Tok == token.VAR{
GenDecl.Specs = append([]ast.Spec{
&ast.ValueSpec{nil,
[]*ast.Ident{
ast.NewIdent("countGoFunctions"),
},nil, []ast.Expr{
&ast.BasicLit{GenDecl.TokPos, token.INT, "0"},
},nil,
},
},GenDecl.Specs...)
}
if BlockStmt, ok := node.(*ast.BlockStmt); ok {
newStmtList := make([]ast.Stmt, len(BlockStmt.List) * 2)
fmt.Println(len(BlockStmt.List))
k := 0
for e := 0; e < len(BlockStmt.List); e++{
if GoStmt, ok := BlockStmt.List[e].(*ast.GoStmt); ok{
newStmtList[k] = &ast.IncDecStmt{
&ast.Ident{
BlockStmt.Rbrace, "countGoFunctions", nil,
},
BlockStmt.Rbrace, token.INC,
}
//fmt.Println(e + 1)
fmt.Println(GoStmt)
newStmtList[k + 1] = BlockStmt.List[e]
k++
} else {
//fmt.Println(e)
newStmtList[k] = BlockStmt.List[e]
}
k++
}
i := 0
for i = 0; i < len(newStmtList); i++ {
if newStmtList[i] == nil{
break
}
}
fmt.Println("i = ", i)
BlockStmt.List = make([]ast.Stmt, i)
copy(BlockStmt.List, newStmtList[0:i])
}
return true
})
}