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

View as plain text