Black Lives Matter. Support the Equal Justice Initiative.

Source file src/go/types/check.go

Documentation: go/types

     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  // This file implements the Check function, which drives type-checking.
     6  
     7  package types
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"go/ast"
    13  	"go/constant"
    14  	"go/token"
    15  )
    16  
    17  // debugging/development support
    18  const (
    19  	debug = false // leave on during development
    20  	trace = false // turn on for detailed type resolution traces
    21  )
    22  
    23  // If forceStrict is set, the type-checker enforces additional
    24  // rules not specified by the Go 1 spec, but which will
    25  // catch guaranteed run-time errors if the respective
    26  // code is executed. In other words, programs passing in
    27  // strict mode are Go 1 compliant, but not all Go 1 programs
    28  // will pass in strict mode. The additional rules are:
    29  //
    30  // - A type assertion x.(T) where T is an interface type
    31  //   is invalid if any (statically known) method that exists
    32  //   for both x and T have different signatures.
    33  //
    34  const forceStrict = false
    35  
    36  // exprInfo stores information about an untyped expression.
    37  type exprInfo struct {
    38  	isLhs bool // expression is lhs operand of a shift with delayed type-check
    39  	mode  operandMode
    40  	typ   *Basic
    41  	val   constant.Value // constant value; or nil (if not a constant)
    42  }
    43  
    44  // A context represents the context within which an object is type-checked.
    45  type context struct {
    46  	decl          *declInfo              // package-level declaration whose init expression/function body is checked
    47  	scope         *Scope                 // top-most scope for lookups
    48  	pos           token.Pos              // if valid, identifiers are looked up as if at position pos (used by Eval)
    49  	iota          constant.Value         // value of iota in a constant declaration; nil otherwise
    50  	errpos        positioner             // if set, identifier position of a constant with inherited initializer
    51  	sig           *Signature             // function signature if inside a function; nil otherwise
    52  	isPanic       map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
    53  	hasLabel      bool                   // set if a function makes use of labels (only ~1% of functions); unused outside functions
    54  	hasCallOrRecv bool                   // set if an expression contains a function call or channel receive operation
    55  }
    56  
    57  // lookup looks up name in the current context and returns the matching object, or nil.
    58  func (ctxt *context) lookup(name string) Object {
    59  	_, obj := ctxt.scope.LookupParent(name, ctxt.pos)
    60  	return obj
    61  }
    62  
    63  // An importKey identifies an imported package by import path and source directory
    64  // (directory containing the file containing the import). In practice, the directory
    65  // may always be the same, or may not matter. Given an (import path, directory), an
    66  // importer must always return the same package (but given two different import paths,
    67  // an importer may still return the same package by mapping them to the same package
    68  // paths).
    69  type importKey struct {
    70  	path, dir string
    71  }
    72  
    73  // A dotImportKey describes a dot-imported object in the given scope.
    74  type dotImportKey struct {
    75  	scope *Scope
    76  	obj   Object
    77  }
    78  
    79  // A Checker maintains the state of the type checker.
    80  // It must be created with NewChecker.
    81  type Checker struct {
    82  	// package information
    83  	// (initialized by NewChecker, valid for the life-time of checker)
    84  	conf *Config
    85  	fset *token.FileSet
    86  	pkg  *Package
    87  	*Info
    88  	version version                    // accepted language version
    89  	objMap  map[Object]*declInfo       // maps package-level objects and (non-interface) methods to declaration info
    90  	impMap  map[importKey]*Package     // maps (import path, source directory) to (complete or fake) package
    91  	posMap  map[*Interface][]token.Pos // maps interface types to lists of embedded interface positions
    92  	typMap  map[string]*Named          // maps an instantiated named type hash to a *Named type
    93  
    94  	// pkgPathMap maps package names to the set of distinct import paths we've
    95  	// seen for that name, anywhere in the import graph. It is used for
    96  	// disambiguating package names in error messages.
    97  	//
    98  	// pkgPathMap is allocated lazily, so that we don't pay the price of building
    99  	// it on the happy path. seenPkgMap tracks the packages that we've already
   100  	// walked.
   101  	pkgPathMap map[string]map[string]bool
   102  	seenPkgMap map[*Package]bool
   103  
   104  	// information collected during type-checking of a set of package files
   105  	// (initialized by Files, valid only for the duration of check.Files;
   106  	// maps and lists are allocated on demand)
   107  	files        []*ast.File               // package files
   108  	imports      []*PkgName                // list of imported packages
   109  	dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
   110  
   111  	firstErr error                 // first error encountered
   112  	methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
   113  	untyped  map[ast.Expr]exprInfo // map of expressions without final type
   114  	delayed  []func()              // stack of delayed action segments; segments are processed in FIFO order
   115  	objPath  []Object              // path of object dependencies during type inference (for cycle reporting)
   116  
   117  	// context within which the current object is type-checked
   118  	// (valid only for the duration of type-checking a specific object)
   119  	context
   120  
   121  	// debugging
   122  	indent int // indentation for tracing
   123  }
   124  
   125  // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
   126  func (check *Checker) addDeclDep(to Object) {
   127  	from := check.decl
   128  	if from == nil {
   129  		return // not in a package-level init expression
   130  	}
   131  	if _, found := check.objMap[to]; !found {
   132  		return // to is not a package-level object
   133  	}
   134  	from.addDep(to)
   135  }
   136  
   137  func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
   138  	m := check.untyped
   139  	if m == nil {
   140  		m = make(map[ast.Expr]exprInfo)
   141  		check.untyped = m
   142  	}
   143  	m[e] = exprInfo{lhs, mode, typ, val}
   144  }
   145  
   146  // later pushes f on to the stack of actions that will be processed later;
   147  // either at the end of the current statement, or in case of a local constant
   148  // or variable declaration, before the constant or variable is in scope
   149  // (so that f still sees the scope before any new declarations).
   150  func (check *Checker) later(f func()) {
   151  	check.delayed = append(check.delayed, f)
   152  }
   153  
   154  // push pushes obj onto the object path and returns its index in the path.
   155  func (check *Checker) push(obj Object) int {
   156  	check.objPath = append(check.objPath, obj)
   157  	return len(check.objPath) - 1
   158  }
   159  
   160  // pop pops and returns the topmost object from the object path.
   161  func (check *Checker) pop() Object {
   162  	i := len(check.objPath) - 1
   163  	obj := check.objPath[i]
   164  	check.objPath[i] = nil
   165  	check.objPath = check.objPath[:i]
   166  	return obj
   167  }
   168  
   169  // NewChecker returns a new Checker instance for a given package.
   170  // Package files may be added incrementally via checker.Files.
   171  func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
   172  	// make sure we have a configuration
   173  	if conf == nil {
   174  		conf = new(Config)
   175  	}
   176  
   177  	// make sure we have an info struct
   178  	if info == nil {
   179  		info = new(Info)
   180  	}
   181  
   182  	version, err := parseGoVersion(conf.goVersion)
   183  	if err != nil {
   184  		panic(fmt.Sprintf("invalid Go version %q (%v)", conf.goVersion, err))
   185  	}
   186  
   187  	return &Checker{
   188  		conf:    conf,
   189  		fset:    fset,
   190  		pkg:     pkg,
   191  		Info:    info,
   192  		version: version,
   193  		objMap:  make(map[Object]*declInfo),
   194  		impMap:  make(map[importKey]*Package),
   195  		posMap:  make(map[*Interface][]token.Pos),
   196  		typMap:  make(map[string]*Named),
   197  	}
   198  }
   199  
   200  // initFiles initializes the files-specific portion of checker.
   201  // The provided files must all belong to the same package.
   202  func (check *Checker) initFiles(files []*ast.File) {
   203  	// start with a clean slate (check.Files may be called multiple times)
   204  	check.files = nil
   205  	check.imports = nil
   206  	check.dotImportMap = nil
   207  
   208  	check.firstErr = nil
   209  	check.methods = nil
   210  	check.untyped = nil
   211  	check.delayed = nil
   212  
   213  	// determine package name and collect valid files
   214  	pkg := check.pkg
   215  	for _, file := range files {
   216  		switch name := file.Name.Name; pkg.name {
   217  		case "":
   218  			if name != "_" {
   219  				pkg.name = name
   220  			} else {
   221  				check.errorf(file.Name, _BlankPkgName, "invalid package name _")
   222  			}
   223  			fallthrough
   224  
   225  		case name:
   226  			check.files = append(check.files, file)
   227  
   228  		default:
   229  			check.errorf(atPos(file.Package), _MismatchedPkgName, "package %s; expected %s", name, pkg.name)
   230  			// ignore this file
   231  		}
   232  	}
   233  }
   234  
   235  // A bailout panic is used for early termination.
   236  type bailout struct{}
   237  
   238  func (check *Checker) handleBailout(err *error) {
   239  	switch p := recover().(type) {
   240  	case nil, bailout:
   241  		// normal return or early exit
   242  		*err = check.firstErr
   243  	default:
   244  		// re-panic
   245  		panic(p)
   246  	}
   247  }
   248  
   249  // Files checks the provided files as part of the checker's package.
   250  func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
   251  
   252  var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
   253  
   254  func (check *Checker) checkFiles(files []*ast.File) (err error) {
   255  	if check.conf.FakeImportC && check.conf.go115UsesCgo {
   256  		return errBadCgo
   257  	}
   258  
   259  	defer check.handleBailout(&err)
   260  
   261  	check.initFiles(files)
   262  
   263  	check.collectObjects()
   264  
   265  	check.packageObjects()
   266  
   267  	check.processDelayed(0) // incl. all functions
   268  
   269  	check.initOrder()
   270  
   271  	if !check.conf.DisableUnusedImportCheck {
   272  		check.unusedImports()
   273  	}
   274  
   275  	check.recordUntyped()
   276  
   277  	if check.Info != nil {
   278  		sanitizeInfo(check.Info)
   279  	}
   280  
   281  	check.pkg.complete = true
   282  
   283  	// no longer needed - release memory
   284  	check.imports = nil
   285  	check.dotImportMap = nil
   286  	check.pkgPathMap = nil
   287  	check.seenPkgMap = nil
   288  
   289  	// TODO(rFindley) There's more memory we should release at this point.
   290  
   291  	return
   292  }
   293  
   294  // processDelayed processes all delayed actions pushed after top.
   295  func (check *Checker) processDelayed(top int) {
   296  	// If each delayed action pushes a new action, the
   297  	// stack will continue to grow during this loop.
   298  	// However, it is only processing functions (which
   299  	// are processed in a delayed fashion) that may
   300  	// add more actions (such as nested functions), so
   301  	// this is a sufficiently bounded process.
   302  	for i := top; i < len(check.delayed); i++ {
   303  		check.delayed[i]() // may append to check.delayed
   304  	}
   305  	assert(top <= len(check.delayed)) // stack must not have shrunk
   306  	check.delayed = check.delayed[:top]
   307  }
   308  
   309  func (check *Checker) record(x *operand) {
   310  	// convert x into a user-friendly set of values
   311  	// TODO(gri) this code can be simplified
   312  	var typ Type
   313  	var val constant.Value
   314  	switch x.mode {
   315  	case invalid:
   316  		typ = Typ[Invalid]
   317  	case novalue:
   318  		typ = (*Tuple)(nil)
   319  	case constant_:
   320  		typ = x.typ
   321  		val = x.val
   322  	default:
   323  		typ = x.typ
   324  	}
   325  	assert(x.expr != nil && typ != nil)
   326  
   327  	if isUntyped(typ) {
   328  		// delay type and value recording until we know the type
   329  		// or until the end of type checking
   330  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   331  	} else {
   332  		check.recordTypeAndValue(x.expr, x.mode, typ, val)
   333  	}
   334  }
   335  
   336  func (check *Checker) recordUntyped() {
   337  	if !debug && check.Types == nil {
   338  		return // nothing to do
   339  	}
   340  
   341  	for x, info := range check.untyped {
   342  		if debug && isTyped(info.typ) {
   343  			check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
   344  			unreachable()
   345  		}
   346  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   347  	}
   348  }
   349  
   350  func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
   351  	assert(x != nil)
   352  	assert(typ != nil)
   353  	if mode == invalid {
   354  		return // omit
   355  	}
   356  	if mode == constant_ {
   357  		assert(val != nil)
   358  		// We check is(typ, IsConstType) here as constant expressions may be
   359  		// recorded as type parameters.
   360  		assert(typ == Typ[Invalid] || is(typ, IsConstType))
   361  	}
   362  	if m := check.Types; m != nil {
   363  		m[x] = TypeAndValue{mode, typ, val}
   364  	}
   365  }
   366  
   367  func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
   368  	// f must be a (possibly parenthesized, possibly qualified)
   369  	// identifier denoting a built-in (including unsafe's non-constant
   370  	// functions Add and Slice): record the signature for f and possible
   371  	// children.
   372  	for {
   373  		check.recordTypeAndValue(f, builtin, sig, nil)
   374  		switch p := f.(type) {
   375  		case *ast.Ident, *ast.SelectorExpr:
   376  			return // we're done
   377  		case *ast.ParenExpr:
   378  			f = p.X
   379  		default:
   380  			unreachable()
   381  		}
   382  	}
   383  }
   384  
   385  func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
   386  	assert(x != nil)
   387  	if a[0] == nil || a[1] == nil {
   388  		return
   389  	}
   390  	assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
   391  	if m := check.Types; m != nil {
   392  		for {
   393  			tv := m[x]
   394  			assert(tv.Type != nil) // should have been recorded already
   395  			pos := x.Pos()
   396  			tv.Type = NewTuple(
   397  				NewVar(pos, check.pkg, "", a[0]),
   398  				NewVar(pos, check.pkg, "", a[1]),
   399  			)
   400  			m[x] = tv
   401  			// if x is a parenthesized expression (p.X), update p.X
   402  			p, _ := x.(*ast.ParenExpr)
   403  			if p == nil {
   404  				break
   405  			}
   406  			x = p.X
   407  		}
   408  	}
   409  }
   410  
   411  func (check *Checker) recordInferred(call ast.Expr, targs []Type, sig *Signature) {
   412  	assert(call != nil)
   413  	assert(sig != nil)
   414  	if m := getInferred(check.Info); m != nil {
   415  		m[call] = _Inferred{targs, sig}
   416  	}
   417  }
   418  
   419  func (check *Checker) recordDef(id *ast.Ident, obj Object) {
   420  	assert(id != nil)
   421  	if m := check.Defs; m != nil {
   422  		m[id] = obj
   423  	}
   424  }
   425  
   426  func (check *Checker) recordUse(id *ast.Ident, obj Object) {
   427  	assert(id != nil)
   428  	assert(obj != nil)
   429  	if m := check.Uses; m != nil {
   430  		m[id] = obj
   431  	}
   432  }
   433  
   434  func (check *Checker) recordImplicit(node ast.Node, obj Object) {
   435  	assert(node != nil)
   436  	assert(obj != nil)
   437  	if m := check.Implicits; m != nil {
   438  		m[node] = obj
   439  	}
   440  }
   441  
   442  func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   443  	assert(obj != nil && (recv == nil || len(index) > 0))
   444  	check.recordUse(x.Sel, obj)
   445  	if m := check.Selections; m != nil {
   446  		m[x] = &Selection{kind, recv, obj, index, indirect}
   447  	}
   448  }
   449  
   450  func (check *Checker) recordScope(node ast.Node, scope *Scope) {
   451  	assert(node != nil)
   452  	assert(scope != nil)
   453  	if m := check.Scopes; m != nil {
   454  		m[node] = scope
   455  	}
   456  }
   457  

View as plain text