github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/cmd/vet/types.go (about)

     1  // Copyright 2010 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  // This file contains the pieces of the tool that use typechecking from the go/types package.
     6  
     7  package main
     8  
     9  import (
    10  	"go/ast"
    11  	"go/build"
    12  	"go/importer"
    13  	"go/token"
    14  	"go/types"
    15  )
    16  
    17  // stdImporter is the importer we use to import packages.
    18  // It is shared so that all packages are imported by the same importer.
    19  var stdImporter types.Importer
    20  
    21  var (
    22  	errorType        *types.Interface
    23  	stringerType     *types.Interface // possibly nil
    24  	formatterType    *types.Interface // possibly nil
    25  	httpResponseType types.Type       // possibly nil
    26  	httpClientType   types.Type       // possibly nil
    27  )
    28  
    29  func inittypes() {
    30  	errorType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
    31  
    32  	if typ := importType("fmt", "Stringer"); typ != nil {
    33  		stringerType = typ.Underlying().(*types.Interface)
    34  	}
    35  	if typ := importType("fmt", "Formatter"); typ != nil {
    36  		formatterType = typ.Underlying().(*types.Interface)
    37  	}
    38  	if typ := importType("net/http", "Response"); typ != nil {
    39  		httpResponseType = typ
    40  	}
    41  	if typ := importType("net/http", "Client"); typ != nil {
    42  		httpClientType = typ
    43  	}
    44  }
    45  
    46  // importType returns the type denoted by the qualified identifier
    47  // path.name, and adds the respective package to the imports map
    48  // as a side effect. In case of an error, importType returns nil.
    49  func importType(path, name string) types.Type {
    50  	pkg, err := stdImporter.Import(path)
    51  	if err != nil {
    52  		// This can happen if the package at path hasn't been compiled yet.
    53  		warnf("import failed: %v", err)
    54  		return nil
    55  	}
    56  	if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {
    57  		return obj.Type()
    58  	}
    59  	warnf("invalid type name %q", name)
    60  	return nil
    61  }
    62  
    63  func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) error {
    64  	if stdImporter == nil {
    65  		if *source {
    66  			stdImporter = importer.For("source", nil)
    67  		} else {
    68  			stdImporter = importer.Default()
    69  		}
    70  		inittypes()
    71  	}
    72  	pkg.defs = make(map[*ast.Ident]types.Object)
    73  	pkg.uses = make(map[*ast.Ident]types.Object)
    74  	pkg.selectors = make(map[*ast.SelectorExpr]*types.Selection)
    75  	pkg.spans = make(map[types.Object]Span)
    76  	pkg.types = make(map[ast.Expr]types.TypeAndValue)
    77  	config := types.Config{
    78  		// We use the same importer for all imports to ensure that
    79  		// everybody sees identical packages for the given paths.
    80  		Importer: stdImporter,
    81  		// By providing a Config with our own error function, it will continue
    82  		// past the first error. There is no need for that function to do anything.
    83  		Error: func(error) {},
    84  
    85  		Sizes: archSizes,
    86  	}
    87  	info := &types.Info{
    88  		Selections: pkg.selectors,
    89  		Types:      pkg.types,
    90  		Defs:       pkg.defs,
    91  		Uses:       pkg.uses,
    92  	}
    93  	typesPkg, err := config.Check(pkg.path, fs, astFiles, info)
    94  	pkg.typesPkg = typesPkg
    95  	// update spans
    96  	for id, obj := range pkg.defs {
    97  		pkg.growSpan(id, obj)
    98  	}
    99  	for id, obj := range pkg.uses {
   100  		pkg.growSpan(id, obj)
   101  	}
   102  	return err
   103  }
   104  
   105  // matchArgType reports an error if printf verb t is not appropriate
   106  // for operand arg.
   107  //
   108  // typ is used only for recursive calls; external callers must supply nil.
   109  //
   110  // (Recursion arises from the compound types {map,chan,slice} which
   111  // may be printed with %d etc. if that is appropriate for their element
   112  // types.)
   113  func (f *File) matchArgType(t printfArgType, typ types.Type, arg ast.Expr) bool {
   114  	return f.matchArgTypeInternal(t, typ, arg, make(map[types.Type]bool))
   115  }
   116  
   117  // matchArgTypeInternal is the internal version of matchArgType. It carries a map
   118  // remembering what types are in progress so we don't recur when faced with recursive
   119  // types or mutually recursive types.
   120  func (f *File) matchArgTypeInternal(t printfArgType, typ types.Type, arg ast.Expr, inProgress map[types.Type]bool) bool {
   121  	// %v, %T accept any argument type.
   122  	if t == anyType {
   123  		return true
   124  	}
   125  	if typ == nil {
   126  		// external call
   127  		typ = f.pkg.types[arg].Type
   128  		if typ == nil {
   129  			return true // probably a type check problem
   130  		}
   131  	}
   132  	// If the type implements fmt.Formatter, we have nothing to check.
   133  	if f.isFormatter(typ) {
   134  		return true
   135  	}
   136  	// If we can use a string, might arg (dynamically) implement the Stringer or Error interface?
   137  	if t&argString != 0 {
   138  		if types.AssertableTo(errorType, typ) || stringerType != nil && types.AssertableTo(stringerType, typ) {
   139  			return true
   140  		}
   141  	}
   142  
   143  	typ = typ.Underlying()
   144  	if inProgress[typ] {
   145  		// We're already looking at this type. The call that started it will take care of it.
   146  		return true
   147  	}
   148  	inProgress[typ] = true
   149  
   150  	switch typ := typ.(type) {
   151  	case *types.Signature:
   152  		return t&argPointer != 0
   153  
   154  	case *types.Map:
   155  		// Recur: map[int]int matches %d.
   156  		return t&argPointer != 0 ||
   157  			(f.matchArgTypeInternal(t, typ.Key(), arg, inProgress) && f.matchArgTypeInternal(t, typ.Elem(), arg, inProgress))
   158  
   159  	case *types.Chan:
   160  		return t&argPointer != 0
   161  
   162  	case *types.Array:
   163  		// Same as slice.
   164  		if types.Identical(typ.Elem().Underlying(), types.Typ[types.Byte]) && t&argString != 0 {
   165  			return true // %s matches []byte
   166  		}
   167  		// Recur: []int matches %d.
   168  		return t&argPointer != 0 || f.matchArgTypeInternal(t, typ.Elem().Underlying(), arg, inProgress)
   169  
   170  	case *types.Slice:
   171  		// Same as array.
   172  		if types.Identical(typ.Elem().Underlying(), types.Typ[types.Byte]) && t&argString != 0 {
   173  			return true // %s matches []byte
   174  		}
   175  		// Recur: []int matches %d. But watch out for
   176  		//	type T []T
   177  		// If the element is a pointer type (type T[]*T), it's handled fine by the Pointer case below.
   178  		return t&argPointer != 0 || f.matchArgTypeInternal(t, typ.Elem(), arg, inProgress)
   179  
   180  	case *types.Pointer:
   181  		// Ugly, but dealing with an edge case: a known pointer to an invalid type,
   182  		// probably something from a failed import.
   183  		if typ.Elem().String() == "invalid type" {
   184  			if *verbose {
   185  				f.Warnf(arg.Pos(), "printf argument %v is pointer to invalid or unknown type", f.gofmt(arg))
   186  			}
   187  			return true // special case
   188  		}
   189  		// If it's actually a pointer with %p, it prints as one.
   190  		if t == argPointer {
   191  			return true
   192  		}
   193  		// If it's pointer to struct, that's equivalent in our analysis to whether we can print the struct.
   194  		if str, ok := typ.Elem().Underlying().(*types.Struct); ok {
   195  			return f.matchStructArgType(t, str, arg, inProgress)
   196  		}
   197  		// The rest can print with %p as pointers, or as integers with %x etc.
   198  		return t&(argInt|argPointer) != 0
   199  
   200  	case *types.Struct:
   201  		return f.matchStructArgType(t, typ, arg, inProgress)
   202  
   203  	case *types.Interface:
   204  		// There's little we can do.
   205  		// Whether any particular verb is valid depends on the argument.
   206  		// The user may have reasonable prior knowledge of the contents of the interface.
   207  		return true
   208  
   209  	case *types.Basic:
   210  		switch typ.Kind() {
   211  		case types.UntypedBool,
   212  			types.Bool:
   213  			return t&argBool != 0
   214  
   215  		case types.UntypedInt,
   216  			types.Int,
   217  			types.Int8,
   218  			types.Int16,
   219  			types.Int32,
   220  			types.Int64,
   221  			types.Uint,
   222  			types.Uint8,
   223  			types.Uint16,
   224  			types.Uint32,
   225  			types.Uint64,
   226  			types.Uintptr:
   227  			return t&argInt != 0
   228  
   229  		case types.UntypedFloat,
   230  			types.Float32,
   231  			types.Float64:
   232  			return t&argFloat != 0
   233  
   234  		case types.UntypedComplex,
   235  			types.Complex64,
   236  			types.Complex128:
   237  			return t&argComplex != 0
   238  
   239  		case types.UntypedString,
   240  			types.String:
   241  			return t&argString != 0
   242  
   243  		case types.UnsafePointer:
   244  			return t&(argPointer|argInt) != 0
   245  
   246  		case types.UntypedRune:
   247  			return t&(argInt|argRune) != 0
   248  
   249  		case types.UntypedNil:
   250  			return t&argPointer != 0 // TODO?
   251  
   252  		case types.Invalid:
   253  			if *verbose {
   254  				f.Warnf(arg.Pos(), "printf argument %v has invalid or unknown type", f.gofmt(arg))
   255  			}
   256  			return true // Probably a type check problem.
   257  		}
   258  		panic("unreachable")
   259  	}
   260  
   261  	return false
   262  }
   263  
   264  // hasBasicType reports whether x's type is a types.Basic with the given kind.
   265  func (f *File) hasBasicType(x ast.Expr, kind types.BasicKind) bool {
   266  	t := f.pkg.types[x].Type
   267  	if t != nil {
   268  		t = t.Underlying()
   269  	}
   270  	b, ok := t.(*types.Basic)
   271  	return ok && b.Kind() == kind
   272  }
   273  
   274  // matchStructArgType reports whether all the elements of the struct match the expected
   275  // type. For instance, with "%d" all the elements must be printable with the "%d" format.
   276  func (f *File) matchStructArgType(t printfArgType, typ *types.Struct, arg ast.Expr, inProgress map[types.Type]bool) bool {
   277  	for i := 0; i < typ.NumFields(); i++ {
   278  		if !f.matchArgTypeInternal(t, typ.Field(i).Type(), arg, inProgress) {
   279  			return false
   280  		}
   281  	}
   282  	return true
   283  }
   284  
   285  // hasMethod reports whether the type contains a method with the given name.
   286  // It is part of the workaround for Formatters and should be deleted when
   287  // that workaround is no longer necessary.
   288  // TODO: This could be better once issue 6259 is fixed.
   289  func (f *File) hasMethod(typ types.Type, name string) bool {
   290  	// assume we have an addressable variable of type typ
   291  	obj, _, _ := types.LookupFieldOrMethod(typ, true, f.pkg.typesPkg, name)
   292  	_, ok := obj.(*types.Func)
   293  	return ok
   294  }
   295  
   296  var archSizes = types.SizesFor("gc", build.Default.GOARCH)