github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/cmd/api/goapi.go (about)

     1  // Copyright 2011 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  // Binary api computes the exported API of a set of Go packages.
     6  package main
     7  
     8  import (
     9  	"bufio"
    10  	"bytes"
    11  	"flag"
    12  	"fmt"
    13  	"go/ast"
    14  	"go/build"
    15  	"go/parser"
    16  	"go/token"
    17  	"go/types"
    18  	"io"
    19  	"io/ioutil"
    20  	"log"
    21  	"os"
    22  	"os/exec"
    23  	"path/filepath"
    24  	"regexp"
    25  	"runtime"
    26  	"sort"
    27  	"strings"
    28  )
    29  
    30  // Flags
    31  var (
    32  	checkFile  = flag.String("c", "", "optional comma-separated filename(s) to check API against")
    33  	allowNew   = flag.Bool("allow_new", true, "allow API additions")
    34  	exceptFile = flag.String("except", "", "optional filename of packages that are allowed to change without triggering a failure in the tool")
    35  	nextFile   = flag.String("next", "", "optional filename of tentative upcoming API features for the next release. This file can be lazily maintained. It only affects the delta warnings from the -c file printed on success.")
    36  	verbose    = flag.Bool("v", false, "verbose debugging")
    37  	forceCtx   = flag.String("contexts", "", "optional comma-separated list of <goos>-<goarch>[-cgo] to override default contexts.")
    38  )
    39  
    40  // contexts are the default contexts which are scanned, unless
    41  // overridden by the -contexts flag.
    42  var contexts = []*build.Context{
    43  	{GOOS: "linux", GOARCH: "386", CgoEnabled: true},
    44  	{GOOS: "linux", GOARCH: "386"},
    45  	{GOOS: "linux", GOARCH: "amd64", CgoEnabled: true},
    46  	{GOOS: "linux", GOARCH: "amd64"},
    47  	{GOOS: "linux", GOARCH: "arm", CgoEnabled: true},
    48  	{GOOS: "linux", GOARCH: "arm"},
    49  	{GOOS: "darwin", GOARCH: "386", CgoEnabled: true},
    50  	{GOOS: "darwin", GOARCH: "386"},
    51  	{GOOS: "darwin", GOARCH: "amd64", CgoEnabled: true},
    52  	{GOOS: "darwin", GOARCH: "amd64"},
    53  	{GOOS: "windows", GOARCH: "amd64"},
    54  	{GOOS: "windows", GOARCH: "386"},
    55  	{GOOS: "freebsd", GOARCH: "386", CgoEnabled: true},
    56  	{GOOS: "freebsd", GOARCH: "386"},
    57  	{GOOS: "freebsd", GOARCH: "amd64", CgoEnabled: true},
    58  	{GOOS: "freebsd", GOARCH: "amd64"},
    59  	{GOOS: "freebsd", GOARCH: "arm", CgoEnabled: true},
    60  	{GOOS: "freebsd", GOARCH: "arm"},
    61  	{GOOS: "netbsd", GOARCH: "386", CgoEnabled: true},
    62  	{GOOS: "netbsd", GOARCH: "386"},
    63  	{GOOS: "netbsd", GOARCH: "amd64", CgoEnabled: true},
    64  	{GOOS: "netbsd", GOARCH: "amd64"},
    65  	{GOOS: "netbsd", GOARCH: "arm", CgoEnabled: true},
    66  	{GOOS: "netbsd", GOARCH: "arm"},
    67  	{GOOS: "openbsd", GOARCH: "386", CgoEnabled: true},
    68  	{GOOS: "openbsd", GOARCH: "386"},
    69  	{GOOS: "openbsd", GOARCH: "amd64", CgoEnabled: true},
    70  	{GOOS: "openbsd", GOARCH: "amd64"},
    71  }
    72  
    73  func contextName(c *build.Context) string {
    74  	s := c.GOOS + "-" + c.GOARCH
    75  	if c.CgoEnabled {
    76  		return s + "-cgo"
    77  	}
    78  	return s
    79  }
    80  
    81  func parseContext(c string) *build.Context {
    82  	parts := strings.Split(c, "-")
    83  	if len(parts) < 2 {
    84  		log.Fatalf("bad context: %q", c)
    85  	}
    86  	bc := &build.Context{
    87  		GOOS:   parts[0],
    88  		GOARCH: parts[1],
    89  	}
    90  	if len(parts) == 3 {
    91  		if parts[2] == "cgo" {
    92  			bc.CgoEnabled = true
    93  		} else {
    94  			log.Fatalf("bad context: %q", c)
    95  		}
    96  	}
    97  	return bc
    98  }
    99  
   100  func setContexts() {
   101  	contexts = []*build.Context{}
   102  	for _, c := range strings.Split(*forceCtx, ",") {
   103  		contexts = append(contexts, parseContext(c))
   104  	}
   105  }
   106  
   107  var internalPkg = regexp.MustCompile(`(^|/)internal($|/)`)
   108  
   109  func main() {
   110  	flag.Parse()
   111  
   112  	if !strings.Contains(runtime.Version(), "weekly") && !strings.Contains(runtime.Version(), "devel") {
   113  		if *nextFile != "" {
   114  			fmt.Printf("Go version is %q, ignoring -next %s\n", runtime.Version(), *nextFile)
   115  			*nextFile = ""
   116  		}
   117  	}
   118  
   119  	if *forceCtx != "" {
   120  		setContexts()
   121  	}
   122  	for _, c := range contexts {
   123  		c.Compiler = build.Default.Compiler
   124  	}
   125  
   126  	var pkgNames []string
   127  	if flag.NArg() > 0 {
   128  		pkgNames = flag.Args()
   129  	} else {
   130  		stds, err := exec.Command("go", "list", "std").Output()
   131  		if err != nil {
   132  			log.Fatal(err)
   133  		}
   134  		for _, pkg := range strings.Fields(string(stds)) {
   135  			if !internalPkg.MatchString(pkg) {
   136  				pkgNames = append(pkgNames, pkg)
   137  			}
   138  		}
   139  	}
   140  
   141  	var featureCtx = make(map[string]map[string]bool) // feature -> context name -> true
   142  	for _, context := range contexts {
   143  		w := NewWalker(context, filepath.Join(build.Default.GOROOT, "src"))
   144  
   145  		for _, name := range pkgNames {
   146  			// - Package "unsafe" contains special signatures requiring
   147  			//   extra care when printing them - ignore since it is not
   148  			//   going to change w/o a language change.
   149  			// - We don't care about the API of commands.
   150  			if name != "unsafe" && !strings.HasPrefix(name, "cmd/") {
   151  				if name == "runtime/cgo" && !context.CgoEnabled {
   152  					// w.Import(name) will return nil
   153  					continue
   154  				}
   155  				pkg, _ := w.Import(name)
   156  				w.export(pkg)
   157  			}
   158  		}
   159  
   160  		ctxName := contextName(context)
   161  		for _, f := range w.Features() {
   162  			if featureCtx[f] == nil {
   163  				featureCtx[f] = make(map[string]bool)
   164  			}
   165  			featureCtx[f][ctxName] = true
   166  		}
   167  	}
   168  
   169  	var features []string
   170  	for f, cmap := range featureCtx {
   171  		if len(cmap) == len(contexts) {
   172  			features = append(features, f)
   173  			continue
   174  		}
   175  		comma := strings.Index(f, ",")
   176  		for cname := range cmap {
   177  			f2 := fmt.Sprintf("%s (%s)%s", f[:comma], cname, f[comma:])
   178  			features = append(features, f2)
   179  		}
   180  	}
   181  
   182  	fail := false
   183  	defer func() {
   184  		if fail {
   185  			os.Exit(1)
   186  		}
   187  	}()
   188  
   189  	bw := bufio.NewWriter(os.Stdout)
   190  	defer bw.Flush()
   191  
   192  	if *checkFile == "" {
   193  		sort.Strings(features)
   194  		for _, f := range features {
   195  			fmt.Fprintln(bw, f)
   196  		}
   197  		return
   198  	}
   199  
   200  	var required []string
   201  	for _, file := range strings.Split(*checkFile, ",") {
   202  		required = append(required, fileFeatures(file)...)
   203  	}
   204  	optional := fileFeatures(*nextFile)
   205  	exception := fileFeatures(*exceptFile)
   206  	fail = !compareAPI(bw, features, required, optional, exception,
   207  		*allowNew && strings.Contains(runtime.Version(), "devel"))
   208  }
   209  
   210  // export emits the exported package features.
   211  func (w *Walker) export(pkg *types.Package) {
   212  	if *verbose {
   213  		log.Println(pkg)
   214  	}
   215  	pop := w.pushScope("pkg " + pkg.Path())
   216  	w.current = pkg
   217  	scope := pkg.Scope()
   218  	for _, name := range scope.Names() {
   219  		if ast.IsExported(name) {
   220  			w.emitObj(scope.Lookup(name))
   221  		}
   222  	}
   223  	pop()
   224  }
   225  
   226  func set(items []string) map[string]bool {
   227  	s := make(map[string]bool)
   228  	for _, v := range items {
   229  		s[v] = true
   230  	}
   231  	return s
   232  }
   233  
   234  var spaceParensRx = regexp.MustCompile(` \(\S+?\)`)
   235  
   236  func featureWithoutContext(f string) string {
   237  	if !strings.Contains(f, "(") {
   238  		return f
   239  	}
   240  	return spaceParensRx.ReplaceAllString(f, "")
   241  }
   242  
   243  func compareAPI(w io.Writer, features, required, optional, exception []string, allowAdd bool) (ok bool) {
   244  	ok = true
   245  
   246  	optionalSet := set(optional)
   247  	exceptionSet := set(exception)
   248  	featureSet := set(features)
   249  
   250  	sort.Strings(features)
   251  	sort.Strings(required)
   252  
   253  	take := func(sl *[]string) string {
   254  		s := (*sl)[0]
   255  		*sl = (*sl)[1:]
   256  		return s
   257  	}
   258  
   259  	for len(required) > 0 || len(features) > 0 {
   260  		switch {
   261  		case len(features) == 0 || (len(required) > 0 && required[0] < features[0]):
   262  			feature := take(&required)
   263  			if exceptionSet[feature] {
   264  				// An "unfortunate" case: the feature was once
   265  				// included in the API (e.g. go1.txt), but was
   266  				// subsequently removed. These are already
   267  				// acknowledged by being in the file
   268  				// "api/except.txt". No need to print them out
   269  				// here.
   270  			} else if featureSet[featureWithoutContext(feature)] {
   271  				// okay.
   272  			} else {
   273  				fmt.Fprintf(w, "-%s\n", feature)
   274  				ok = false // broke compatibility
   275  			}
   276  		case len(required) == 0 || (len(features) > 0 && required[0] > features[0]):
   277  			newFeature := take(&features)
   278  			if optionalSet[newFeature] {
   279  				// Known added feature to the upcoming release.
   280  				// Delete it from the map so we can detect any upcoming features
   281  				// which were never seen.  (so we can clean up the nextFile)
   282  				delete(optionalSet, newFeature)
   283  			} else {
   284  				fmt.Fprintf(w, "+%s\n", newFeature)
   285  				if !allowAdd {
   286  					ok = false // we're in lock-down mode for next release
   287  				}
   288  			}
   289  		default:
   290  			take(&required)
   291  			take(&features)
   292  		}
   293  	}
   294  
   295  	// In next file, but not in API.
   296  	var missing []string
   297  	for feature := range optionalSet {
   298  		missing = append(missing, feature)
   299  	}
   300  	sort.Strings(missing)
   301  	for _, feature := range missing {
   302  		fmt.Fprintf(w, "±%s\n", feature)
   303  	}
   304  	return
   305  }
   306  
   307  func fileFeatures(filename string) []string {
   308  	if filename == "" {
   309  		return nil
   310  	}
   311  	bs, err := ioutil.ReadFile(filename)
   312  	if err != nil {
   313  		log.Fatalf("Error reading file %s: %v", filename, err)
   314  	}
   315  	lines := strings.Split(string(bs), "\n")
   316  	var nonblank []string
   317  	for _, line := range lines {
   318  		line = strings.TrimSpace(line)
   319  		if line != "" && !strings.HasPrefix(line, "#") {
   320  			nonblank = append(nonblank, line)
   321  		}
   322  	}
   323  	return nonblank
   324  }
   325  
   326  var fset = token.NewFileSet()
   327  
   328  type Walker struct {
   329  	context  *build.Context
   330  	root     string
   331  	scope    []string
   332  	current  *types.Package
   333  	features map[string]bool           // set
   334  	imported map[string]*types.Package // packages already imported
   335  }
   336  
   337  func NewWalker(context *build.Context, root string) *Walker {
   338  	return &Walker{
   339  		context:  context,
   340  		root:     root,
   341  		features: map[string]bool{},
   342  		imported: map[string]*types.Package{"unsafe": types.Unsafe},
   343  	}
   344  }
   345  
   346  func (w *Walker) Features() (fs []string) {
   347  	for f := range w.features {
   348  		fs = append(fs, f)
   349  	}
   350  	sort.Strings(fs)
   351  	return
   352  }
   353  
   354  var parsedFileCache = make(map[string]*ast.File)
   355  
   356  func (w *Walker) parseFile(dir, file string) (*ast.File, error) {
   357  	filename := filepath.Join(dir, file)
   358  	if f := parsedFileCache[filename]; f != nil {
   359  		return f, nil
   360  	}
   361  
   362  	f, err := parser.ParseFile(fset, filename, nil, 0)
   363  	if err != nil {
   364  		return nil, err
   365  	}
   366  	parsedFileCache[filename] = f
   367  
   368  	return f, nil
   369  }
   370  
   371  func contains(list []string, s string) bool {
   372  	for _, t := range list {
   373  		if t == s {
   374  			return true
   375  		}
   376  	}
   377  	return false
   378  }
   379  
   380  // The package cache doesn't operate correctly in rare (so far artificial)
   381  // circumstances (issue 8425). Disable before debugging non-obvious errors
   382  // from the type-checker.
   383  const usePkgCache = true
   384  
   385  var (
   386  	pkgCache = map[string]*types.Package{} // map tagKey to package
   387  	pkgTags  = map[string][]string{}       // map import dir to list of relevant tags
   388  )
   389  
   390  // tagKey returns the tag-based key to use in the pkgCache.
   391  // It is a comma-separated string; the first part is dir, the rest tags.
   392  // The satisfied tags are derived from context but only those that
   393  // matter (the ones listed in the tags argument) are used.
   394  // The tags list, which came from go/build's Package.AllTags,
   395  // is known to be sorted.
   396  func tagKey(dir string, context *build.Context, tags []string) string {
   397  	ctags := map[string]bool{
   398  		context.GOOS:   true,
   399  		context.GOARCH: true,
   400  	}
   401  	if context.CgoEnabled {
   402  		ctags["cgo"] = true
   403  	}
   404  	for _, tag := range context.BuildTags {
   405  		ctags[tag] = true
   406  	}
   407  	// TODO: ReleaseTags (need to load default)
   408  	key := dir
   409  	for _, tag := range tags {
   410  		if ctags[tag] {
   411  			key += "," + tag
   412  		}
   413  	}
   414  	return key
   415  }
   416  
   417  // Importing is a sentinel taking the place in Walker.imported
   418  // for a package that is in the process of being imported.
   419  var importing types.Package
   420  
   421  func (w *Walker) Import(name string) (*types.Package, error) {
   422  	pkg := w.imported[name]
   423  	if pkg != nil {
   424  		if pkg == &importing {
   425  			log.Fatalf("cycle importing package %q", name)
   426  		}
   427  		return pkg, nil
   428  	}
   429  	w.imported[name] = &importing
   430  
   431  	root := w.root
   432  	if strings.HasPrefix(name, "golang.org/x/") {
   433  		root = filepath.Join(root, "vendor")
   434  	}
   435  
   436  	// Determine package files.
   437  	dir := filepath.Join(root, filepath.FromSlash(name))
   438  	if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
   439  		log.Fatalf("no source in tree for import %q: %v", name, err)
   440  	}
   441  
   442  	context := w.context
   443  	if context == nil {
   444  		context = &build.Default
   445  	}
   446  
   447  	// Look in cache.
   448  	// If we've already done an import with the same set
   449  	// of relevant tags, reuse the result.
   450  	var key string
   451  	if usePkgCache {
   452  		if tags, ok := pkgTags[dir]; ok {
   453  			key = tagKey(dir, context, tags)
   454  			if pkg := pkgCache[key]; pkg != nil {
   455  				w.imported[name] = pkg
   456  				return pkg, nil
   457  			}
   458  		}
   459  	}
   460  
   461  	info, err := context.ImportDir(dir, 0)
   462  	if err != nil {
   463  		if _, nogo := err.(*build.NoGoError); nogo {
   464  			return nil, nil
   465  		}
   466  		log.Fatalf("pkg %q, dir %q: ScanDir: %v", name, dir, err)
   467  	}
   468  
   469  	// Save tags list first time we see a directory.
   470  	if usePkgCache {
   471  		if _, ok := pkgTags[dir]; !ok {
   472  			pkgTags[dir] = info.AllTags
   473  			key = tagKey(dir, context, info.AllTags)
   474  		}
   475  	}
   476  
   477  	filenames := append(append([]string{}, info.GoFiles...), info.CgoFiles...)
   478  
   479  	// Parse package files.
   480  	var files []*ast.File
   481  	for _, file := range filenames {
   482  		f, err := w.parseFile(dir, file)
   483  		if err != nil {
   484  			log.Fatalf("error parsing package %s: %s", name, err)
   485  		}
   486  		files = append(files, f)
   487  	}
   488  
   489  	// Type-check package files.
   490  	conf := types.Config{
   491  		IgnoreFuncBodies: true,
   492  		FakeImportC:      true,
   493  		Importer:         w,
   494  	}
   495  	pkg, err = conf.Check(name, fset, files, nil)
   496  	if err != nil {
   497  		ctxt := "<no context>"
   498  		if w.context != nil {
   499  			ctxt = fmt.Sprintf("%s-%s", w.context.GOOS, w.context.GOARCH)
   500  		}
   501  		log.Fatalf("error typechecking package %s: %s (%s)", name, err, ctxt)
   502  	}
   503  
   504  	if usePkgCache {
   505  		pkgCache[key] = pkg
   506  	}
   507  
   508  	w.imported[name] = pkg
   509  	return pkg, nil
   510  }
   511  
   512  // pushScope enters a new scope (walking a package, type, node, etc)
   513  // and returns a function that will leave the scope (with sanity checking
   514  // for mismatched pushes & pops)
   515  func (w *Walker) pushScope(name string) (popFunc func()) {
   516  	w.scope = append(w.scope, name)
   517  	return func() {
   518  		if len(w.scope) == 0 {
   519  			log.Fatalf("attempt to leave scope %q with empty scope list", name)
   520  		}
   521  		if w.scope[len(w.scope)-1] != name {
   522  			log.Fatalf("attempt to leave scope %q, but scope is currently %#v", name, w.scope)
   523  		}
   524  		w.scope = w.scope[:len(w.scope)-1]
   525  	}
   526  }
   527  
   528  func sortedMethodNames(typ *types.Interface) []string {
   529  	n := typ.NumMethods()
   530  	list := make([]string, n)
   531  	for i := range list {
   532  		list[i] = typ.Method(i).Name()
   533  	}
   534  	sort.Strings(list)
   535  	return list
   536  }
   537  
   538  func (w *Walker) writeType(buf *bytes.Buffer, typ types.Type) {
   539  	switch typ := typ.(type) {
   540  	case *types.Basic:
   541  		s := typ.Name()
   542  		switch typ.Kind() {
   543  		case types.UnsafePointer:
   544  			s = "unsafe.Pointer"
   545  		case types.UntypedBool:
   546  			s = "ideal-bool"
   547  		case types.UntypedInt:
   548  			s = "ideal-int"
   549  		case types.UntypedRune:
   550  			// "ideal-char" for compatibility with old tool
   551  			// TODO(gri) change to "ideal-rune"
   552  			s = "ideal-char"
   553  		case types.UntypedFloat:
   554  			s = "ideal-float"
   555  		case types.UntypedComplex:
   556  			s = "ideal-complex"
   557  		case types.UntypedString:
   558  			s = "ideal-string"
   559  		case types.UntypedNil:
   560  			panic("should never see untyped nil type")
   561  		default:
   562  			switch s {
   563  			case "byte":
   564  				s = "uint8"
   565  			case "rune":
   566  				s = "int32"
   567  			}
   568  		}
   569  		buf.WriteString(s)
   570  
   571  	case *types.Array:
   572  		fmt.Fprintf(buf, "[%d]", typ.Len())
   573  		w.writeType(buf, typ.Elem())
   574  
   575  	case *types.Slice:
   576  		buf.WriteString("[]")
   577  		w.writeType(buf, typ.Elem())
   578  
   579  	case *types.Struct:
   580  		buf.WriteString("struct")
   581  
   582  	case *types.Pointer:
   583  		buf.WriteByte('*')
   584  		w.writeType(buf, typ.Elem())
   585  
   586  	case *types.Tuple:
   587  		panic("should never see a tuple type")
   588  
   589  	case *types.Signature:
   590  		buf.WriteString("func")
   591  		w.writeSignature(buf, typ)
   592  
   593  	case *types.Interface:
   594  		buf.WriteString("interface{")
   595  		if typ.NumMethods() > 0 {
   596  			buf.WriteByte(' ')
   597  			buf.WriteString(strings.Join(sortedMethodNames(typ), ", "))
   598  			buf.WriteByte(' ')
   599  		}
   600  		buf.WriteString("}")
   601  
   602  	case *types.Map:
   603  		buf.WriteString("map[")
   604  		w.writeType(buf, typ.Key())
   605  		buf.WriteByte(']')
   606  		w.writeType(buf, typ.Elem())
   607  
   608  	case *types.Chan:
   609  		var s string
   610  		switch typ.Dir() {
   611  		case types.SendOnly:
   612  			s = "chan<- "
   613  		case types.RecvOnly:
   614  			s = "<-chan "
   615  		case types.SendRecv:
   616  			s = "chan "
   617  		default:
   618  			panic("unreachable")
   619  		}
   620  		buf.WriteString(s)
   621  		w.writeType(buf, typ.Elem())
   622  
   623  	case *types.Named:
   624  		obj := typ.Obj()
   625  		pkg := obj.Pkg()
   626  		if pkg != nil && pkg != w.current {
   627  			buf.WriteString(pkg.Name())
   628  			buf.WriteByte('.')
   629  		}
   630  		buf.WriteString(typ.Obj().Name())
   631  
   632  	default:
   633  		panic(fmt.Sprintf("unknown type %T", typ))
   634  	}
   635  }
   636  
   637  func (w *Walker) writeSignature(buf *bytes.Buffer, sig *types.Signature) {
   638  	w.writeParams(buf, sig.Params(), sig.Variadic())
   639  	switch res := sig.Results(); res.Len() {
   640  	case 0:
   641  		// nothing to do
   642  	case 1:
   643  		buf.WriteByte(' ')
   644  		w.writeType(buf, res.At(0).Type())
   645  	default:
   646  		buf.WriteByte(' ')
   647  		w.writeParams(buf, res, false)
   648  	}
   649  }
   650  
   651  func (w *Walker) writeParams(buf *bytes.Buffer, t *types.Tuple, variadic bool) {
   652  	buf.WriteByte('(')
   653  	for i, n := 0, t.Len(); i < n; i++ {
   654  		if i > 0 {
   655  			buf.WriteString(", ")
   656  		}
   657  		typ := t.At(i).Type()
   658  		if variadic && i+1 == n {
   659  			buf.WriteString("...")
   660  			typ = typ.(*types.Slice).Elem()
   661  		}
   662  		w.writeType(buf, typ)
   663  	}
   664  	buf.WriteByte(')')
   665  }
   666  
   667  func (w *Walker) typeString(typ types.Type) string {
   668  	var buf bytes.Buffer
   669  	w.writeType(&buf, typ)
   670  	return buf.String()
   671  }
   672  
   673  func (w *Walker) signatureString(sig *types.Signature) string {
   674  	var buf bytes.Buffer
   675  	w.writeSignature(&buf, sig)
   676  	return buf.String()
   677  }
   678  
   679  func (w *Walker) emitObj(obj types.Object) {
   680  	switch obj := obj.(type) {
   681  	case *types.Const:
   682  		w.emitf("const %s %s", obj.Name(), w.typeString(obj.Type()))
   683  		w.emitf("const %s = %s", obj.Name(), obj.Val())
   684  	case *types.Var:
   685  		w.emitf("var %s %s", obj.Name(), w.typeString(obj.Type()))
   686  	case *types.TypeName:
   687  		w.emitType(obj)
   688  	case *types.Func:
   689  		w.emitFunc(obj)
   690  	default:
   691  		panic("unknown object: " + obj.String())
   692  	}
   693  }
   694  
   695  func (w *Walker) emitType(obj *types.TypeName) {
   696  	name := obj.Name()
   697  	typ := obj.Type()
   698  	switch typ := typ.Underlying().(type) {
   699  	case *types.Struct:
   700  		w.emitStructType(name, typ)
   701  	case *types.Interface:
   702  		w.emitIfaceType(name, typ)
   703  		return // methods are handled by emitIfaceType
   704  	default:
   705  		w.emitf("type %s %s", name, w.typeString(typ.Underlying()))
   706  	}
   707  
   708  	// emit methods with value receiver
   709  	var methodNames map[string]bool
   710  	vset := types.NewMethodSet(typ)
   711  	for i, n := 0, vset.Len(); i < n; i++ {
   712  		m := vset.At(i)
   713  		if m.Obj().Exported() {
   714  			w.emitMethod(m)
   715  			if methodNames == nil {
   716  				methodNames = make(map[string]bool)
   717  			}
   718  			methodNames[m.Obj().Name()] = true
   719  		}
   720  	}
   721  
   722  	// emit methods with pointer receiver; exclude
   723  	// methods that we have emitted already
   724  	// (the method set of *T includes the methods of T)
   725  	pset := types.NewMethodSet(types.NewPointer(typ))
   726  	for i, n := 0, pset.Len(); i < n; i++ {
   727  		m := pset.At(i)
   728  		if m.Obj().Exported() && !methodNames[m.Obj().Name()] {
   729  			w.emitMethod(m)
   730  		}
   731  	}
   732  }
   733  
   734  func (w *Walker) emitStructType(name string, typ *types.Struct) {
   735  	typeStruct := fmt.Sprintf("type %s struct", name)
   736  	w.emitf(typeStruct)
   737  	defer w.pushScope(typeStruct)()
   738  
   739  	for i := 0; i < typ.NumFields(); i++ {
   740  		f := typ.Field(i)
   741  		if !f.Exported() {
   742  			continue
   743  		}
   744  		typ := f.Type()
   745  		if f.Anonymous() {
   746  			w.emitf("embedded %s", w.typeString(typ))
   747  			continue
   748  		}
   749  		w.emitf("%s %s", f.Name(), w.typeString(typ))
   750  	}
   751  }
   752  
   753  func (w *Walker) emitIfaceType(name string, typ *types.Interface) {
   754  	pop := w.pushScope("type " + name + " interface")
   755  
   756  	var methodNames []string
   757  	complete := true
   758  	mset := types.NewMethodSet(typ)
   759  	for i, n := 0, mset.Len(); i < n; i++ {
   760  		m := mset.At(i).Obj().(*types.Func)
   761  		if !m.Exported() {
   762  			complete = false
   763  			continue
   764  		}
   765  		methodNames = append(methodNames, m.Name())
   766  		w.emitf("%s%s", m.Name(), w.signatureString(m.Type().(*types.Signature)))
   767  	}
   768  
   769  	if !complete {
   770  		// The method set has unexported methods, so all the
   771  		// implementations are provided by the same package,
   772  		// so the method set can be extended. Instead of recording
   773  		// the full set of names (below), record only that there were
   774  		// unexported methods. (If the interface shrinks, we will notice
   775  		// because a method signature emitted during the last loop
   776  		// will disappear.)
   777  		w.emitf("unexported methods")
   778  	}
   779  
   780  	pop()
   781  
   782  	if !complete {
   783  		return
   784  	}
   785  
   786  	if len(methodNames) == 0 {
   787  		w.emitf("type %s interface {}", name)
   788  		return
   789  	}
   790  
   791  	sort.Strings(methodNames)
   792  	w.emitf("type %s interface { %s }", name, strings.Join(methodNames, ", "))
   793  }
   794  
   795  func (w *Walker) emitFunc(f *types.Func) {
   796  	sig := f.Type().(*types.Signature)
   797  	if sig.Recv() != nil {
   798  		panic("method considered a regular function: " + f.String())
   799  	}
   800  	w.emitf("func %s%s", f.Name(), w.signatureString(sig))
   801  }
   802  
   803  func (w *Walker) emitMethod(m *types.Selection) {
   804  	sig := m.Type().(*types.Signature)
   805  	recv := sig.Recv().Type()
   806  	// report exported methods with unexported receiver base type
   807  	if true {
   808  		base := recv
   809  		if p, _ := recv.(*types.Pointer); p != nil {
   810  			base = p.Elem()
   811  		}
   812  		if obj := base.(*types.Named).Obj(); !obj.Exported() {
   813  			log.Fatalf("exported method with unexported receiver base type: %s", m)
   814  		}
   815  	}
   816  	w.emitf("method (%s) %s%s", w.typeString(recv), m.Obj().Name(), w.signatureString(sig))
   817  }
   818  
   819  func (w *Walker) emitf(format string, args ...interface{}) {
   820  	f := strings.Join(w.scope, ", ") + ", " + fmt.Sprintf(format, args...)
   821  	if strings.Contains(f, "\n") {
   822  		panic("feature contains newlines: " + f)
   823  	}
   824  
   825  	if _, dup := w.features[f]; dup {
   826  		panic("duplicate feature inserted: " + f)
   827  	}
   828  	w.features[f] = true
   829  
   830  	if *verbose {
   831  		log.Printf("feature: %s", f)
   832  	}
   833  }