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