Debian Codegraph @

generate/generate.go

raw symbols SCIP
1 // Copyright 2012 Aaron Jacobs. All Rights Reserved.
2 // Author: [email protected] (Aaron Jacobs)
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 // Package generate implements code generation for mock classes. This is an
17 // implementation detail of the createmock command, which you probably want to
18 // use directly instead.
19 package generate
20
21 import (
22 "bytes"
23 "errors"
24 "fmt"
25 "go/ast"
26 "go/parser"
27 "go/printer"
28 "go/token"
29 "io"
30 "path"
31 "reflect"
32 "regexp"
33 "text/template"
34 )
35
36 const gTmplStr = `
37 // This file was auto-generated using createmock. See the following page for
38 // more information:
39 //
40 // https://github.com/jacobsa/oglemock
41 //
42
43 package {{pathBase .OutputPkgPath}}
44
45 import (
46 {{range $identifier, $import := .Imports}}{{$identifier}} "{{$import}}"
47 {{end}}
48 )
49
50 {{range .Interfaces}}
51 {{$interfaceName := printf "Mock%s" .Name}}
52 {{$structName := printf "mock%s" .Name}}
53
54 type {{$interfaceName}} interface {
55 {{getTypeString .}}
56 oglemock.MockObject
57 }
58
59 type {{$structName}} struct {
60 controller oglemock.Controller
61 description string
62 }
63
64 func New{{printf "Mock%s" .Name}}(
65 c oglemock.Controller,
66 desc string) {{$interfaceName}} {
67 return &{{$structName}}{
68 controller: c,
69 description: desc,
70 }
71 }
72
73 func (m *{{$structName}}) Oglemock_Id() uintptr {
74 return uintptr(unsafe.Pointer(m))
75 }
76
77 func (m *{{$structName}}) Oglemock_Description() string {
78 return m.description
79 }
80
81 {{range getMethods .}}
82 {{$funcType := .Type}}
83 {{$inputTypes := getInputs $funcType}}
84 {{$outputTypes := getOutputs $funcType}}
85
86 func (m *{{$structName}}) {{.Name}}({{range $i, $type := $inputTypes}}p{{$i}} {{getInputTypeString $i $funcType}}, {{end}}) ({{range $i, $type := $outputTypes}}o{{$i}} {{getTypeString $type}}, {{end}}) {
87 // Get a file name and line number for the caller.
88 _, file, line, _ := runtime.Caller(1)
89
90 // Hand the call off to the controller, which does most of the work.
91 retVals := m.controller.HandleMethodCall(
92 m,
93 "{{.Name}}",
94 file,
95 line,
96 []interface{}{ {{range $i, $type := $inputTypes}}p{{$i}}, {{end}} })
97
98 if len(retVals) != {{len $outputTypes}} {
99 panic(fmt.Sprintf("{{$structName}}.{{.Name}}: invalid return values: %v", retVals))
100 }
101
102 {{range $i, $type := $outputTypes}}
103 // o{{$i}} {{getTypeString $type}}
104 if retVals[{{$i}}] != nil {
105 o{{$i}} = retVals[{{$i}}].({{getTypeString $type}})
106 }
107 {{end}}
108
109 return
110 }
111 {{end}}
112 {{end}}
113 `
114
115 type tmplArg struct {
116 // The set of interfaces to mock, and the full name of the package from which
117 // they all come.
118 Interfaces []reflect.Type
119 InterfacePkgPath string
120
121 // The package path for the generate code.
122 OutputPkgPath string
123
124 // Imports needed by the interfaces.
125 Imports importMap
126 }
127
128 func (a *tmplArg) getInputTypeString(i int, ft reflect.Type) string {
129 numInputs := ft.NumIn()
130 if i == numInputs-1 && ft.IsVariadic() {
131 return "..." + a.getTypeString(ft.In(i).Elem())
132 }
133
134 return a.getTypeString(ft.In(i))
135 }
136
137 func (a *tmplArg) getTypeString(t reflect.Type) string {
138 return typeString(t, a.OutputPkgPath)
139 }
140
141 func getMethods(it reflect.Type) []reflect.Method {
142 numMethods := it.NumMethod()
143 methods := make([]reflect.Method, numMethods)
144
145 for i := 0; i < numMethods; i++ {
146 methods[i] = it.Method(i)
147 }
148
149 return methods
150 }
151
152 func getInputs(ft reflect.Type) []reflect.Type {
153 numIn := ft.NumIn()
154 inputs := make([]reflect.Type, numIn)
155
156 for i := 0; i < numIn; i++ {
157 inputs[i] = ft.In(i)
158 }
159
160 return inputs
161 }
162
163 func getOutputs(ft reflect.Type) []reflect.Type {
164 numOut := ft.NumOut()
165 outputs := make([]reflect.Type, numOut)
166
167 for i := 0; i < numOut; i++ {
168 outputs[i] = ft.Out(i)
169 }
170
171 return outputs
172 }
173
174 // A map from import identifier to package to use that identifier for,
175 // containing elements for each import needed by a set of mocked interfaces.
176 type importMap map[string]string
177
178 var typePackageIdentifierRegexp = regexp.MustCompile(`^([\pL_0-9]+)\.[\pL_0-9]+$`)
179
180 // Add an import for the supplied type, without recursing.
181 func addImportForType(imports importMap, t reflect.Type) {
182 // If there is no package path, this is a built-in type and we don't need an
183 // import.
184 pkgPath := t.PkgPath()
185 if pkgPath == "" {
186 return
187 }
188
189 // Work around a bug in Go:
190 //
191 // http://code.google.com/p/go/issues/detail?id=2660
192 //
193 var errorPtr *error
194 if t == reflect.TypeOf(errorPtr).Elem() {
195 return
196 }
197
198 // Use the identifier that's part of the type's string representation as the
199 // import identifier. This means that we'll do the right thing for package
200 // "foo/bar" with declaration "package baz".
201 match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
202 if match == nil {
203 return
204 }
205
206 imports[match[1]] = pkgPath
207 }
208
209 // Add all necessary imports for the type, recursing as appropriate.
210 func addImportsForType(imports importMap, t reflect.Type) {
211 // Add any import needed for the type itself.
212 addImportForType(imports, t)
213
214 // Handle special cases where recursion is needed.
215 switch t.Kind() {
216 case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice:
217 addImportsForType(imports, t.Elem())
218
219 case reflect.Func:
220 // Input parameters.
221 for i := 0; i < t.NumIn(); i++ {
222 addImportsForType(imports, t.In(i))
223 }
224
225 // Return values.
226 for i := 0; i < t.NumOut(); i++ {
227 addImportsForType(imports, t.Out(i))
228 }
229
230 case reflect.Map:
231 addImportsForType(imports, t.Key())
232 addImportsForType(imports, t.Elem())
233 }
234 }
235
236 // Add imports for each of the methods of the interface, but not the interface
237 // itself.
238 func addImportsForInterfaceMethods(imports importMap, it reflect.Type) {
239 // Handle each method.
240 for i := 0; i < it.NumMethod(); i++ {
241 m := it.Method(i)
242 addImportsForType(imports, m.Type)
243 }
244 }
245
246 // Given a set of interfaces, return a map from import identifier to package to
247 // use that identifier for, containing elements for each import needed by the
248 // mock versions of those interfaces in a package with the given path.
249 func getImports(
250 interfaces []reflect.Type,
251 pkgPath string) importMap {
252 imports := make(importMap)
253 for _, it := range interfaces {
254 addImportForType(imports, it)
255 addImportsForInterfaceMethods(imports, it)
256 }
257
258 // Make sure there are imports for other types used by the generated code
259 // itself.
260 imports["fmt"] = "fmt"
261 imports["oglemock"] = "github.com/jacobsa/oglemock"
262 imports["runtime"] = "runtime"
263 imports["unsafe"] = "unsafe"
264
265 // Remove any self-imports generated above.
266 for k, v := range imports {
267 if v == pkgPath {
268 delete(imports, k)
269 }
270 }
271
272 return imports
273 }
274
275 // Given a set of interfaces to mock, write out source code suitable for
276 // inclusion in a package with the supplied full package path containing mock
277 // implementations of those interfaces.
278 func GenerateMockSource(
279 w io.Writer,
280 outputPkgPath string,
281 interfaces []reflect.Type) (err error) {
282 // Sanity-check arguments.
283 if outputPkgPath == "" {
284 return errors.New("Package path must be non-empty.")
285 }
286
287 if len(interfaces) == 0 {
288 return errors.New("List of interfaces must be non-empty.")
289 }
290
291 // Make sure each type is indeed an interface.
292 for _, it := range interfaces {
293 if it.Kind() != reflect.Interface {
294 return errors.New("Invalid type: " + it.String())
295 }
296 }
297
298 // Make sure each interface is from the same package.
299 interfacePkgPath := interfaces[0].PkgPath()
300 for _, t := range interfaces {
301 if t.PkgPath() != interfacePkgPath {
302 err = fmt.Errorf(
303 "Package path mismatch: %q vs. %q",
304 interfacePkgPath,
305 t.PkgPath())
306
307 return
308 }
309 }
310
311 // Set up an appropriate template arg.
312 arg := tmplArg{
313 Interfaces: interfaces,
314 InterfacePkgPath: interfacePkgPath,
315 OutputPkgPath: outputPkgPath,
316 Imports: getImports(interfaces, outputPkgPath),
317 }
318
319 // Configure and parse the template.
320 tmpl := template.New("code")
321 tmpl.Funcs(template.FuncMap{
322 "pathBase": path.Base,
323 "getMethods": getMethods,
324 "getInputs": getInputs,
325 "getOutputs": getOutputs,
326 "getInputTypeString": arg.getInputTypeString,
327 "getTypeString": arg.getTypeString,
328 })
329
330 _, err = tmpl.Parse(gTmplStr)
331 if err != nil {
332 err = fmt.Errorf("Parse: %v", err)
333 return
334 }
335
336 // Execute the template, collecting the raw output into a buffer.
337 buf := new(bytes.Buffer)
338 if err := tmpl.Execute(buf, arg); err != nil {
339 return err
340 }
341
342 // Parse the output.
343 fset := token.NewFileSet()
344 astFile, err := parser.ParseFile(
345 fset,
346 path.Base(outputPkgPath+".go"),
347 buf,
348 parser.ParseComments)
349
350 if err != nil {
351 err = fmt.Errorf("parser.ParseFile: %v", err)
352 return
353 }
354
355 // Sort the import lines in the AST in the same way that gofmt does.
356 ast.SortImports(fset, astFile)
357
358 // Pretty-print the AST, using the same options that gofmt does by default.
359 cfg := &printer.Config{
360 Mode: printer.UseSpaces | printer.TabIndent,
361 Tabwidth: 8,
362 }
363
364 if err = cfg.Fprint(w, fset, astFile); err != nil {
365 return errors.New("Error pretty printing: " + err.Error())
366 }
367
368 return nil
369 }