github.com/F4RD1N/gomobile@v1.0.1/bind/bind.go (about)

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