bind.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // Package bind implements a code generator for gobind.
  5. //
  6. // See the documentation on the gobind command for usage details
  7. // and the list of currently supported types.
  8. // (http://godoc.org/golang.org/x/mobile/cmd/gobind)
  9. package bind
  10. // TODO(crawshaw): slice support
  11. // TODO(crawshaw): channel support
  12. import (
  13. "bytes"
  14. "go/format"
  15. "go/token"
  16. "go/types"
  17. "io"
  18. )
  19. const gobindPreamble = "// Code generated by gobind. DO NOT EDIT.\n\n"
  20. type (
  21. GeneratorConfig struct {
  22. Writer io.Writer
  23. Fset *token.FileSet
  24. Pkg *types.Package
  25. AllPkg []*types.Package
  26. }
  27. fileType int
  28. )
  29. // GenGo generates a Go stub to support foreign language APIs.
  30. func GenGo(conf *GeneratorConfig) error {
  31. buf := new(bytes.Buffer)
  32. g := &goGen{
  33. Generator: &Generator{
  34. Printer: &Printer{Buf: buf, IndentEach: []byte("\t")},
  35. Fset: conf.Fset,
  36. AllPkg: conf.AllPkg,
  37. Pkg: conf.Pkg,
  38. },
  39. }
  40. g.Init()
  41. if err := g.gen(); err != nil {
  42. return err
  43. }
  44. src := buf.Bytes()
  45. srcf, err := format.Source(src)
  46. if err != nil {
  47. conf.Writer.Write(src) // for debugging
  48. return err
  49. }
  50. _, err = conf.Writer.Write(srcf)
  51. return err
  52. }