...
Run Format

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 object to declaration info
    80  	impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
    81  
    82  	// information collected during type-checking of a set of package files
    83  	// (initialized by Files, valid only for the duration of check.Files;
    84  	// maps and lists are allocated on demand)
    85  	files            []*ast.File                       // package files
    86  	unusedDotImports map[*Scope]map[*Package]token.Pos // positions of unused dot-imported packages for each file scope
    87  
    88  	firstErr   error                    // first error encountered
    89  	methods    map[*TypeName][]*Func    // maps package scope type names to associated non-blank, non-interface methods
    90  	interfaces map[*TypeName]*ifaceInfo // maps interface type names to corresponding interface infos
    91  	untyped    map[ast.Expr]exprInfo    // map of expressions without final type
    92  	delayed    []func()                 // stack of delayed actions
    93  	objPath    []Object                 // path of object dependencies during type inference (for cycle reporting)
    94  
    95  	// context within which the current object is type-checked
    96  	// (valid only for the duration of type-checking a specific object)
    97  	context
    98  
    99  	// debugging
   100  	indent int // indentation for tracing
   101  }
   102  
   103  // addUnusedImport adds the position of a dot-imported package
   104  // pkg to the map of dot imports for the given file scope.
   105  func (check *Checker) addUnusedDotImport(scope *Scope, pkg *Package, pos token.Pos) {
   106  	mm := check.unusedDotImports
   107  	if mm == nil {
   108  		mm = make(map[*Scope]map[*Package]token.Pos)
   109  		check.unusedDotImports = mm
   110  	}
   111  	m := mm[scope]
   112  	if m == nil {
   113  		m = make(map[*Package]token.Pos)
   114  		mm[scope] = m
   115  	}
   116  	m[pkg] = pos
   117  }
   118  
   119  // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
   120  func (check *Checker) addDeclDep(to Object) {
   121  	from := check.decl
   122  	if from == nil {
   123  		return // not in a package-level init expression
   124  	}
   125  	if _, found := check.objMap[to]; !found {
   126  		return // to is not a package-level object
   127  	}
   128  	from.addDep(to)
   129  }
   130  
   131  func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
   132  	m := check.untyped
   133  	if m == nil {
   134  		m = make(map[ast.Expr]exprInfo)
   135  		check.untyped = m
   136  	}
   137  	m[e] = exprInfo{lhs, mode, typ, val}
   138  }
   139  
   140  // later pushes f on to the stack of actions that will be processed later;
   141  // either at the end of the current statement, or in case of a local constant
   142  // or variable declaration, before the constant or variable is in scope
   143  // (so that f still sees the scope before any new declarations).
   144  func (check *Checker) later(f func()) {
   145  	check.delayed = append(check.delayed, f)
   146  }
   147  
   148  // push pushes obj onto the object path and returns its index in the path.
   149  func (check *Checker) push(obj Object) int {
   150  	check.objPath = append(check.objPath, obj)
   151  	return len(check.objPath) - 1
   152  }
   153  
   154  // pop pops and returns the topmost object from the object path.
   155  func (check *Checker) pop() Object {
   156  	i := len(check.objPath) - 1
   157  	obj := check.objPath[i]
   158  	check.objPath[i] = nil
   159  	check.objPath = check.objPath[:i]
   160  	return obj
   161  }
   162  
   163  // pathString returns a string of the form a->b-> ... ->g for an object path [a, b, ... g].
   164  func (check *Checker) pathString() string {
   165  	return objPathString(check.objPath)
   166  }
   167  
   168  // NewChecker returns a new Checker instance for a given package.
   169  // Package files may be added incrementally via checker.Files.
   170  func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
   171  	// make sure we have a configuration
   172  	if conf == nil {
   173  		conf = new(Config)
   174  	}
   175  
   176  	// make sure we have an info struct
   177  	if info == nil {
   178  		info = new(Info)
   179  	}
   180  
   181  	return &Checker{
   182  		conf:   conf,
   183  		fset:   fset,
   184  		pkg:    pkg,
   185  		Info:   info,
   186  		objMap: make(map[Object]*declInfo),
   187  		impMap: make(map[importKey]*Package),
   188  	}
   189  }
   190  
   191  // initFiles initializes the files-specific portion of checker.
   192  // The provided files must all belong to the same package.
   193  func (check *Checker) initFiles(files []*ast.File) {
   194  	// start with a clean slate (check.Files may be called multiple times)
   195  	check.files = nil
   196  	check.unusedDotImports = nil
   197  
   198  	check.firstErr = nil
   199  	check.methods = nil
   200  	check.interfaces = nil
   201  	check.untyped = nil
   202  	check.delayed = nil
   203  
   204  	// determine package name and collect valid files
   205  	pkg := check.pkg
   206  	for _, file := range files {
   207  		switch name := file.Name.Name; pkg.name {
   208  		case "":
   209  			if name != "_" {
   210  				pkg.name = name
   211  			} else {
   212  				check.errorf(file.Name.Pos(), "invalid package name _")
   213  			}
   214  			fallthrough
   215  
   216  		case name:
   217  			check.files = append(check.files, file)
   218  
   219  		default:
   220  			check.errorf(file.Package, "package %s; expected %s", name, pkg.name)
   221  			// ignore this file
   222  		}
   223  	}
   224  }
   225  
   226  // A bailout panic is used for early termination.
   227  type bailout struct{}
   228  
   229  func (check *Checker) handleBailout(err *error) {
   230  	switch p := recover().(type) {
   231  	case nil, bailout:
   232  		// normal return or early exit
   233  		*err = check.firstErr
   234  	default:
   235  		// re-panic
   236  		panic(p)
   237  	}
   238  }
   239  
   240  // Files checks the provided files as part of the checker's package.
   241  func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
   242  
   243  func (check *Checker) checkFiles(files []*ast.File) (err error) {
   244  	defer check.handleBailout(&err)
   245  
   246  	check.initFiles(files)
   247  
   248  	check.collectObjects()
   249  
   250  	check.packageObjects()
   251  
   252  	check.processDelayed(0) // incl. all functions
   253  
   254  	check.initOrder()
   255  
   256  	if !check.conf.DisableUnusedImportCheck {
   257  		check.unusedImports()
   258  	}
   259  
   260  	check.recordUntyped()
   261  
   262  	check.pkg.complete = true
   263  	return
   264  }
   265  
   266  func (check *Checker) recordUntyped() {
   267  	if !debug && check.Types == nil {
   268  		return // nothing to do
   269  	}
   270  
   271  	for x, info := range check.untyped {
   272  		if debug && isTyped(info.typ) {
   273  			check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
   274  			unreachable()
   275  		}
   276  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   277  	}
   278  }
   279  
   280  func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
   281  	assert(x != nil)
   282  	assert(typ != nil)
   283  	if mode == invalid {
   284  		return // omit
   285  	}
   286  	assert(typ != nil)
   287  	if mode == constant_ {
   288  		assert(val != nil)
   289  		assert(typ == Typ[Invalid] || isConstType(typ))
   290  	}
   291  	if m := check.Types; m != nil {
   292  		m[x] = TypeAndValue{mode, typ, val}
   293  	}
   294  }
   295  
   296  func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
   297  	// f must be a (possibly parenthesized) identifier denoting a built-in
   298  	// (built-ins in package unsafe always produce a constant result and
   299  	// we don't record their signatures, so we don't see qualified idents
   300  	// here): record the signature for f and possible children.
   301  	for {
   302  		check.recordTypeAndValue(f, builtin, sig, nil)
   303  		switch p := f.(type) {
   304  		case *ast.Ident:
   305  			return // we're done
   306  		case *ast.ParenExpr:
   307  			f = p.X
   308  		default:
   309  			unreachable()
   310  		}
   311  	}
   312  }
   313  
   314  func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
   315  	assert(x != nil)
   316  	if a[0] == nil || a[1] == nil {
   317  		return
   318  	}
   319  	assert(isTyped(a[0]) && isTyped(a[1]) && isBoolean(a[1]))
   320  	if m := check.Types; m != nil {
   321  		for {
   322  			tv := m[x]
   323  			assert(tv.Type != nil) // should have been recorded already
   324  			pos := x.Pos()
   325  			tv.Type = NewTuple(
   326  				NewVar(pos, check.pkg, "", a[0]),
   327  				NewVar(pos, check.pkg, "", a[1]),
   328  			)
   329  			m[x] = tv
   330  			// if x is a parenthesized expression (p.X), update p.X
   331  			p, _ := x.(*ast.ParenExpr)
   332  			if p == nil {
   333  				break
   334  			}
   335  			x = p.X
   336  		}
   337  	}
   338  }
   339  
   340  func (check *Checker) recordDef(id *ast.Ident, obj Object) {
   341  	assert(id != nil)
   342  	if m := check.Defs; m != nil {
   343  		m[id] = obj
   344  	}
   345  }
   346  
   347  func (check *Checker) recordUse(id *ast.Ident, obj Object) {
   348  	assert(id != nil)
   349  	assert(obj != nil)
   350  	if m := check.Uses; m != nil {
   351  		m[id] = obj
   352  	}
   353  }
   354  
   355  func (check *Checker) recordImplicit(node ast.Node, obj Object) {
   356  	assert(node != nil)
   357  	assert(obj != nil)
   358  	if m := check.Implicits; m != nil {
   359  		m[node] = obj
   360  	}
   361  }
   362  
   363  func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   364  	assert(obj != nil && (recv == nil || len(index) > 0))
   365  	check.recordUse(x.Sel, obj)
   366  	if m := check.Selections; m != nil {
   367  		m[x] = &Selection{kind, recv, obj, index, indirect}
   368  	}
   369  }
   370  
   371  func (check *Checker) recordScope(node ast.Node, scope *Scope) {
   372  	assert(node != nil)
   373  	assert(scope != nil)
   374  	if m := check.Scopes; m != nil {
   375  		m[node] = scope
   376  	}
   377  }
   378  

View as plain text