github.com/lovishpuri/go-40569/src@v0.0.0-20230519171745-f8623e7c56cf/go/types/check.go (about)

     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  	. "internal/types/errors"
    16  )
    17  
    18  // nopos indicates an unknown position
    19  var nopos token.Pos
    20  
    21  // debugging/development support
    22  const debug = false // leave on during development
    23  
    24  // exprInfo stores information about an untyped expression.
    25  type exprInfo struct {
    26  	isLhs bool // expression is lhs operand of a shift with delayed type-check
    27  	mode  operandMode
    28  	typ   *Basic
    29  	val   constant.Value // constant value; or nil (if not a constant)
    30  }
    31  
    32  // An environment represents the environment within which an object is
    33  // type-checked.
    34  type environment struct {
    35  	decl          *declInfo              // package-level declaration whose init expression/function body is checked
    36  	scope         *Scope                 // top-most scope for lookups
    37  	pos           token.Pos              // if valid, identifiers are looked up as if at position pos (used by Eval)
    38  	iota          constant.Value         // value of iota in a constant declaration; nil otherwise
    39  	errpos        positioner             // if set, identifier position of a constant with inherited initializer
    40  	inTParamList  bool                   // set if inside a type parameter list
    41  	sig           *Signature             // function signature if inside a function; nil otherwise
    42  	isPanic       map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
    43  	hasLabel      bool                   // set if a function makes use of labels (only ~1% of functions); unused outside functions
    44  	hasCallOrRecv bool                   // set if an expression contains a function call or channel receive operation
    45  }
    46  
    47  // lookup looks up name in the current environment and returns the matching object, or nil.
    48  func (env *environment) lookup(name string) Object {
    49  	_, obj := env.scope.LookupParent(name, env.pos)
    50  	return obj
    51  }
    52  
    53  // An importKey identifies an imported package by import path and source directory
    54  // (directory containing the file containing the import). In practice, the directory
    55  // may always be the same, or may not matter. Given an (import path, directory), an
    56  // importer must always return the same package (but given two different import paths,
    57  // an importer may still return the same package by mapping them to the same package
    58  // paths).
    59  type importKey struct {
    60  	path, dir string
    61  }
    62  
    63  // A dotImportKey describes a dot-imported object in the given scope.
    64  type dotImportKey struct {
    65  	scope *Scope
    66  	name  string
    67  }
    68  
    69  // An action describes a (delayed) action.
    70  type action struct {
    71  	f    func()      // action to be executed
    72  	desc *actionDesc // action description; may be nil, requires debug to be set
    73  }
    74  
    75  // If debug is set, describef sets a printf-formatted description for action a.
    76  // Otherwise, it is a no-op.
    77  func (a *action) describef(pos positioner, format string, args ...any) {
    78  	if debug {
    79  		a.desc = &actionDesc{pos, format, args}
    80  	}
    81  }
    82  
    83  // An actionDesc provides information on an action.
    84  // For debugging only.
    85  type actionDesc struct {
    86  	pos    positioner
    87  	format string
    88  	args   []any
    89  }
    90  
    91  // A Checker maintains the state of the type checker.
    92  // It must be created with NewChecker.
    93  type Checker struct {
    94  	// package information
    95  	// (initialized by NewChecker, valid for the life-time of checker)
    96  	conf *Config
    97  	ctxt *Context // context for de-duplicating instances
    98  	fset *token.FileSet
    99  	pkg  *Package
   100  	*Info
   101  	version version                // accepted language version
   102  	nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
   103  	objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
   104  	impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
   105  	valids  instanceLookup         // valid *Named (incl. instantiated) types per the validType check
   106  
   107  	// pkgPathMap maps package names to the set of distinct import paths we've
   108  	// seen for that name, anywhere in the import graph. It is used for
   109  	// disambiguating package names in error messages.
   110  	//
   111  	// pkgPathMap is allocated lazily, so that we don't pay the price of building
   112  	// it on the happy path. seenPkgMap tracks the packages that we've already
   113  	// walked.
   114  	pkgPathMap map[string]map[string]bool
   115  	seenPkgMap map[*Package]bool
   116  
   117  	// information collected during type-checking of a set of package files
   118  	// (initialized by Files, valid only for the duration of check.Files;
   119  	// maps and lists are allocated on demand)
   120  	files         []*ast.File               // package files
   121  	posVers       map[*token.File]version   // Pos -> Go version mapping
   122  	imports       []*PkgName                // list of imported packages
   123  	dotImportMap  map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
   124  	recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
   125  	brokenAliases map[*TypeName]bool        // set of aliases with broken (not yet determined) types
   126  	unionTypeSets map[*Union]*_TypeSet      // computed type sets for union types
   127  	mono          monoGraph                 // graph for detecting non-monomorphizable instantiation loops
   128  
   129  	firstErr error                 // first error encountered
   130  	methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
   131  	untyped  map[ast.Expr]exprInfo // map of expressions without final type
   132  	delayed  []action              // stack of delayed action segments; segments are processed in FIFO order
   133  	objPath  []Object              // path of object dependencies during type inference (for cycle reporting)
   134  	cleaners []cleaner             // list of types that may need a final cleanup at the end of type-checking
   135  
   136  	// environment within which the current object is type-checked (valid only
   137  	// for the duration of type-checking a specific object)
   138  	environment
   139  
   140  	// debugging
   141  	indent int // indentation for tracing
   142  }
   143  
   144  // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
   145  func (check *Checker) addDeclDep(to Object) {
   146  	from := check.decl
   147  	if from == nil {
   148  		return // not in a package-level init expression
   149  	}
   150  	if _, found := check.objMap[to]; !found {
   151  		return // to is not a package-level object
   152  	}
   153  	from.addDep(to)
   154  }
   155  
   156  // brokenAlias records that alias doesn't have a determined type yet.
   157  // It also sets alias.typ to Typ[Invalid].
   158  func (check *Checker) brokenAlias(alias *TypeName) {
   159  	if check.brokenAliases == nil {
   160  		check.brokenAliases = make(map[*TypeName]bool)
   161  	}
   162  	check.brokenAliases[alias] = true
   163  	alias.typ = Typ[Invalid]
   164  }
   165  
   166  // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
   167  func (check *Checker) validAlias(alias *TypeName, typ Type) {
   168  	delete(check.brokenAliases, alias)
   169  	alias.typ = typ
   170  }
   171  
   172  // isBrokenAlias reports whether alias doesn't have a determined type yet.
   173  func (check *Checker) isBrokenAlias(alias *TypeName) bool {
   174  	return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
   175  }
   176  
   177  func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
   178  	m := check.untyped
   179  	if m == nil {
   180  		m = make(map[ast.Expr]exprInfo)
   181  		check.untyped = m
   182  	}
   183  	m[e] = exprInfo{lhs, mode, typ, val}
   184  }
   185  
   186  // later pushes f on to the stack of actions that will be processed later;
   187  // either at the end of the current statement, or in case of a local constant
   188  // or variable declaration, before the constant or variable is in scope
   189  // (so that f still sees the scope before any new declarations).
   190  // later returns the pushed action so one can provide a description
   191  // via action.describef for debugging, if desired.
   192  func (check *Checker) later(f func()) *action {
   193  	i := len(check.delayed)
   194  	check.delayed = append(check.delayed, action{f: f})
   195  	return &check.delayed[i]
   196  }
   197  
   198  // push pushes obj onto the object path and returns its index in the path.
   199  func (check *Checker) push(obj Object) int {
   200  	check.objPath = append(check.objPath, obj)
   201  	return len(check.objPath) - 1
   202  }
   203  
   204  // pop pops and returns the topmost object from the object path.
   205  func (check *Checker) pop() Object {
   206  	i := len(check.objPath) - 1
   207  	obj := check.objPath[i]
   208  	check.objPath[i] = nil
   209  	check.objPath = check.objPath[:i]
   210  	return obj
   211  }
   212  
   213  type cleaner interface {
   214  	cleanup()
   215  }
   216  
   217  // needsCleanup records objects/types that implement the cleanup method
   218  // which will be called at the end of type-checking.
   219  func (check *Checker) needsCleanup(c cleaner) {
   220  	check.cleaners = append(check.cleaners, c)
   221  }
   222  
   223  // NewChecker returns a new Checker instance for a given package.
   224  // Package files may be added incrementally via checker.Files.
   225  func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
   226  	// make sure we have a configuration
   227  	if conf == nil {
   228  		conf = new(Config)
   229  	}
   230  
   231  	// make sure we have an info struct
   232  	if info == nil {
   233  		info = new(Info)
   234  	}
   235  
   236  	version, err := parseGoVersion(conf.GoVersion)
   237  	if err != nil {
   238  		panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
   239  	}
   240  
   241  	return &Checker{
   242  		conf:    conf,
   243  		ctxt:    conf.Context,
   244  		fset:    fset,
   245  		pkg:     pkg,
   246  		Info:    info,
   247  		version: version,
   248  		objMap:  make(map[Object]*declInfo),
   249  		impMap:  make(map[importKey]*Package),
   250  	}
   251  }
   252  
   253  // initFiles initializes the files-specific portion of checker.
   254  // The provided files must all belong to the same package.
   255  func (check *Checker) initFiles(files []*ast.File) {
   256  	// start with a clean slate (check.Files may be called multiple times)
   257  	check.files = nil
   258  	check.imports = nil
   259  	check.dotImportMap = nil
   260  
   261  	check.firstErr = nil
   262  	check.methods = nil
   263  	check.untyped = nil
   264  	check.delayed = nil
   265  	check.objPath = nil
   266  	check.cleaners = nil
   267  
   268  	// determine package name and collect valid files
   269  	pkg := check.pkg
   270  	for _, file := range files {
   271  		switch name := file.Name.Name; pkg.name {
   272  		case "":
   273  			if name != "_" {
   274  				pkg.name = name
   275  			} else {
   276  				check.error(file.Name, BlankPkgName, "invalid package name _")
   277  			}
   278  			fallthrough
   279  
   280  		case name:
   281  			check.files = append(check.files, file)
   282  
   283  		default:
   284  			check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
   285  			// ignore this file
   286  		}
   287  	}
   288  
   289  	for _, file := range check.files {
   290  		v, _ := parseGoVersion(file.GoVersion)
   291  		if v.major > 0 {
   292  			if v.equal(check.version) {
   293  				continue
   294  			}
   295  			// Go 1.21 introduced the feature of setting the go.mod
   296  			// go line to an early version of Go and allowing //go:build lines
   297  			// to “upgrade” the Go version in a given file.
   298  			// We can do that backwards compatibly.
   299  			// Go 1.21 also introduced the feature of allowing //go:build lines
   300  			// to “downgrade” the Go version in a given file.
   301  			// That can't be done compatibly in general, since before the
   302  			// build lines were ignored and code got the module's Go version.
   303  			// To work around this, downgrades are only allowed when the
   304  			// module's Go version is Go 1.21 or later.
   305  			// If there is no check.version, then we don't really know what Go version to apply.
   306  			// Legacy tools may do this, and they historically have accepted everything.
   307  			// Preserve that behavior by ignoring //go:build constraints entirely in that case.
   308  			if (v.before(check.version) && check.version.before(version{1, 21})) || check.version.equal(version{0, 0}) {
   309  				continue
   310  			}
   311  			if check.posVers == nil {
   312  				check.posVers = make(map[*token.File]version)
   313  			}
   314  			check.posVers[check.fset.File(file.FileStart)] = v
   315  		}
   316  	}
   317  }
   318  
   319  // A posVers records that the file starting at pos declares the Go version vers.
   320  type posVers struct {
   321  	pos  token.Pos
   322  	vers version
   323  }
   324  
   325  // A bailout panic is used for early termination.
   326  type bailout struct{}
   327  
   328  func (check *Checker) handleBailout(err *error) {
   329  	switch p := recover().(type) {
   330  	case nil, bailout:
   331  		// normal return or early exit
   332  		*err = check.firstErr
   333  	default:
   334  		// re-panic
   335  		panic(p)
   336  	}
   337  }
   338  
   339  // Files checks the provided files as part of the checker's package.
   340  func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
   341  
   342  var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
   343  
   344  func (check *Checker) checkFiles(files []*ast.File) (err error) {
   345  	if check.conf.FakeImportC && check.conf.go115UsesCgo {
   346  		return errBadCgo
   347  	}
   348  
   349  	defer check.handleBailout(&err)
   350  
   351  	print := func(msg string) {
   352  		if check.conf._Trace {
   353  			fmt.Println()
   354  			fmt.Println(msg)
   355  		}
   356  	}
   357  
   358  	print("== initFiles ==")
   359  	check.initFiles(files)
   360  
   361  	print("== collectObjects ==")
   362  	check.collectObjects()
   363  
   364  	print("== packageObjects ==")
   365  	check.packageObjects()
   366  
   367  	print("== processDelayed ==")
   368  	check.processDelayed(0) // incl. all functions
   369  
   370  	print("== cleanup ==")
   371  	check.cleanup()
   372  
   373  	print("== initOrder ==")
   374  	check.initOrder()
   375  
   376  	if !check.conf.DisableUnusedImportCheck {
   377  		print("== unusedImports ==")
   378  		check.unusedImports()
   379  	}
   380  
   381  	print("== recordUntyped ==")
   382  	check.recordUntyped()
   383  
   384  	if check.firstErr == nil {
   385  		// TODO(mdempsky): Ensure monomorph is safe when errors exist.
   386  		check.monomorph()
   387  	}
   388  
   389  	check.pkg.complete = true
   390  
   391  	// no longer needed - release memory
   392  	check.imports = nil
   393  	check.dotImportMap = nil
   394  	check.pkgPathMap = nil
   395  	check.seenPkgMap = nil
   396  	check.recvTParamMap = nil
   397  	check.brokenAliases = nil
   398  	check.unionTypeSets = nil
   399  	check.ctxt = nil
   400  
   401  	// TODO(rFindley) There's more memory we should release at this point.
   402  
   403  	return
   404  }
   405  
   406  // processDelayed processes all delayed actions pushed after top.
   407  func (check *Checker) processDelayed(top int) {
   408  	// If each delayed action pushes a new action, the
   409  	// stack will continue to grow during this loop.
   410  	// However, it is only processing functions (which
   411  	// are processed in a delayed fashion) that may
   412  	// add more actions (such as nested functions), so
   413  	// this is a sufficiently bounded process.
   414  	for i := top; i < len(check.delayed); i++ {
   415  		a := &check.delayed[i]
   416  		if check.conf._Trace {
   417  			if a.desc != nil {
   418  				check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
   419  			} else {
   420  				check.trace(nopos, "-- delayed %p", a.f)
   421  			}
   422  		}
   423  		a.f() // may append to check.delayed
   424  		if check.conf._Trace {
   425  			fmt.Println()
   426  		}
   427  	}
   428  	assert(top <= len(check.delayed)) // stack must not have shrunk
   429  	check.delayed = check.delayed[:top]
   430  }
   431  
   432  // cleanup runs cleanup for all collected cleaners.
   433  func (check *Checker) cleanup() {
   434  	// Don't use a range clause since Named.cleanup may add more cleaners.
   435  	for i := 0; i < len(check.cleaners); i++ {
   436  		check.cleaners[i].cleanup()
   437  	}
   438  	check.cleaners = nil
   439  }
   440  
   441  func (check *Checker) record(x *operand) {
   442  	// convert x into a user-friendly set of values
   443  	// TODO(gri) this code can be simplified
   444  	var typ Type
   445  	var val constant.Value
   446  	switch x.mode {
   447  	case invalid:
   448  		typ = Typ[Invalid]
   449  	case novalue:
   450  		typ = (*Tuple)(nil)
   451  	case constant_:
   452  		typ = x.typ
   453  		val = x.val
   454  	default:
   455  		typ = x.typ
   456  	}
   457  	assert(x.expr != nil && typ != nil)
   458  
   459  	if isUntyped(typ) {
   460  		// delay type and value recording until we know the type
   461  		// or until the end of type checking
   462  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   463  	} else {
   464  		check.recordTypeAndValue(x.expr, x.mode, typ, val)
   465  	}
   466  }
   467  
   468  func (check *Checker) recordUntyped() {
   469  	if !debug && check.Types == nil {
   470  		return // nothing to do
   471  	}
   472  
   473  	for x, info := range check.untyped {
   474  		if debug && isTyped(info.typ) {
   475  			check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
   476  			unreachable()
   477  		}
   478  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   479  	}
   480  }
   481  
   482  func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
   483  	assert(x != nil)
   484  	assert(typ != nil)
   485  	if mode == invalid {
   486  		return // omit
   487  	}
   488  	if mode == constant_ {
   489  		assert(val != nil)
   490  		// We check allBasic(typ, IsConstType) here as constant expressions may be
   491  		// recorded as type parameters.
   492  		assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
   493  	}
   494  	if m := check.Types; m != nil {
   495  		m[x] = TypeAndValue{mode, typ, val}
   496  	}
   497  }
   498  
   499  func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
   500  	// f must be a (possibly parenthesized, possibly qualified)
   501  	// identifier denoting a built-in (including unsafe's non-constant
   502  	// functions Add and Slice): record the signature for f and possible
   503  	// children.
   504  	for {
   505  		check.recordTypeAndValue(f, builtin, sig, nil)
   506  		switch p := f.(type) {
   507  		case *ast.Ident, *ast.SelectorExpr:
   508  			return // we're done
   509  		case *ast.ParenExpr:
   510  			f = p.X
   511  		default:
   512  			unreachable()
   513  		}
   514  	}
   515  }
   516  
   517  // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
   518  // (and therefore has tuple type).
   519  func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
   520  	assert(x != nil)
   521  	assert(len(a) == 2)
   522  	if a[0].mode == invalid {
   523  		return
   524  	}
   525  	t0, t1 := a[0].typ, a[1].typ
   526  	assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
   527  	if m := check.Types; m != nil {
   528  		for {
   529  			tv := m[x]
   530  			assert(tv.Type != nil) // should have been recorded already
   531  			pos := x.Pos()
   532  			tv.Type = NewTuple(
   533  				NewVar(pos, check.pkg, "", t0),
   534  				NewVar(pos, check.pkg, "", t1),
   535  			)
   536  			m[x] = tv
   537  			// if x is a parenthesized expression (p.X), update p.X
   538  			p, _ := x.(*ast.ParenExpr)
   539  			if p == nil {
   540  				break
   541  			}
   542  			x = p.X
   543  		}
   544  	}
   545  }
   546  
   547  // recordInstance records instantiation information into check.Info, if the
   548  // Instances map is non-nil. The given expr must be an ident, selector, or
   549  // index (list) expr with ident or selector operand.
   550  //
   551  // TODO(rfindley): the expr parameter is fragile. See if we can access the
   552  // instantiated identifier in some other way.
   553  func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
   554  	ident := instantiatedIdent(expr)
   555  	assert(ident != nil)
   556  	assert(typ != nil)
   557  	if m := check.Instances; m != nil {
   558  		m[ident] = Instance{newTypeList(targs), typ}
   559  	}
   560  }
   561  
   562  func instantiatedIdent(expr ast.Expr) *ast.Ident {
   563  	var selOrIdent ast.Expr
   564  	switch e := expr.(type) {
   565  	case *ast.IndexExpr:
   566  		selOrIdent = e.X
   567  	case *ast.IndexListExpr:
   568  		selOrIdent = e.X
   569  	case *ast.SelectorExpr, *ast.Ident:
   570  		selOrIdent = e
   571  	}
   572  	switch x := selOrIdent.(type) {
   573  	case *ast.Ident:
   574  		return x
   575  	case *ast.SelectorExpr:
   576  		return x.Sel
   577  	}
   578  	panic("instantiated ident not found")
   579  }
   580  
   581  func (check *Checker) recordDef(id *ast.Ident, obj Object) {
   582  	assert(id != nil)
   583  	if m := check.Defs; m != nil {
   584  		m[id] = obj
   585  	}
   586  }
   587  
   588  func (check *Checker) recordUse(id *ast.Ident, obj Object) {
   589  	assert(id != nil)
   590  	assert(obj != nil)
   591  	if m := check.Uses; m != nil {
   592  		m[id] = obj
   593  	}
   594  }
   595  
   596  func (check *Checker) recordImplicit(node ast.Node, obj Object) {
   597  	assert(node != nil)
   598  	assert(obj != nil)
   599  	if m := check.Implicits; m != nil {
   600  		m[node] = obj
   601  	}
   602  }
   603  
   604  func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   605  	assert(obj != nil && (recv == nil || len(index) > 0))
   606  	check.recordUse(x.Sel, obj)
   607  	if m := check.Selections; m != nil {
   608  		m[x] = &Selection{kind, recv, obj, index, indirect}
   609  	}
   610  }
   611  
   612  func (check *Checker) recordScope(node ast.Node, scope *Scope) {
   613  	assert(node != nil)
   614  	assert(scope != nil)
   615  	if m := check.Scopes; m != nil {
   616  		m[node] = scope
   617  	}
   618  }