forked from aloder/tojen
/
main.go
211 lines (191 loc) · 5.01 KB
/
main.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package gen
import (
"bytes"
"go/ast"
"go/parser"
"go/token"
"strconv"
"strings"
"github.com/dave/jennifer/jen"
)
var jenImp = "github.com/dave/jennifer/jen"
func funcDecl(s *ast.FuncDecl) jen.Code {
ret := jen.Qual("github.com/dave/jennifer/jen", "Func").Call()
if s.Recv != nil {
ret.Dot("Params").Call(fieldList(s.Recv)...)
}
ret.Add(ident(s.Name))
ret.Add(funcType(s.Type))
ret.Add(blockStmt(s.Body))
return ret
}
var paths = map[string]string{}
//var formating = false
// GenerateFileBytes takes an array of bytes and transforms it into jennifer
// code
func GenerateFileBytes(s []byte, packName string, main bool, formating bool) ([]byte, error) {
file := GenerateFile(s, packName, main)
b := &bytes.Buffer{}
err := file.Render(b)
if err != nil {
return s, err
}
ret := b.Bytes()
if formating {
ret = formatNulls(ret)
ret = formatStructs(ret)
ret = formatBlock(ret)
ret = formatParams(ret)
ret, err = goFormat(ret)
if err != nil {
return ret, err
}
}
return ret, nil
}
func imports(imports []*ast.ImportSpec) (map[string]string, []jen.Code) {
p := make(map[string]string)
anonImports := []jen.Code{}
for _, i := range imports {
pathVal := i.Path.Value[1 : len(i.Path.Value)-1]
name := pathVal
if i.Name == nil {
idx := strings.Index(pathVal, "/")
if idx != -1 {
name = pathVal[idx+1:]
}
} else {
name = i.Name.String()
if name == "." {
panic(". imports not supported")
}
if name == "_" {
anonImports = append(anonImports, jen.Lit(pathVal))
continue
}
}
p[name] = pathVal
}
return p, anonImports
}
// GenerateFile Generates a jennifer file given a series of bytes a package name
// and if you want a main function or not
func GenerateFile(s []byte, packName string, main bool) *jen.File {
file := jen.NewFile(packName)
astFile := parseFile(s)
var anonImports []jen.Code
// paths is a global variable to map the exported object to the import
paths, anonImports = imports(astFile.Imports)
// generate the generative code based on the file
decls := []string{}
for _, decl := range astFile.Decls {
code, name := makeJenCode(decl)
file.Add(code)
decls = append(decls, name)
}
// generate the function that pieces togeather all the code
var codes []jen.Code
codes = append(codes, genNewJenFile(astFile.Name.String()))
// add anon imports i.e. _ for side effects
if len(anonImports) > 0 {
codes = append(codes, jen.Id("ret").Dot("Anon").Call(anonImports...))
}
// add the generated functions to the created jen file
for _, name := range decls {
codes = append(codes, jen.Id("ret").Dot("Add").Call(jen.Id(name).Call()))
}
// return the created jen file
codes = append(codes, jen.Return().Id("ret"))
// add the patch function to the output file
file.Add(
jen.Func().Id("genFile").Params().Op("*").Qual(jenImp, "File").Block(codes...),
)
// if main then generate a main function that prints out the output of the
// patch function
if main {
file.Add(genMainFunc())
}
return file
}
func genNewJenFile(name string) jen.Code {
return jen.Id("ret").Op(":=").Qual(jenImp, "NewFile").Call(jen.Lit(name))
}
func genMainFunc() jen.Code {
return jen.Func().Id("main").Params().Block(
jen.Id("ret").Op(":=").Id("genFile").Call(),
jen.Qual("fmt", "Printf").Call(
jen.Lit("%#v"),
jen.Id("ret"),
),
)
}
func makeJenCode(s ast.Decl) (jen.Code, string) {
inner := jen.Null()
name := ""
switch t := s.(type) {
case *ast.GenDecl:
name = "genDeclAt" + strconv.Itoa(int(t.TokPos))
inner.Add(genDecl(t))
case *ast.FuncDecl:
name = "genFunc" + t.Name.String()
inner.Add(funcDecl(t))
}
return makeJenFileFunc(name, inner), name
}
func makeJenFileFunc(name string, block jen.Code) jen.Code {
return jen.Func().Id(name).Params().Qual(jenImp, "Code").Block(
jen.Return().Add(block),
)
}
func parseFile(code []byte) *ast.File {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", code, parser.ParseComments)
if err != nil {
panic(err)
}
return f
}
func genDecl(g *ast.GenDecl) jen.Code {
ret := jen.Qual(jenImp, "Null").Call()
for _, spec := range g.Specs {
switch s := spec.(type) {
case *ast.ValueSpec:
ret.Add(valueSpec(s))
case *ast.TypeSpec:
ret.Add(typeSpec(s))
}
}
return ret
}
func typeSpec(s *ast.TypeSpec) jen.Code {
return jen.Dot("Type").Call().Add(ident(s.Name)).Add(genExpr(s.Type))
}
func valueSpec(s *ast.ValueSpec) jen.Code {
ret := jen.Dot("Var").Call()
ret.Add(identsList(s.Names))
ret.Add(genExpr(s.Type))
if len(s.Values) > 0 {
ret.Dot("Op").Call(jen.Lit("="))
ret.Add(genExprs(s.Values))
}
return ret
}
func basicLit(b *ast.BasicLit) jen.Code {
switch b.Kind {
case token.INT:
i, err := strconv.ParseInt(b.Value, 10, 32)
if err != nil {
return nil
}
return jen.Dot("Lit").Call(jen.Lit(int(i)))
case token.FLOAT:
return jen.Dot("Lit").Call(jen.Id(b.Value))
case token.IMAG:
panic("Cannot parse Imaginary Numbers")
case token.CHAR:
return jen.Dot("Id").Call(jen.Id("\"" + b.Value + "\""))
case token.STRING:
return jen.Dot("Lit").Call(jen.Id(b.Value))
}
return nil
}