2012-01-25 18:47:57 -07:00
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2013-08-09 16:44:00 -06:00
// +build api_tool
2013-08-08 15:10:59 -06:00
// Binary api computes the exported API of a set of Go packages.
2012-01-25 18:47:57 -07:00
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
2012-10-30 04:23:44 -06:00
"io"
2012-01-25 18:47:57 -07:00
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
2012-10-30 06:12:59 -06:00
"regexp"
2012-06-08 11:44:13 -06:00
"runtime"
2012-01-25 18:47:57 -07:00
"sort"
"strings"
2013-08-08 15:10:59 -06:00
"code.google.com/p/go.tools/go/types"
2012-01-25 18:47:57 -07:00
)
// Flags
var (
2013-05-06 18:25:09 -06:00
checkFile = flag . String ( "c" , "" , "optional comma-separated filename(s) to check API against" )
2012-10-03 19:35:17 -06:00
allowNew = flag . Bool ( "allow_new" , true , "allow API additions" )
exceptFile = flag . String ( "except" , "" , "optional filename of packages that are allowed to change without triggering a failure in the tool" )
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." )
verbose = flag . Bool ( "v" , false , "verbose debugging" )
forceCtx = flag . String ( "contexts" , "" , "optional comma-separated list of <goos>-<goarch>[-cgo] to override default contexts." )
2012-01-25 18:47:57 -07:00
)
2012-05-23 14:45:53 -06:00
// contexts are the default contexts which are scanned, unless
// overridden by the -contexts flag.
2012-02-07 19:13:11 -07:00
var contexts = [ ] * build . Context {
{ GOOS : "linux" , GOARCH : "386" , CgoEnabled : true } ,
{ GOOS : "linux" , GOARCH : "386" } ,
{ GOOS : "linux" , GOARCH : "amd64" , CgoEnabled : true } ,
{ GOOS : "linux" , GOARCH : "amd64" } ,
2013-05-21 07:47:32 -06:00
{ GOOS : "linux" , GOARCH : "arm" , CgoEnabled : true } ,
2012-06-04 01:21:58 -06:00
{ GOOS : "linux" , GOARCH : "arm" } ,
2012-02-07 19:13:11 -07:00
{ GOOS : "darwin" , GOARCH : "386" , CgoEnabled : true } ,
{ GOOS : "darwin" , GOARCH : "386" } ,
{ GOOS : "darwin" , GOARCH : "amd64" , CgoEnabled : true } ,
{ GOOS : "darwin" , GOARCH : "amd64" } ,
{ GOOS : "windows" , GOARCH : "amd64" } ,
{ GOOS : "windows" , GOARCH : "386" } ,
2013-05-21 07:47:32 -06:00
{ GOOS : "freebsd" , GOARCH : "386" , CgoEnabled : true } ,
2012-06-01 19:42:36 -06:00
{ GOOS : "freebsd" , GOARCH : "386" } ,
2013-05-21 07:47:32 -06:00
{ GOOS : "freebsd" , GOARCH : "amd64" , CgoEnabled : true } ,
{ GOOS : "freebsd" , GOARCH : "amd64" } ,
{ GOOS : "freebsd" , GOARCH : "arm" , CgoEnabled : true } ,
{ GOOS : "freebsd" , GOARCH : "arm" } ,
{ GOOS : "netbsd" , GOARCH : "386" , CgoEnabled : true } ,
{ GOOS : "netbsd" , GOARCH : "386" } ,
{ GOOS : "netbsd" , GOARCH : "amd64" , CgoEnabled : true } ,
{ GOOS : "netbsd" , GOARCH : "amd64" } ,
{ GOOS : "netbsd" , GOARCH : "arm" , CgoEnabled : true } ,
{ GOOS : "netbsd" , GOARCH : "arm" } ,
{ GOOS : "openbsd" , GOARCH : "386" , CgoEnabled : true } ,
{ GOOS : "openbsd" , GOARCH : "386" } ,
{ GOOS : "openbsd" , GOARCH : "amd64" , CgoEnabled : true } ,
{ GOOS : "openbsd" , GOARCH : "amd64" } ,
2012-02-07 19:13:11 -07:00
}
func contextName ( c * build . Context ) string {
s := c . GOOS + "-" + c . GOARCH
if c . CgoEnabled {
return s + "-cgo"
}
return s
}
2012-05-23 14:45:53 -06:00
func parseContext ( c string ) * build . Context {
parts := strings . Split ( c , "-" )
if len ( parts ) < 2 {
log . Fatalf ( "bad context: %q" , c )
}
bc := & build . Context {
GOOS : parts [ 0 ] ,
GOARCH : parts [ 1 ] ,
}
if len ( parts ) == 3 {
if parts [ 2 ] == "cgo" {
bc . CgoEnabled = true
} else {
log . Fatalf ( "bad context: %q" , c )
}
}
return bc
}
func setContexts ( ) {
contexts = [ ] * build . Context { }
for _ , c := range strings . Split ( * forceCtx , "," ) {
contexts = append ( contexts , parseContext ( c ) )
}
}
2014-07-21 13:06:30 -06:00
var internalPkg = regexp . MustCompile ( ` (^|/)internal($|/) ` )
2012-01-25 18:47:57 -07:00
func main ( ) {
flag . Parse ( )
2012-09-24 19:35:20 -06:00
if ! strings . Contains ( runtime . Version ( ) , "weekly" ) && ! strings . Contains ( runtime . Version ( ) , "devel" ) {
2012-06-08 11:44:13 -06:00
if * nextFile != "" {
fmt . Printf ( "Go version is %q, ignoring -next %s\n" , runtime . Version ( ) , * nextFile )
* nextFile = ""
}
}
2012-05-23 14:45:53 -06:00
if * forceCtx != "" {
setContexts ( )
}
for _ , c := range contexts {
c . Compiler = build . Default . Compiler
}
2013-08-08 15:10:59 -06:00
var pkgNames [ ] string
2012-01-25 18:47:57 -07:00
if flag . NArg ( ) > 0 {
2013-08-08 15:10:59 -06:00
pkgNames = flag . Args ( )
2012-01-25 18:47:57 -07:00
} else {
stds , err := exec . Command ( "go" , "list" , "std" ) . Output ( )
if err != nil {
log . Fatal ( err )
}
2014-07-21 13:06:30 -06:00
for _ , pkg := range strings . Fields ( string ( stds ) ) {
if ! internalPkg . MatchString ( pkg ) {
pkgNames = append ( pkgNames , pkg )
}
}
2012-01-25 18:47:57 -07:00
}
2012-02-07 19:13:11 -07:00
var featureCtx = make ( map [ string ] map [ string ] bool ) // feature -> context name -> true
for _ , context := range contexts {
2013-08-08 15:10:59 -06:00
w := NewWalker ( context , filepath . Join ( build . Default . GOROOT , "src/pkg" ) )
2012-02-07 19:13:11 -07:00
2013-08-08 15:10:59 -06:00
for _ , name := range pkgNames {
// - Package "unsafe" contains special signatures requiring
// extra care when printing them - ignore since it is not
// going to change w/o a language change.
// - We don't care about the API of commands.
if name != "unsafe" && ! strings . HasPrefix ( name , "cmd/" ) {
2013-09-11 12:42:34 -06:00
if name == "runtime/cgo" && ! context . CgoEnabled {
// w.Import(name) will return nil
continue
}
2013-08-08 15:10:59 -06:00
w . export ( w . Import ( name ) )
2012-02-07 19:13:11 -07:00
}
}
2013-08-08 15:10:59 -06:00
2012-02-07 19:13:11 -07:00
ctxName := contextName ( context )
for _ , f := range w . Features ( ) {
if featureCtx [ f ] == nil {
featureCtx [ f ] = make ( map [ string ] bool )
}
featureCtx [ f ] [ ctxName ] = true
}
2012-01-29 22:04:13 -07:00
}
2012-01-25 18:47:57 -07:00
2012-02-07 19:13:11 -07:00
var features [ ] string
for f , cmap := range featureCtx {
if len ( cmap ) == len ( contexts ) {
features = append ( features , f )
2012-01-25 18:47:57 -07:00
continue
}
2012-02-07 19:13:11 -07:00
comma := strings . Index ( f , "," )
for cname := range cmap {
f2 := fmt . Sprintf ( "%s (%s)%s" , f [ : comma ] , cname , f [ comma : ] )
features = append ( features , f2 )
2012-01-25 18:47:57 -07:00
}
}
2012-05-22 19:41:20 -06:00
fail := false
defer func ( ) {
if fail {
os . Exit ( 1 )
}
} ( )
2012-01-25 18:47:57 -07:00
bw := bufio . NewWriter ( os . Stdout )
defer bw . Flush ( )
2012-05-22 19:41:20 -06:00
if * checkFile == "" {
2013-01-19 23:20:46 -07:00
sort . Strings ( features )
2012-05-22 19:41:20 -06:00
for _ , f := range features {
2013-08-08 15:10:59 -06:00
fmt . Fprintln ( bw , f )
2012-01-25 18:47:57 -07:00
}
2012-05-22 19:41:20 -06:00
return
}
2013-05-06 18:25:09 -06:00
var required [ ] string
for _ , file := range strings . Split ( * checkFile , "," ) {
required = append ( required , fileFeatures ( file ) ... )
}
2012-10-30 04:23:44 -06:00
optional := fileFeatures ( * nextFile )
exception := fileFeatures ( * exceptFile )
fail = ! compareAPI ( bw , features , required , optional , exception )
}
2012-05-22 19:41:20 -06:00
2013-08-08 15:10:59 -06:00
// export emits the exported package features.
func ( w * Walker ) export ( pkg * types . Package ) {
if * verbose {
log . Println ( pkg )
}
pop := w . pushScope ( "pkg " + pkg . Path ( ) )
w . current = pkg
scope := pkg . Scope ( )
for _ , name := range scope . Names ( ) {
if ast . IsExported ( name ) {
w . emitObj ( scope . Lookup ( name ) )
}
}
pop ( )
}
2012-10-30 06:12:59 -06:00
func set ( items [ ] string ) map [ string ] bool {
s := make ( map [ string ] bool )
for _ , v := range items {
s [ v ] = true
}
return s
}
var spaceParensRx = regexp . MustCompile ( ` \(\S+?\) ` )
func featureWithoutContext ( f string ) string {
if ! strings . Contains ( f , "(" ) {
return f
}
return spaceParensRx . ReplaceAllString ( f , "" )
}
2012-10-30 04:23:44 -06:00
func compareAPI ( w io . Writer , features , required , optional , exception [ ] string ) ( ok bool ) {
ok = true
2012-05-22 19:41:20 -06:00
2012-10-30 06:12:59 -06:00
optionalSet := set ( optional )
exceptionSet := set ( exception )
featureSet := set ( features )
2012-10-30 04:23:44 -06:00
sort . Strings ( features )
sort . Strings ( required )
2012-10-03 19:35:17 -06:00
2012-05-22 19:41:20 -06:00
take := func ( sl * [ ] string ) string {
s := ( * sl ) [ 0 ]
* sl = ( * sl ) [ 1 : ]
return s
}
for len ( required ) > 0 || len ( features ) > 0 {
switch {
2012-10-30 06:12:59 -06:00
case len ( features ) == 0 || ( len ( required ) > 0 && required [ 0 ] < features [ 0 ] ) :
2012-10-03 19:35:17 -06:00
feature := take ( & required )
2012-10-30 04:23:44 -06:00
if exceptionSet [ feature ] {
2013-05-14 10:43:56 -06:00
// An "unfortunate" case: the feature was once
// included in the API (e.g. go1.txt), but was
// subsequently removed. These are already
// acknowledged by being in the file
// "api/except.txt". No need to print them out
// here.
2012-10-30 06:12:59 -06:00
} else if featureSet [ featureWithoutContext ( feature ) ] {
// okay.
2012-10-03 19:35:17 -06:00
} else {
2012-10-30 04:23:44 -06:00
fmt . Fprintf ( w , "-%s\n" , feature )
ok = false // broke compatibility
2012-10-03 19:35:17 -06:00
}
2012-10-30 06:12:59 -06:00
case len ( required ) == 0 || ( len ( features ) > 0 && required [ 0 ] > features [ 0 ] ) :
2012-05-22 19:41:20 -06:00
newFeature := take ( & features )
2012-10-30 04:23:44 -06:00
if optionalSet [ newFeature ] {
2012-05-22 19:41:20 -06:00
// Known added feature to the upcoming release.
// Delete it from the map so we can detect any upcoming features
// which were never seen. (so we can clean up the nextFile)
2012-10-30 04:23:44 -06:00
delete ( optionalSet , newFeature )
2012-05-22 19:41:20 -06:00
} else {
2012-10-30 04:23:44 -06:00
fmt . Fprintf ( w , "+%s\n" , newFeature )
2012-05-22 19:41:20 -06:00
if ! * allowNew {
2012-10-30 04:23:44 -06:00
ok = false // we're in lock-down mode for next release
2012-05-22 19:41:20 -06:00
}
2012-01-25 18:47:57 -07:00
}
2012-05-22 19:41:20 -06:00
default :
take ( & required )
take ( & features )
2012-01-25 18:47:57 -07:00
}
}
2012-05-22 19:41:20 -06:00
2012-09-26 23:39:56 -06:00
// In next file, but not in API.
2012-05-22 19:41:20 -06:00
var missing [ ] string
2012-10-30 04:23:44 -06:00
for feature := range optionalSet {
2012-05-22 19:41:20 -06:00
missing = append ( missing , feature )
}
sort . Strings ( missing )
for _ , feature := range missing {
2012-10-30 04:23:44 -06:00
fmt . Fprintf ( w , "±%s\n" , feature )
2012-05-22 19:41:20 -06:00
}
2012-10-30 04:23:44 -06:00
return
2012-05-22 19:41:20 -06:00
}
func fileFeatures ( filename string ) [ ] string {
2012-10-30 04:23:44 -06:00
if filename == "" {
return nil
}
2012-05-22 19:41:20 -06:00
bs , err := ioutil . ReadFile ( filename )
if err != nil {
log . Fatalf ( "Error reading file %s: %v" , filename , err )
}
2012-06-08 11:44:13 -06:00
text := strings . TrimSpace ( string ( bs ) )
if text == "" {
return nil
}
return strings . Split ( text , "\n" )
2012-01-25 18:47:57 -07:00
}
2012-11-13 10:59:46 -07:00
var fset = token . NewFileSet ( )
2012-01-25 18:47:57 -07:00
type Walker struct {
2013-08-08 15:10:59 -06:00
context * build . Context
root string
scope [ ] string
current * types . Package
features map [ string ] bool // set
imported map [ string ] * types . Package // packages already imported
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func NewWalker ( context * build . Context , root string ) * Walker {
2012-01-25 18:47:57 -07:00
return & Walker {
2013-08-08 15:10:59 -06:00
context : context ,
root : root ,
features : map [ string ] bool { } ,
imported : map [ string ] * types . Package { "unsafe" : types . Unsafe } ,
2012-01-25 18:47:57 -07:00
}
}
func ( w * Walker ) Features ( ) ( fs [ ] string ) {
for f := range w . features {
fs = append ( fs , f )
}
sort . Strings ( fs )
return
}
2013-08-08 15:10:59 -06:00
var parsedFileCache = make ( map [ string ] * ast . File )
func ( w * Walker ) parseFile ( dir , file string ) ( * ast . File , error ) {
filename := filepath . Join ( dir , file )
f , _ := parsedFileCache [ filename ]
if f != nil {
return f , nil
}
var err error
// generate missing context-dependent files.
if w . context != nil && file == fmt . Sprintf ( "zgoos_%s.go" , w . context . GOOS ) {
src := fmt . Sprintf ( "package runtime; const theGoos = `%s`" , w . context . GOOS )
f , err = parser . ParseFile ( fset , filename , src , 0 )
2012-01-29 22:04:13 -07:00
if err != nil {
2013-08-08 15:10:59 -06:00
log . Fatalf ( "incorrect generated file: %s" , err )
2012-01-29 22:04:13 -07:00
}
}
2013-08-08 15:10:59 -06:00
if w . context != nil && file == fmt . Sprintf ( "zgoarch_%s.go" , w . context . GOARCH ) {
src := fmt . Sprintf ( "package runtime; const theGoarch = `%s`" , w . context . GOARCH )
f , err = parser . ParseFile ( fset , filename , src , 0 )
if err != nil {
log . Fatalf ( "incorrect generated file: %s" , err )
}
}
2014-07-16 15:16:19 -06:00
if w . context != nil && file == fmt . Sprintf ( "zruntime_defs_%s_%s.go" , w . context . GOOS , w . context . GOARCH ) {
// Just enough to keep the api checker happy.
2014-08-21 11:16:49 -06:00
src := "package runtime; type (" +
" maptype struct{}; _type struct{}; alg struct{};" +
2014-08-27 21:41:10 -06:00
" mspan struct{}; m struct{}; mutex struct{}; slicetype struct{};" +
2014-08-21 11:16:49 -06:00
" iface struct{}; eface struct{}; interfacetype struct{}; itab struct{};" +
" mcache struct{}; bucket struct{}; sudog struct{}; g struct{};" +
2014-08-24 02:31:03 -06:00
" hchan struct{}; chantype struct{}; waitq struct{};" +
2014-08-24 23:59:13 -06:00
" note struct{}; wincallbackcontext struct{};" +
2014-08-28 09:51:09 -06:00
" gobuf struct{}; funcval struct{}; _func struct{};" +
2014-08-24 23:59:13 -06:00
"); " +
"const ( cb_max = 2000 )"
2014-07-16 15:16:19 -06:00
f , err = parser . ParseFile ( fset , filename , src , 0 )
if err != nil {
log . Fatalf ( "incorrect generated file: %s" , err )
}
}
2012-11-19 14:50:20 -07:00
2013-08-08 15:10:59 -06:00
if f == nil {
2012-11-19 14:50:20 -07:00
f , err = parser . ParseFile ( fset , filename , nil , 0 )
if err != nil {
return nil , err
}
}
2013-08-08 15:10:59 -06:00
parsedFileCache [ filename ] = f
return f , nil
2012-11-19 14:50:20 -07:00
}
2013-08-08 15:10:59 -06:00
func contains ( list [ ] string , s string ) bool {
for _ , t := range list {
if t == s {
return true
}
2012-01-29 22:04:13 -07:00
}
2013-08-08 15:10:59 -06:00
return false
}
2013-08-09 16:44:00 -06:00
var (
pkgCache = map [ string ] * types . Package { } // map tagKey to package
pkgTags = map [ string ] [ ] string { } // map import dir to list of relevant tags
)
// tagKey returns the tag-based key to use in the pkgCache.
// It is a comma-separated string; the first part is dir, the rest tags.
// The satisfied tags are derived from context but only those that
// matter (the ones listed in the tags argument) are used.
// The tags list, which came from go/build's Package.AllTags,
// is known to be sorted.
func tagKey ( dir string , context * build . Context , tags [ ] string ) string {
ctags := map [ string ] bool {
context . GOOS : true ,
context . GOARCH : true ,
}
if context . CgoEnabled {
ctags [ "cgo" ] = true
}
for _ , tag := range context . BuildTags {
ctags [ tag ] = true
}
// TODO: ReleaseTags (need to load default)
key := dir
for _ , tag := range tags {
if ctags [ tag ] {
key += "," + tag
}
}
return key
}
2013-08-08 15:10:59 -06:00
// Importing is a sentinel taking the place in Walker.imported
// for a package that is in the process of being imported.
var importing types . Package
func ( w * Walker ) Import ( name string ) ( pkg * types . Package ) {
pkg = w . imported [ name ]
if pkg != nil {
if pkg == & importing {
log . Fatalf ( "cycle importing package %q" , name )
}
return pkg
}
w . imported [ name ] = & importing
// Determine package files.
go/build: replace FindTree, ScanDir, Tree, DirInfo with Import, Package
This is an API change, but one I have been promising would
happen when it was clear what the go command needed.
This is basically a complete replacement of what used to be here.
build.Tree is gone.
build.DirInfo is expanded and now called build.Package.
build.FindTree is now build.Import(package, srcDir, build.FindOnly).
The returned *Package contains information that FindTree returned,
but applicable only to a single package.
build.ScanDir is now build.ImportDir.
build.FindTree+build.ScanDir is now build.Import.
The new Import API allows specifying the source directory,
in order to resolve local imports (import "./foo") and also allows
scanning of packages outside of $GOPATH. They will come back
with less information in the Package, but they will still work.
The old go/build API exposed both too much and too little.
This API is much closer to what the go command needs,
and it works well enough in the other places where it is
used. Path is gone, so it can no longer be misused. (Fixes issue 2749.)
This CL updates clients of go/build other than the go command.
The go command changes are in a separate CL, to be submitted
at the same time.
R=golang-dev, r, alex.brainman, adg
CC=golang-dev
https://golang.org/cl/5713043
2012-03-01 10:12:09 -07:00
dir := filepath . Join ( w . root , filepath . FromSlash ( name ) )
2013-08-08 15:10:59 -06:00
if fi , err := os . Stat ( dir ) ; err != nil || ! fi . IsDir ( ) {
log . Fatalf ( "no source in tree for package %q" , pkg )
}
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
context := w . context
if context == nil {
context = & build . Default
2012-02-07 19:13:11 -07:00
}
2013-08-09 16:44:00 -06:00
// Look in cache.
// If we've already done an import with the same set
// of relevant tags, reuse the result.
var key string
if tags , ok := pkgTags [ dir ] ; ok {
key = tagKey ( dir , context , tags )
if pkg := pkgCache [ key ] ; pkg != nil {
w . imported [ name ] = pkg
return pkg
}
}
2013-08-08 15:10:59 -06:00
info , err := context . ImportDir ( dir , 0 )
2012-01-25 18:47:57 -07:00
if err != nil {
2013-08-08 15:10:59 -06:00
if _ , nogo := err . ( * build . NoGoError ) ; nogo {
2012-02-07 19:13:11 -07:00
return
}
2012-01-25 18:47:57 -07:00
log . Fatalf ( "pkg %q, dir %q: ScanDir: %v" , name , dir , err )
}
2013-08-09 16:44:00 -06:00
// Save tags list first time we see a directory.
if _ , ok := pkgTags [ dir ] ; ! ok {
pkgTags [ dir ] = info . AllTags
key = tagKey ( dir , context , info . AllTags )
}
2013-08-08 15:10:59 -06:00
filenames := append ( append ( [ ] string { } , info . GoFiles ... ) , info . CgoFiles ... )
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
// Certain files only exist when building for the specified context.
// Add them manually.
if name == "runtime" {
n := fmt . Sprintf ( "zgoos_%s.go" , w . context . GOOS )
if ! contains ( filenames , n ) {
filenames = append ( filenames , n )
2012-01-25 18:47:57 -07:00
}
2012-01-29 22:04:13 -07:00
2013-08-08 15:10:59 -06:00
n = fmt . Sprintf ( "zgoarch_%s.go" , w . context . GOARCH )
if ! contains ( filenames , n ) {
filenames = append ( filenames , n )
2012-01-29 22:04:13 -07:00
}
2014-07-16 15:16:19 -06:00
n = fmt . Sprintf ( "zruntime_defs_%s_%s.go" , w . context . GOOS , w . context . GOARCH )
if ! contains ( filenames , n ) {
filenames = append ( filenames , n )
}
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
// Parse package files.
var files [ ] * ast . File
for _ , file := range filenames {
f , err := w . parseFile ( dir , file )
if err != nil {
log . Fatalf ( "error parsing package %s: %s" , name , err )
2012-02-20 23:37:25 -07:00
}
2013-08-08 15:10:59 -06:00
files = append ( files , f )
2012-02-20 23:37:25 -07:00
}
2013-08-08 15:10:59 -06:00
// Type-check package files.
conf := types . Config {
IgnoreFuncBodies : true ,
FakeImportC : true ,
Import : func ( imports map [ string ] * types . Package , name string ) ( * types . Package , error ) {
pkg := w . Import ( name )
imports [ name ] = pkg
return pkg , nil
} ,
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
pkg , err = conf . Check ( name , fset , files , nil )
if err != nil {
ctxt := "<no context>"
if w . context != nil {
ctxt = fmt . Sprintf ( "%s-%s" , w . context . GOOS , w . context . GOARCH )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
log . Fatalf ( "error typechecking package %s: %s (%s)" , name , err , ctxt )
2012-01-25 18:47:57 -07:00
}
2013-08-09 16:44:00 -06:00
pkgCache [ key ] = pkg
2013-08-08 15:10:59 -06:00
w . imported [ name ] = pkg
return
2012-01-25 18:47:57 -07:00
}
// pushScope enters a new scope (walking a package, type, node, etc)
// and returns a function that will leave the scope (with sanity checking
// for mismatched pushes & pops)
func ( w * Walker ) pushScope ( name string ) ( popFunc func ( ) ) {
w . scope = append ( w . scope , name )
return func ( ) {
if len ( w . scope ) == 0 {
log . Fatalf ( "attempt to leave scope %q with empty scope list" , name )
}
if w . scope [ len ( w . scope ) - 1 ] != name {
log . Fatalf ( "attempt to leave scope %q, but scope is currently %#v" , name , w . scope )
}
w . scope = w . scope [ : len ( w . scope ) - 1 ]
}
}
2013-08-08 15:10:59 -06:00
func sortedMethodNames ( typ * types . Interface ) [ ] string {
n := typ . NumMethods ( )
list := make ( [ ] string , n )
for i := range list {
list [ i ] = typ . Method ( i ) . Name ( )
}
sort . Strings ( list )
return list
}
func ( w * Walker ) writeType ( buf * bytes . Buffer , typ types . Type ) {
switch typ := typ . ( type ) {
case * types . Basic :
s := typ . Name ( )
switch typ . Kind ( ) {
case types . UnsafePointer :
s = "unsafe.Pointer"
case types . UntypedBool :
s = "ideal-bool"
case types . UntypedInt :
s = "ideal-int"
case types . UntypedRune :
// "ideal-char" for compatibility with old tool
// TODO(gri) change to "ideal-rune"
s = "ideal-char"
case types . UntypedFloat :
s = "ideal-float"
case types . UntypedComplex :
s = "ideal-complex"
case types . UntypedString :
s = "ideal-string"
case types . UntypedNil :
panic ( "should never see untyped nil type" )
default :
switch s {
case "byte" :
s = "uint8"
case "rune" :
s = "int32"
}
}
buf . WriteString ( s )
case * types . Array :
fmt . Fprintf ( buf , "[%d]" , typ . Len ( ) )
w . writeType ( buf , typ . Elem ( ) )
case * types . Slice :
buf . WriteString ( "[]" )
w . writeType ( buf , typ . Elem ( ) )
case * types . Struct :
buf . WriteString ( "struct" )
case * types . Pointer :
buf . WriteByte ( '*' )
w . writeType ( buf , typ . Elem ( ) )
case * types . Tuple :
panic ( "should never see a tuple type" )
case * types . Signature :
buf . WriteString ( "func" )
w . writeSignature ( buf , typ )
case * types . Interface :
buf . WriteString ( "interface{" )
if typ . NumMethods ( ) > 0 {
buf . WriteByte ( ' ' )
buf . WriteString ( strings . Join ( sortedMethodNames ( typ ) , ", " ) )
buf . WriteByte ( ' ' )
}
buf . WriteString ( "}" )
case * types . Map :
buf . WriteString ( "map[" )
w . writeType ( buf , typ . Key ( ) )
buf . WriteByte ( ']' )
w . writeType ( buf , typ . Elem ( ) )
case * types . Chan :
var s string
switch typ . Dir ( ) {
case ast . SEND :
s = "chan<- "
case ast . RECV :
s = "<-chan "
default :
s = "chan "
2012-01-29 22:04:13 -07:00
}
2013-08-08 15:10:59 -06:00
buf . WriteString ( s )
w . writeType ( buf , typ . Elem ( ) )
2012-01-29 22:04:13 -07:00
2013-08-08 15:10:59 -06:00
case * types . Named :
obj := typ . Obj ( )
pkg := obj . Pkg ( )
if pkg != nil && pkg != w . current {
buf . WriteString ( pkg . Name ( ) )
buf . WriteByte ( '.' )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
buf . WriteString ( typ . Obj ( ) . Name ( ) )
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
default :
panic ( fmt . Sprintf ( "unknown type %T" , typ ) )
}
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) writeSignature ( buf * bytes . Buffer , sig * types . Signature ) {
w . writeParams ( buf , sig . Params ( ) , sig . IsVariadic ( ) )
switch res := sig . Results ( ) ; res . Len ( ) {
case 0 :
// nothing to do
case 1 :
buf . WriteByte ( ' ' )
w . writeType ( buf , res . At ( 0 ) . Type ( ) )
default :
buf . WriteByte ( ' ' )
w . writeParams ( buf , res , false )
}
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) writeParams ( buf * bytes . Buffer , t * types . Tuple , variadic bool ) {
buf . WriteByte ( '(' )
for i , n := 0 , t . Len ( ) ; i < n ; i ++ {
if i > 0 {
buf . WriteString ( ", " )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
typ := t . At ( i ) . Type ( )
if variadic && i + 1 == n {
buf . WriteString ( "..." )
typ = typ . ( * types . Slice ) . Elem ( )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
w . writeType ( buf , typ )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
buf . WriteByte ( ')' )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) typeString ( typ types . Type ) string {
var buf bytes . Buffer
w . writeType ( & buf , typ )
return buf . String ( )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) signatureString ( sig * types . Signature ) string {
var buf bytes . Buffer
w . writeSignature ( & buf , sig )
return buf . String ( )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitObj ( obj types . Object ) {
switch obj := obj . ( type ) {
case * types . Const :
w . emitf ( "const %s %s" , obj . Name ( ) , w . typeString ( obj . Type ( ) ) )
2013-09-06 13:01:01 -06:00
w . emitf ( "const %s = %s" , obj . Name ( ) , obj . Val ( ) )
2013-08-08 15:10:59 -06:00
case * types . Var :
w . emitf ( "var %s %s" , obj . Name ( ) , w . typeString ( obj . Type ( ) ) )
case * types . TypeName :
w . emitType ( obj )
case * types . Func :
w . emitFunc ( obj )
default :
panic ( "unknown object: " + obj . String ( ) )
2012-01-25 18:47:57 -07:00
}
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitType ( obj * types . TypeName ) {
name := obj . Name ( )
typ := obj . Type ( )
switch typ := typ . Underlying ( ) . ( type ) {
case * types . Struct :
w . emitStructType ( name , typ )
case * types . Interface :
w . emitIfaceType ( name , typ )
return // methods are handled by emitIfaceType
default :
w . emitf ( "type %s %s" , name , w . typeString ( typ . Underlying ( ) ) )
}
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
// emit methods with value receiver
var methodNames map [ string ] bool
vset := typ . MethodSet ( )
for i , n := 0 , vset . Len ( ) ; i < n ; i ++ {
m := vset . At ( i )
if m . Obj ( ) . IsExported ( ) {
w . emitMethod ( m )
if methodNames == nil {
methodNames = make ( map [ string ] bool )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
methodNames [ m . Obj ( ) . Name ( ) ] = true
2012-01-25 18:47:57 -07:00
}
}
2012-01-29 22:04:13 -07:00
2013-08-08 15:10:59 -06:00
// emit methods with pointer receiver; exclude
// methods that we have emitted already
// (the method set of *T includes the methods of T)
pset := types . NewPointer ( typ ) . MethodSet ( )
for i , n := 0 , pset . Len ( ) ; i < n ; i ++ {
m := pset . At ( i )
if m . Obj ( ) . IsExported ( ) && ! methodNames [ m . Obj ( ) . Name ( ) ] {
w . emitMethod ( m )
}
2012-01-25 18:47:57 -07:00
}
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitStructType ( name string , typ * types . Struct ) {
2012-01-25 18:47:57 -07:00
typeStruct := fmt . Sprintf ( "type %s struct" , name )
2013-08-08 15:10:59 -06:00
w . emitf ( typeStruct )
defer w . pushScope ( typeStruct ) ( )
for i := 0 ; i < typ . NumFields ( ) ; i ++ {
f := typ . Field ( i )
if ! f . IsExported ( ) {
continue
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
typ := f . Type ( )
if f . Anonymous ( ) {
w . emitf ( "embedded %s" , w . typeString ( typ ) )
continue
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
w . emitf ( "%s %s" , f . Name ( ) , w . typeString ( typ ) )
2012-01-25 18:47:57 -07:00
}
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitIfaceType ( name string , typ * types . Interface ) {
pop := w . pushScope ( "type " + name + " interface" )
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
var methodNames [ ] string
complete := true
mset := typ . MethodSet ( )
for i , n := 0 , mset . Len ( ) ; i < n ; i ++ {
m := mset . At ( i ) . Obj ( ) . ( * types . Func )
if ! m . IsExported ( ) {
complete = false
continue
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
methodNames = append ( methodNames , m . Name ( ) )
w . emitf ( "%s%s" , m . Name ( ) , w . signatureString ( m . Type ( ) . ( * types . Signature ) ) )
2012-01-25 18:47:57 -07:00
}
2012-01-29 22:04:13 -07:00
2012-09-18 13:57:03 -06:00
if ! complete {
// The method set has unexported methods, so all the
// implementations are provided by the same package,
// so the method set can be extended. Instead of recording
// the full set of names (below), record only that there were
// unexported methods. (If the interface shrinks, we will notice
2013-08-08 15:10:59 -06:00
// because a method signature emitted during the last loop
2012-09-18 13:57:03 -06:00
// will disappear.)
2013-08-08 15:10:59 -06:00
w . emitf ( "unexported methods" )
2012-09-18 13:57:03 -06:00
}
2013-08-08 15:10:59 -06:00
2012-01-25 18:47:57 -07:00
pop ( )
2012-09-18 13:57:03 -06:00
if ! complete {
return
}
2013-08-08 15:10:59 -06:00
if len ( methodNames ) == 0 {
w . emitf ( "type %s interface {}" , name )
2012-02-20 23:37:25 -07:00
return
}
2012-01-25 18:47:57 -07:00
2013-08-08 15:10:59 -06:00
sort . Strings ( methodNames )
w . emitf ( "type %s interface { %s }" , name , strings . Join ( methodNames , ", " ) )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitFunc ( f * types . Func ) {
sig := f . Type ( ) . ( * types . Signature )
if sig . Recv ( ) != nil {
panic ( "method considered a regular function: " + f . String ( ) )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
w . emitf ( "func %s%s" , f . Name ( ) , w . signatureString ( sig ) )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitMethod ( m * types . Selection ) {
sig := m . Type ( ) . ( * types . Signature )
recv := sig . Recv ( ) . Type ( )
2014-05-02 14:17:55 -06:00
// report exported methods with unexported receiver base type
2013-08-08 15:10:59 -06:00
if true {
base := recv
if p , _ := recv . ( * types . Pointer ) ; p != nil {
base = p . Elem ( )
}
if obj := base . ( * types . Named ) . Obj ( ) ; ! obj . IsExported ( ) {
log . Fatalf ( "exported method with unexported receiver base type: %s" , m )
2012-01-25 18:47:57 -07:00
}
}
2013-08-08 15:10:59 -06:00
w . emitf ( "method (%s) %s%s" , w . typeString ( recv ) , m . Obj ( ) . Name ( ) , w . signatureString ( sig ) )
2012-01-25 18:47:57 -07:00
}
2013-08-08 15:10:59 -06:00
func ( w * Walker ) emitf ( format string , args ... interface { } ) {
f := strings . Join ( w . scope , ", " ) + ", " + fmt . Sprintf ( format , args ... )
if strings . Contains ( f , "\n" ) {
panic ( "feature contains newlines: " + f )
2012-01-25 18:47:57 -07:00
}
2013-01-28 17:45:45 -07:00
2012-01-25 18:47:57 -07:00
if _ , dup := w . features [ f ] ; dup {
panic ( "duplicate feature inserted: " + f )
}
w . features [ f ] = true
2013-08-08 15:10:59 -06:00
2012-01-25 18:47:57 -07:00
if * verbose {
log . Printf ( "feature: %s" , f )
}
}