-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
165 lines (147 loc) · 3.87 KB
/
file.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
package main
import "bytes"
import "fmt"
import "go/ast"
import "go/format"
import "go/parser"
import "go/types"
import "os"
import "path"
import "path/filepath"
import "strconv"
import "strings"
import "text/template"
import "defimpl/util"
// File represents a single file to be processed.
type File struct {
AstFile *ast.File
InputFilePath string
Package string
Interfaces []*InterfaceDefinition
Output *ast.File
}
func (f *File) Defimpl() string {
return os.Args[0]
}
type ToImport struct {
Name string
Path string
}
func (f *File) Qualifier(pkg *types.Package) string {
ppath := pkg.Path()
for _, ispec := range f.AstFile.Imports {
unq, err := strconv.Unquote(ispec.Path.Value)
if err != nil {
panic(err)
}
if unq == ppath {
if ispec.Name == nil {
_, base := path.Split(ppath)
return base
} else {
return ispec.Name.Name
}
}
}
return ""
}
var _ types.Qualifier = (&File{}).Qualifier
func (f *File) OutputFilePath() string {
input := f.InputFilePath
return filepath.Join(filepath.Dir(input), "impl_"+filepath.Base(input))
}
func IsOutputFilePath(f string) bool {
return strings.HasPrefix(filepath.Base(f), "impl_")
}
// NewFile returns a File object for the given ast.File.
// Interfaces will be filled in.
func NewFile(ctx *context, astFile *ast.File) *File {
f := &File{
AstFile: astFile,
InputFilePath: ctx.fset.Position(astFile.Package).Filename,
Package: astFile.Name.Name,
Interfaces: []*InterfaceDefinition{},
}
for _, decl := range astFile.Decls {
if id := NewInterface(ctx, f , decl); id != nil {
f.Interfaces = append(f.Interfaces, id)
}
}
return f
}
func (f *File) Write(ctx *context) error {
if !f.AnyStructs() {
return nil
}
output := f.OutputFilePath()
out, err := os.Create(output)
if err != nil {
return fmt.Errorf("Can't create %s: %s", output, err)
}
f.GenerateCode(ctx, output)
format.Node(out, ctx.fset, f.Output)
out.Close()
fmt.Printf("Wrote %s\n", output)
return nil
}
// AnyStructs returns true if the File defines interfaces for which
// impl structs will be defined.
func (f *File) AnyStructs() bool {
for _, i := range f.Interfaces {
if i.DefinesStruct() {
return true
}
}
return false
}
func (f *File) GenerateCode(ctx *context, filepath string) {
writer := bytes.NewBufferString("")
err := OutputFileTemplate.Execute(writer, f)
if err != nil {
fmt.Fprintf(os.Stderr, "defimpl: %s\n", writer.String())
panic(err)
}
parsed, err := parser.ParseFile(ctx.fset, filepath, writer.String(), parser.ParseComments)
if err != nil {
fmt.Fprintf(os.Stderr, "defimpl: %s\n", writer.String())
panic(err)
}
errs := util.EnsureImports(ctx.fset, f.AstFile, parsed)
for _, err := range errs {
fmt.Fprintf(os.Stderr, "defimpl: %s\n", err)
}
f.Output = parsed
}
// OutputFileTemplate is the template for generating the output file
// containing the programatically generated struct and method definitions
// that implement the interfaces in the input file.
// The parameter is a File object.
var OutputFileTemplate *template.Template = template.Must(template.New("OutputFileTemplate").Funcs(map[string]interface{}{
// "NormalizedType": util.NormalizedType,
"GlobalDefinitions": GlobalDefinitions,
}).Parse(`
// This file was automatically generated by {{.Defimpl}} from {{.InputFilePath}}.
package {{.Package}}
import "reflect"
import "defimpl/runtime"
{{with $file := . -}}
{{- range .Interfaces -}}
{{- if .DefinesStruct -}}
type {{.StructName}} struct {
{{- range .VerbPhrases}}
{{.Verb.StructBody .}}
{{- end -}}
}
var _ {{.InterfaceName}} = (*{{.StructName}})(nil)
var _ = func() error {
t := reflect.TypeOf(func({{.InterfaceName}}, *{{.StructName}}){})
runtime.Register(t.In(0), t.In(1))
return nil
}()
{{range .VerbPhrases -}}
{{GlobalDefinitions .}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end}}
`)) // end template