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 }) }