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