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

View as plain text