Debian Codegraph @

bind/gengo.go

raw
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package bind
6
7 import (
8 "bytes"
9 "fmt"
10 "go/types"
11 "strings"
12 )
13
14 type goGen struct {
15 *Generator
16
17 // imports is the list of imports, in the form
18 // "the/package/path"
19 //
20 // or
21 //
22 // name "the/package/path"
23 //
24 // in case of duplicates.
25 imports []string
26 // The set of taken import names.
27 importNames map[string]struct{}
28 // importMap is a map from packages to their names. The name of a package is the last
29 // segment of its path, with duplicates resolved by appending a underscore and a unique
30 // number.
31 importMap map[*types.Package]string
32 }
33
34 const (
35 goPreamble = gobindPreamble + `// Package main is an autogenerated binder stub for package %[1]s.
36 //
37 // autogenerated by gobind -lang=go %[2]s
38 package main
39
40 /*
41 #include <stdlib.h>
42 #include <stdint.h>
43 #include "seq.h"
44 #include "%[1]s.h"
45
46 */
47 import "C"
48
49 `
50 )
51
52 func (g *goGen) genFuncBody(o *types.Func, selectorLHS string) {
53 sig := o.Type().(*types.Signature)
54 params := sig.Params()
55 for i := 0; i < params.Len(); i++ {
56 p := params.At(i)
57 pn := "param_" + g.paramName(params, i)
58 g.genRead("_"+pn, pn, p.Type(), modeTransient)
59 }
60
61 res := sig.Results()
62 if res.Len() > 2 || res.Len() == 2 && !isErrorType(res.At(1).Type()) {
63 g.errorf("functions and methods must return either zero or one values, and optionally an error")
64 return
65 }
66 if res.Len() > 0 {
67 for i := 0; i < res.Len(); i++ {
68 if i > 0 {
69 g.Printf(", ")
70 }
71 g.Printf("res_%d", i)
72 }
73 g.Printf(" := ")
74 }
75
76 g.Printf("%s%s(", selectorLHS, o.Name())
77 for i := 0; i < params.Len(); i++ {
78 if i > 0 {
79 g.Printf(", ")
80 }
81 g.Printf("_param_%s", g.paramName(params, i))
82 }
83 g.Printf(")\n")
84
85 for i := 0; i < res.Len(); i++ {
86 pn := fmt.Sprintf("res_%d", i)
87 g.genWrite("_"+pn, pn, res.At(i).Type(), modeRetained)
88 }
89 if res.Len() > 0 {
90 g.Printf("return ")
91 for i := 0; i < res.Len(); i++ {
92 if i > 0 {
93 g.Printf(", ")
94 }
95 g.Printf("_res_%d", i)
96 }
97 g.Printf("\n")
98 }
99 }
100
101 func (g *goGen) genWrite(toVar, fromVar string, t types.Type, mode varMode) {
102 switch t := types.Unalias(t).(type) {
103 case *types.Basic:
104 switch t.Kind() {
105 case types.String:
106 g.Printf("%s := encodeString(%s)\n", toVar, fromVar)
107 case types.Bool:
108 g.Printf("var %s C.%s = 0\n", toVar, g.cgoType(t))
109 g.Printf("if %s { %s = 1 }\n", fromVar, toVar)
110 default:
111 g.Printf("%s := C.%s(%s)\n", toVar, g.cgoType(t), fromVar)
112 }
113 case *types.Slice:
114 if isBytesSlice(t) {
115 g.Printf("%s := fromSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained)
116 return
117 }
118 g.errorf("unsupported type: %s", t)
119 case *types.Pointer:
120 // TODO(crawshaw): test *int
121 // TODO(crawshaw): test **Generator
122 switch t := types.Unalias(t.Elem()).(type) {
123 case *types.Named:
124 g.genToRefNum(toVar, fromVar)
125 default:
126 g.errorf("unsupported type %s", t)
127 }
128 case *types.Named:
129 switch u := t.Underlying().(type) {
130 case *types.Interface, *types.Pointer:
131 g.genToRefNum(toVar, fromVar)
132 default:
133 g.errorf("unsupported, direct named type %s: %s", t, u)
134 }
135 default:
136 g.errorf("unsupported type %s", t)
137 }
138 }
139
140 // genToRefNum generates Go code for converting a variable to its refnum.
141 // Note that the nil-check cannot be lifted into seq.ToRefNum, because a nil
142 // struct pointer does not convert to a nil interface.
143 func (g *goGen) genToRefNum(toVar, fromVar string) {
144 g.Printf("var %s C.int32_t = _seq.NullRefNum\n", toVar)
145 g.Printf("if %s != nil {\n", fromVar)
146 g.Printf(" %s = C.int32_t(_seq.ToRefNum(%s))\n", toVar, fromVar)
147 g.Printf("}\n")
148 }
149
150 func (g *goGen) genFuncSignature(o *types.Func, objName string) {
151 g.Printf("//export proxy%s_%s_%s\n", g.pkgPrefix, objName, o.Name())
152 g.Printf("func proxy%s_%s_%s(", g.pkgPrefix, objName, o.Name())
153 if objName != "" {
154 g.Printf("refnum C.int32_t")
155 }
156 sig := o.Type().(*types.Signature)
157 params := sig.Params()
158 for i := 0; i < params.Len(); i++ {
159 if objName != "" || i > 0 {
160 g.Printf(", ")
161 }
162 p := params.At(i)
163 g.Printf("param_%s C.%s", g.paramName(params, i), g.cgoType(p.Type()))
164 }
165 g.Printf(") ")
166 res := sig.Results()
167 if res.Len() > 0 {
168 g.Printf("(")
169 for i := 0; i < res.Len(); i++ {
170 if i > 0 {
171 g.Printf(", ")
172 }
173 g.Printf("C.%s", g.cgoType(res.At(i).Type()))
174 }
175 g.Printf(") ")
176 }
177 g.Printf("{\n")
178 }
179
180 func (g *goGen) paramName(params *types.Tuple, pos int) string {
181 return basicParamName(params, pos)
182 }
183
184 func (g *goGen) genFunc(o *types.Func) {
185 if !g.isSigSupported(o.Type()) {
186 g.Printf("// skipped function %s with unsupported parameter or result types\n", o.Name())
187 return
188 }
189 g.genFuncSignature(o, "")
190 g.Indent()
191 g.genFuncBody(o, g.pkgName(g.Pkg))
192 g.Outdent()
193 g.Printf("}\n\n")
194 }
195
196 func (g *goGen) genStruct(obj *types.TypeName, T *types.Struct) {
197 fields := exportedFields(T)
198 methods := exportedMethodSet(types.NewPointer(obj.Type()))
199
200 for _, f := range fields {
201 if t := f.Type(); !g.isSupported(t) {
202 g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", obj.Name(), f.Name(), t)
203 continue
204 }
205 g.Printf("//export proxy%s_%s_%s_Set\n", g.pkgPrefix, obj.Name(), f.Name())
206 g.Printf("func proxy%s_%s_%s_Set(refnum C.int32_t, v C.%s) {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type()))
207 g.Indent()
208 g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
209 g.genRead("_v", "v", f.Type(), modeRetained)
210 g.Printf("ref.Get().(*%s%s).%s = _v\n", g.pkgName(g.Pkg), obj.Name(), f.Name())
211 g.Outdent()
212 g.Printf("}\n\n")
213
214 g.Printf("//export proxy%s_%s_%s_Get\n", g.pkgPrefix, obj.Name(), f.Name())
215 g.Printf("func proxy%s_%s_%s_Get(refnum C.int32_t) C.%s {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type()))
216 g.Indent()
217 g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
218 g.Printf("v := ref.Get().(*%s%s).%s\n", g.pkgName(g.Pkg), obj.Name(), f.Name())
219 g.genWrite("_v", "v", f.Type(), modeRetained)
220 g.Printf("return _v\n")
221 g.Outdent()
222 g.Printf("}\n\n")
223 }
224
225 for _, m := range methods {
226 if !g.isSigSupported(m.Type()) {
227 g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
228 continue
229 }
230 g.genFuncSignature(m, obj.Name())
231 g.Indent()
232 g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
233 g.Printf("v := ref.Get().(*%s%s)\n", g.pkgName(g.Pkg), obj.Name())
234 g.genFuncBody(m, "v.")
235 g.Outdent()
236 g.Printf("}\n\n")
237 }
238 // Export constructor for ObjC and Java default no-arg constructors
239 g.Printf("//export new_%s_%s\n", g.Pkg.Name(), obj.Name())
240 g.Printf("func new_%s_%s() C.int32_t {\n", g.Pkg.Name(), obj.Name())
241 g.Indent()
242 g.Printf("return C.int32_t(_seq.ToRefNum(new(%s%s)))\n", g.pkgName(g.Pkg), obj.Name())
243 g.Outdent()
244 g.Printf("}\n")
245 }
246
247 func (g *goGen) genVar(o *types.Var) {
248 if t := o.Type(); !g.isSupported(t) {
249 g.Printf("// skipped variable %s with unsupported type %s\n\n", o.Name(), t)
250 return
251 }
252 // TODO(hyangah): non-struct pointer types (*int), struct type.
253
254 v := fmt.Sprintf("%s%s", g.pkgName(g.Pkg), o.Name())
255
256 // var I int
257 //
258 // func var_setI(v int)
259 g.Printf("//export var_set%s_%s\n", g.pkgPrefix, o.Name())
260 g.Printf("func var_set%s_%s(v C.%s) {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type()))
261 g.Indent()
262 g.genRead("_v", "v", o.Type(), modeRetained)
263 g.Printf("%s = _v\n", v)
264 g.Outdent()
265 g.Printf("}\n")
266
267 // func var_getI() int
268 g.Printf("//export var_get%s_%s\n", g.pkgPrefix, o.Name())
269 g.Printf("func var_get%s_%s() C.%s {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type()))
270 g.Indent()
271 g.Printf("v := %s\n", v)
272 g.genWrite("_v", "v", o.Type(), modeRetained)
273 g.Printf("return _v\n")
274 g.Outdent()
275 g.Printf("}\n")
276 }
277
278 func (g *goGen) genInterface(obj *types.TypeName) {
279 iface := obj.Type().(*types.Named).Underlying().(*types.Interface)
280
281 summary := makeIfaceSummary(iface)
282
283 // Define the entry points.
284 for _, m := range summary.callable {
285 if !g.isSigSupported(m.Type()) {
286 g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
287 continue
288 }
289 g.genFuncSignature(m, obj.Name())
290 g.Indent()
291 g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
292 g.Printf("v := ref.Get().(%s%s)\n", g.pkgName(g.Pkg), obj.Name())
293 g.genFuncBody(m, "v.")
294 g.Outdent()
295 g.Printf("}\n\n")
296 }
297
298 // Define a proxy interface.
299 if !summary.implementable {
300 // The interface defines an unexported method or a method that
301 // uses an unexported type. We cannot generate a proxy object
302 // for such a type.
303 return
304 }
305 g.Printf("type proxy%s_%s _seq.Ref\n\n", g.pkgPrefix, obj.Name())
306
307 g.Printf("func (p *proxy%s_%s) Bind_proxy_refnum__() int32 {\n", g.pkgPrefix, obj.Name())
308 g.Indent()
309 g.Printf("return (*_seq.Ref)(p).Bind_IncNum()\n")
310 g.Outdent()
311 g.Printf("}\n\n")
312
313 for _, m := range summary.callable {
314 if !g.isSigSupported(m.Type()) {
315 g.Printf("// skipped method %s.%s with unsupported parameter or result types\n", obj.Name(), m.Name())
316 continue
317 }
318 sig := m.Type().(*types.Signature)
319 params := sig.Params()
320 res := sig.Results()
321
322 if res.Len() > 2 ||
323 (res.Len() == 2 && !isErrorType(res.At(1).Type())) {
324 g.errorf("functions and methods must return either zero or one value, and optionally an error: %s.%s", obj.Name(), m.Name())
325 continue
326 }
327
328 g.Printf("func (p *proxy%s_%s) %s(", g.pkgPrefix, obj.Name(), m.Name())
329 for i := 0; i < params.Len(); i++ {
330 if i > 0 {
331 g.Printf(", ")
332 }
333 g.Printf("param_%s %s", g.paramName(params, i), g.typeString(params.At(i).Type()))
334 }
335 g.Printf(") ")
336
337 if res.Len() == 1 {
338 g.Printf("%s", g.typeString(res.At(0).Type()))
339 } else if res.Len() == 2 {
340 g.Printf("(%s, error)", g.typeString(res.At(0).Type()))
341 }
342 g.Printf(" {\n")
343 g.Indent()
344
345 for i := 0; i < params.Len(); i++ {
346 pn := "param_" + g.paramName(params, i)
347 g.genWrite("_"+pn, pn, params.At(i).Type(), modeTransient)
348 }
349
350 if res.Len() > 0 {
351 g.Printf("res := ")
352 }
353 g.Printf("C.cproxy%s_%s_%s(C.int32_t(p.Bind_proxy_refnum__())", g.pkgPrefix, obj.Name(), m.Name())
354 for i := 0; i < params.Len(); i++ {
355 g.Printf(", _param_%s", g.paramName(params, i))
356 }
357 g.Printf(")\n")
358 var retName string
359 if res.Len() > 0 {
360 if res.Len() == 1 {
361 T := res.At(0).Type()
362 g.genRead("_res", "res", T, modeRetained)
363 retName = "_res"
364 } else {
365 var rvs []string
366 for i := 0; i < res.Len(); i++ {
367 rv := fmt.Sprintf("res_%d", i)
368 g.genRead(rv, fmt.Sprintf("res.r%d", i), res.At(i).Type(), modeRetained)
369 rvs = append(rvs, rv)
370 }
371 retName = strings.Join(rvs, ", ")
372 }
373 g.Printf("return %s\n", retName)
374 }
375 g.Outdent()
376 g.Printf("}\n\n")
377 }
378 }
379
380 func (g *goGen) genRead(toVar, fromVar string, typ types.Type, mode varMode) {
381 switch t := types.Unalias(typ).(type) {
382 case *types.Basic:
383 switch t.Kind() {
384 case types.String:
385 g.Printf("%s := decodeString(%s)\n", toVar, fromVar)
386 case types.Bool:
387 g.Printf("%s := %s != 0\n", toVar, fromVar)
388 default:
389 g.Printf("%s := %s(%s)\n", toVar, t.Underlying().String(), fromVar)
390 }
391 case *types.Slice:
392 if isBytesSlice(t) {
393 g.Printf("%s := toSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained)
394 return
395 }
396 g.errorf("unsupported type: %s", t)
397 case *types.Pointer:
398 switch u := types.Unalias(t.Elem()).(type) {
399 case *types.Named:
400 o := u.Obj()
401 oPkg := o.Pkg()
402 if !g.validPkg(oPkg) {
403 g.errorf("type %s is defined in %s, which is not bound", u, oPkg)
404 return
405 }
406 g.Printf("// Must be a Go object\n")
407 g.Printf("var %s *%s%s\n", toVar, g.pkgName(oPkg), o.Name())
408 g.Printf("if %s_ref := _seq.FromRefNum(int32(%s)); %s_ref != nil {\n", toVar, fromVar, toVar)
409 g.Printf(" %s = %s_ref.Get().(*%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name())
410 g.Printf("}\n")
411 default:
412 g.errorf("unsupported pointer type %s", t)
413 }
414 case *types.Named:
415 switch t.Underlying().(type) {
416 case *types.Interface, *types.Pointer:
417 hasProxy := true
418 if iface, ok := t.Underlying().(*types.Interface); ok {
419 hasProxy = makeIfaceSummary(iface).implementable
420 }
421 pkgFirst := typePkgFirstElem(t)
422 isWrapper := pkgFirst == "Java" || pkgFirst == "ObjC"
423 o := t.Obj()
424 oPkg := o.Pkg()
425 if !isErrorType(t) && !g.validPkg(oPkg) && !isWrapper {
426 g.errorf("type %s is defined in %s, which is not bound", t, oPkg)
427 return
428 }
429 g.Printf("var %s %s\n", toVar, g.typeString(t))
430 g.Printf("%s_ref := _seq.FromRefNum(int32(%s))\n", toVar, fromVar)
431 g.Printf("if %s_ref != nil {\n", toVar)
432 g.Printf(" if %s < 0 { // go object \n", fromVar)
433 g.Printf(" %s = %s_ref.Get().(%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name())
434 if hasProxy {
435 g.Printf(" } else { // foreign object \n")
436 if isWrapper {
437 var clsName string
438 switch pkgFirst {
439 case "Java":
440 clsName = flattenName(classNameFor(t))
441 case "ObjC":
442 clsName = t.Obj().Name()
443 }
444 g.Printf(" %s = (*proxy_class_%s)(%s_ref)\n", toVar, clsName, toVar)
445 } else {
446 g.Printf(" %s = (*proxy%s_%s)(%s_ref)\n", toVar, pkgPrefix(oPkg), o.Name(), toVar)
447 }
448 }
449 g.Printf(" }\n")
450 g.Printf("}\n")
451 default:
452 g.errorf("unsupported named type %s", t)
453 }
454 default:
455 g.errorf("unsupported type: %s", typ)
456 }
457 }
458
459 func (g *goGen) typeString(typ types.Type) string {
460 pkg := g.Pkg
461
462 switch t := types.Unalias(typ).(type) {
463 case *types.Named:
464 obj := t.Obj()
465 if obj.Pkg() == nil { // e.g. error type is *types.Named.
466 return types.TypeString(typ, types.RelativeTo(pkg))
467 }
468 oPkg := obj.Pkg()
469 if !g.validPkg(oPkg) && !isWrapperType(t) {
470 g.errorf("type %s is defined in %s, which is not bound", t, oPkg)
471 return "TODO"
472 }
473
474 switch t.Underlying().(type) {
475 case *types.Interface, *types.Struct:
476 return fmt.Sprintf("%s%s", g.pkgName(oPkg), types.TypeString(typ, types.RelativeTo(oPkg)))
477 default:
478 g.errorf("unsupported named type %s / %T", t, t)
479 }
480 case *types.Pointer:
481 switch t := types.Unalias(t.Elem()).(type) {
482 case *types.Named:
483 return fmt.Sprintf("*%s", g.typeString(t))
484 default:
485 g.errorf("not yet supported, pointer type %s / %T", t, t)
486 }
487 default:
488 return types.TypeString(typ, types.RelativeTo(pkg))
489 }
490 return ""
491 }
492
493 // genPreamble generates the preamble. It is generated after everything
494 // else, where we know which bound packages to import.
495 func (g *goGen) genPreamble() {
496 pkgName := ""
497 pkgPath := ""
498 if g.Pkg != nil {
499 pkgName = g.Pkg.Name()
500 pkgPath = g.Pkg.Path()
501 } else {
502 pkgName = "universe"
503 }
504 g.Printf(goPreamble, pkgName, pkgPath)
505 g.Printf("import (\n")
506 g.Indent()
507 g.Printf("_seq \"golang.org/x/mobile/bind/seq\"\n")
508 for _, imp := range g.imports {
509 g.Printf("%s\n", imp)
510 }
511 g.Outdent()
512 g.Printf(")\n\n")
513 }
514
515 func (g *goGen) gen() error {
516 g.importNames = make(map[string]struct{})
517 g.importMap = make(map[*types.Package]string)
518
519 // Switch to a temporary buffer so the preamble can be
520 // written last.
521 oldBuf := g.Printer.Buf
522 newBuf := new(bytes.Buffer)
523 g.Printer.Buf = newBuf
524 g.Printf("// suppress the error if seq ends up unused\n")
525 g.Printf("var _ = _seq.FromRefNum\n")
526
527 for _, s := range g.structs {
528 g.genStruct(s.obj, s.t)
529 }
530 for _, intf := range g.interfaces {
531 g.genInterface(intf.obj)
532 }
533 for _, v := range g.vars {
534 g.genVar(v)
535 }
536 for _, f := range g.funcs {
537 g.genFunc(f)
538 }
539 // Switch to the original buffer, write the preamble
540 // and append the rest of the file.
541 g.Printer.Buf = oldBuf
542 g.genPreamble()
543 g.Printer.Buf.Write(newBuf.Bytes())
544 if len(g.err) > 0 {
545 return g.err
546 }
547 return nil
548 }
549
550 // pkgName returns the package name and adds the package to the list of
551 // imports.
552 func (g *goGen) pkgName(pkg *types.Package) string {
553 // The error type has no package
554 if pkg == nil {
555 return ""
556 }
557 if name, exists := g.importMap[pkg]; exists {
558 return name + "."
559 }
560 i := 0
561 pname := pkg.Name()
562 name := pkg.Name()
563 for {
564 if _, exists := g.importNames[name]; !exists {
565 g.importNames[name] = struct{}{}
566 g.importMap[pkg] = name
567 var imp string
568 if pname != name {
569 imp = fmt.Sprintf("%s %q", name, pkg.Path())
570 } else {
571 imp = fmt.Sprintf("%q", pkg.Path())
572 }
573 g.imports = append(g.imports, imp)
574 break
575 }
576 i++
577 name = fmt.Sprintf("%s_%d", pname, i)
578 }
579 g.importMap[pkg] = name
580 return name + "."
581 }