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