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

 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
package main
import ("fmt"
"go/ast"
"go/parser"
"go/token"
"go/format"
"os"
)
func insertInc(file *ast.File) {
file.Decls = append(file.Decls,
&ast.GenDecl {
Doc: nil,
TokPos: token.NoPos,
Tok: token.VAR,
Lparen: token.NoPos,
Rparen: token.NoPos,
Specs:[]ast.Spec {
&ast.ValueSpec {
Doc: nil,
Names: []*ast.Ident{
&ast.Ident {
NamePos: token.NoPos,
Name: "counter",
Obj: &ast.Object {
Kind: ast.Var,
Name: "counter",
Decl: nil,
Data: nil,
Type: nil,
},
},
},
Type: &ast.Ident {
NamePos: token.NoPos,
Name: "int",
Obj: nil,
},
Values: nil,
Comment: nil,
},
},
},
)
ast.Inspect(file, func(node ast.Node) bool {
f, ok := node.(*ast.ForStmt)
if ok {
f.Body.List = append (
[] ast.Stmt{
&ast.IncDecStmt {
X: &ast.Ident {
Name: "counter",
NamePos: token.NoPos,
Obj: nil,
},
TokPos: token.NoPos,
Tok : token.INC,
},
}, f.Body.List...,
)
}
return true
})
i:=0
for ;i<len(file.Decls);i++{
if file.Decls[i].Name.Name == "main" {
break;
}
}
file.Decls[i].Body.List = append(file.Decls[i].Body.List,
}
func main(){
if len(os.Args) != 2 {
fmt.Printf("usage lab2.exe <filename.go>\n")
return;
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, os.Args[1], nil, parser.ParseComments)
if err != nil {
return
}
insertInc(file)
ast.Fprint(os.Stdout,fset,file,nil)
format.Node(os.Stdout,fset,file);
}