Source file src/go/types/check.go

     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  	"fmt"
    11  	"go/ast"
    12  	"go/constant"
    13  	"go/token"
    14  	"internal/godebug"
    15  	. "internal/types/errors"
    16  	"strings"
    17  	"sync/atomic"
    18  )
    19  
    20  // nopos, noposn indicate an unknown position
    21  var nopos token.Pos
    22  var noposn = atPos(nopos)
    23  
    24  // debugging/development support
    25  const debug = false // leave on during development
    26  
    27  // gotypesalias controls the use of Alias types.
    28  // As of Apr 16 2024 they are used by default.
    29  // To disable their use, set GODEBUG to gotypesalias=0.
    30  // This GODEBUG flag will be removed in the near future (tentatively Go 1.24).
    31  var gotypesalias = godebug.New("gotypesalias")
    32  
    33  // _aliasAny changes the behavior of [Scope.Lookup] for "any" in the
    34  // [Universe] scope.
    35  //
    36  // This is necessary because while Alias creation is controlled by
    37  // [Config._EnableAlias], based on the gotypealias variable, the representation
    38  // of "any" is a global. In [Scope.Lookup], we select this global
    39  // representation based on the result of [aliasAny], but as a result need to
    40  // guard against this behavior changing during the type checking pass.
    41  // Therefore we implement the following rule: any number of goroutines can type
    42  // check concurrently with the same EnableAlias value, but if any goroutine
    43  // tries to type check concurrently with a different EnableAlias value, we
    44  // panic.
    45  //
    46  // To achieve this, _aliasAny is a state machine:
    47  //
    48  //	0:        no type checking is occurring
    49  //	negative: type checking is occurring without _EnableAlias set
    50  //	positive: type checking is occurring with _EnableAlias set
    51  var _aliasAny int32
    52  
    53  func aliasAny() bool {
    54  	v := gotypesalias.Value()
    55  	useAlias := v != "0"
    56  	inuse := atomic.LoadInt32(&_aliasAny)
    57  	if inuse != 0 && useAlias != (inuse > 0) {
    58  		panic(fmt.Sprintf("gotypealias mutated during type checking, gotypesalias=%s, inuse=%d", v, inuse))
    59  	}
    60  	return useAlias
    61  }
    62  
    63  // exprInfo stores information about an untyped expression.
    64  type exprInfo struct {
    65  	isLhs bool // expression is lhs operand of a shift with delayed type-check
    66  	mode  operandMode
    67  	typ   *Basic
    68  	val   constant.Value // constant value; or nil (if not a constant)
    69  }
    70  
    71  // An environment represents the environment within which an object is
    72  // type-checked.
    73  type environment struct {
    74  	decl          *declInfo              // package-level declaration whose init expression/function body is checked
    75  	scope         *Scope                 // top-most scope for lookups
    76  	pos           token.Pos              // if valid, identifiers are looked up as if at position pos (used by Eval)
    77  	iota          constant.Value         // value of iota in a constant declaration; nil otherwise
    78  	errpos        positioner             // if set, identifier position of a constant with inherited initializer
    79  	inTParamList  bool                   // set if inside a type parameter list
    80  	sig           *Signature             // function signature if inside a function; nil otherwise
    81  	isPanic       map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
    82  	hasLabel      bool                   // set if a function makes use of labels (only ~1% of functions); unused outside functions
    83  	hasCallOrRecv bool                   // set if an expression contains a function call or channel receive operation
    84  }
    85  
    86  // lookup looks up name in the current environment and returns the matching object, or nil.
    87  func (env *environment) lookup(name string) Object {
    88  	_, obj := env.scope.LookupParent(name, env.pos)
    89  	return obj
    90  }
    91  
    92  // An importKey identifies an imported package by import path and source directory
    93  // (directory containing the file containing the import). In practice, the directory
    94  // may always be the same, or may not matter. Given an (import path, directory), an
    95  // importer must always return the same package (but given two different import paths,
    96  // an importer may still return the same package by mapping them to the same package
    97  // paths).
    98  type importKey struct {
    99  	path, dir string
   100  }
   101  
   102  // A dotImportKey describes a dot-imported object in the given scope.
   103  type dotImportKey struct {
   104  	scope *Scope
   105  	name  string
   106  }
   107  
   108  // An action describes a (delayed) action.
   109  type action struct {
   110  	f    func()      // action to be executed
   111  	desc *actionDesc // action description; may be nil, requires debug to be set
   112  }
   113  
   114  // If debug is set, describef sets a printf-formatted description for action a.
   115  // Otherwise, it is a no-op.
   116  func (a *action) describef(pos positioner, format string, args ...any) {
   117  	if debug {
   118  		a.desc = &actionDesc{pos, format, args}
   119  	}
   120  }
   121  
   122  // An actionDesc provides information on an action.
   123  // For debugging only.
   124  type actionDesc struct {
   125  	pos    positioner
   126  	format string
   127  	args   []any
   128  }
   129  
   130  // A Checker maintains the state of the type checker.
   131  // It must be created with [NewChecker].
   132  type Checker struct {
   133  	// package information
   134  	// (initialized by NewChecker, valid for the life-time of checker)
   135  	conf *Config
   136  	ctxt *Context // context for de-duplicating instances
   137  	fset *token.FileSet
   138  	pkg  *Package
   139  	*Info
   140  	version goVersion              // accepted language version
   141  	nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
   142  	objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
   143  	impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
   144  	// see TODO in validtype.go
   145  	// valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
   146  
   147  	// pkgPathMap maps package names to the set of distinct import paths we've
   148  	// seen for that name, anywhere in the import graph. It is used for
   149  	// disambiguating package names in error messages.
   150  	//
   151  	// pkgPathMap is allocated lazily, so that we don't pay the price of building
   152  	// it on the happy path. seenPkgMap tracks the packages that we've already
   153  	// walked.
   154  	pkgPathMap map[string]map[string]bool
   155  	seenPkgMap map[*Package]bool
   156  
   157  	// information collected during type-checking of a set of package files
   158  	// (initialized by Files, valid only for the duration of check.Files;
   159  	// maps and lists are allocated on demand)
   160  	files         []*ast.File               // package files
   161  	versions      map[*ast.File]string      // maps files to version strings (each file has an entry); shared with Info.FileVersions if present
   162  	imports       []*PkgName                // list of imported packages
   163  	dotImportMap  map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
   164  	recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
   165  	brokenAliases map[*TypeName]bool        // set of aliases with broken (not yet determined) types
   166  	unionTypeSets map[*Union]*_TypeSet      // computed type sets for union types
   167  	mono          monoGraph                 // graph for detecting non-monomorphizable instantiation loops
   168  
   169  	firstErr error                 // first error encountered
   170  	methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
   171  	untyped  map[ast.Expr]exprInfo // map of expressions without final type
   172  	delayed  []action              // stack of delayed action segments; segments are processed in FIFO order
   173  	objPath  []Object              // path of object dependencies during type inference (for cycle reporting)
   174  	cleaners []cleaner             // list of types that may need a final cleanup at the end of type-checking
   175  
   176  	// environment within which the current object is type-checked (valid only
   177  	// for the duration of type-checking a specific object)
   178  	environment
   179  
   180  	// debugging
   181  	indent int // indentation for tracing
   182  }
   183  
   184  // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
   185  func (check *Checker) addDeclDep(to Object) {
   186  	from := check.decl
   187  	if from == nil {
   188  		return // not in a package-level init expression
   189  	}
   190  	if _, found := check.objMap[to]; !found {
   191  		return // to is not a package-level object
   192  	}
   193  	from.addDep(to)
   194  }
   195  
   196  // Note: The following three alias-related functions are only used
   197  //       when Alias types are not enabled.
   198  
   199  // brokenAlias records that alias doesn't have a determined type yet.
   200  // It also sets alias.typ to Typ[Invalid].
   201  // Not used if check.conf._EnableAlias is set.
   202  func (check *Checker) brokenAlias(alias *TypeName) {
   203  	assert(!check.conf._EnableAlias)
   204  	if check.brokenAliases == nil {
   205  		check.brokenAliases = make(map[*TypeName]bool)
   206  	}
   207  	check.brokenAliases[alias] = true
   208  	alias.typ = Typ[Invalid]
   209  }
   210  
   211  // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
   212  func (check *Checker) validAlias(alias *TypeName, typ Type) {
   213  	assert(!check.conf._EnableAlias)
   214  	delete(check.brokenAliases, alias)
   215  	alias.typ = typ
   216  }
   217  
   218  // isBrokenAlias reports whether alias doesn't have a determined type yet.
   219  func (check *Checker) isBrokenAlias(alias *TypeName) bool {
   220  	assert(!check.conf._EnableAlias)
   221  	return check.brokenAliases[alias]
   222  }
   223  
   224  func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
   225  	m := check.untyped
   226  	if m == nil {
   227  		m = make(map[ast.Expr]exprInfo)
   228  		check.untyped = m
   229  	}
   230  	m[e] = exprInfo{lhs, mode, typ, val}
   231  }
   232  
   233  // later pushes f on to the stack of actions that will be processed later;
   234  // either at the end of the current statement, or in case of a local constant
   235  // or variable declaration, before the constant or variable is in scope
   236  // (so that f still sees the scope before any new declarations).
   237  // later returns the pushed action so one can provide a description
   238  // via action.describef for debugging, if desired.
   239  func (check *Checker) later(f func()) *action {
   240  	i := len(check.delayed)
   241  	check.delayed = append(check.delayed, action{f: f})
   242  	return &check.delayed[i]
   243  }
   244  
   245  // push pushes obj onto the object path and returns its index in the path.
   246  func (check *Checker) push(obj Object) int {
   247  	check.objPath = append(check.objPath, obj)
   248  	return len(check.objPath) - 1
   249  }
   250  
   251  // pop pops and returns the topmost object from the object path.
   252  func (check *Checker) pop() Object {
   253  	i := len(check.objPath) - 1
   254  	obj := check.objPath[i]
   255  	check.objPath[i] = nil
   256  	check.objPath = check.objPath[:i]
   257  	return obj
   258  }
   259  
   260  type cleaner interface {
   261  	cleanup()
   262  }
   263  
   264  // needsCleanup records objects/types that implement the cleanup method
   265  // which will be called at the end of type-checking.
   266  func (check *Checker) needsCleanup(c cleaner) {
   267  	check.cleaners = append(check.cleaners, c)
   268  }
   269  
   270  // NewChecker returns a new [Checker] instance for a given package.
   271  // [Package] files may be added incrementally via checker.Files.
   272  func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
   273  	// make sure we have a configuration
   274  	if conf == nil {
   275  		conf = new(Config)
   276  	}
   277  
   278  	// make sure we have an info struct
   279  	if info == nil {
   280  		info = new(Info)
   281  	}
   282  
   283  	// Note: clients may call NewChecker with the Unsafe package, which is
   284  	// globally shared and must not be mutated. Therefore NewChecker must not
   285  	// mutate *pkg.
   286  	//
   287  	// (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
   288  
   289  	// In go/types, conf._EnableAlias is controlled by gotypesalias.
   290  	conf._EnableAlias = gotypesalias.Value() != "0"
   291  
   292  	return &Checker{
   293  		conf:    conf,
   294  		ctxt:    conf.Context,
   295  		fset:    fset,
   296  		pkg:     pkg,
   297  		Info:    info,
   298  		version: asGoVersion(conf.GoVersion),
   299  		objMap:  make(map[Object]*declInfo),
   300  		impMap:  make(map[importKey]*Package),
   301  	}
   302  }
   303  
   304  // initFiles initializes the files-specific portion of checker.
   305  // The provided files must all belong to the same package.
   306  func (check *Checker) initFiles(files []*ast.File) {
   307  	// start with a clean slate (check.Files may be called multiple times)
   308  	check.files = nil
   309  	check.imports = nil
   310  	check.dotImportMap = nil
   311  
   312  	check.firstErr = nil
   313  	check.methods = nil
   314  	check.untyped = nil
   315  	check.delayed = nil
   316  	check.objPath = nil
   317  	check.cleaners = nil
   318  
   319  	// determine package name and collect valid files
   320  	pkg := check.pkg
   321  	for _, file := range files {
   322  		switch name := file.Name.Name; pkg.name {
   323  		case "":
   324  			if name != "_" {
   325  				pkg.name = name
   326  			} else {
   327  				check.error(file.Name, BlankPkgName, "invalid package name _")
   328  			}
   329  			fallthrough
   330  
   331  		case name:
   332  			check.files = append(check.files, file)
   333  
   334  		default:
   335  			check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected package %s", name, pkg.name)
   336  			// ignore this file
   337  		}
   338  	}
   339  
   340  	// reuse Info.FileVersions if provided
   341  	versions := check.Info.FileVersions
   342  	if versions == nil {
   343  		versions = make(map[*ast.File]string)
   344  	}
   345  	check.versions = versions
   346  
   347  	pkgVersionOk := check.version.isValid()
   348  	if pkgVersionOk && len(files) > 0 && check.version.cmp(go_current) > 0 {
   349  		check.errorf(files[0], TooNew, "package requires newer Go version %v (application built with %v)",
   350  			check.version, go_current)
   351  	}
   352  
   353  	// determine Go version for each file
   354  	for _, file := range check.files {
   355  		// use unaltered Config.GoVersion by default
   356  		// (This version string may contain dot-release numbers as in go1.20.1,
   357  		// unlike file versions which are Go language versions only, if valid.)
   358  		v := check.conf.GoVersion
   359  
   360  		// If the file specifies a version, use max(fileVersion, go1.21).
   361  		if fileVersion := asGoVersion(file.GoVersion); fileVersion.isValid() {
   362  			// Go 1.21 introduced the feature of setting the go.mod
   363  			// go line to an early version of Go and allowing //go:build lines
   364  			// to set the Go version in a given file. Versions Go 1.21 and later
   365  			// can be set backwards compatibly as that was the first version
   366  			// files with go1.21 or later build tags could be built with.
   367  			//
   368  			// Set the version to max(fileVersion, go1.21): That will allow a
   369  			// downgrade to a version before go1.22, where the for loop semantics
   370  			// change was made, while being backwards compatible with versions of
   371  			// go before the new //go:build semantics were introduced.
   372  			v = string(versionMax(fileVersion, go1_21))
   373  
   374  			// Report a specific error for each tagged file that's too new.
   375  			// (Normally the build system will have filtered files by version,
   376  			// but clients can present arbitrary files to the type checker.)
   377  			if fileVersion.cmp(go_current) > 0 {
   378  				// Use position of 'package [p]' for types/types2 consistency.
   379  				// (Ideally we would use the //build tag itself.)
   380  				check.errorf(file.Name, TooNew, "file requires newer Go version %v (application built with %v)", fileVersion, go_current)
   381  			}
   382  		}
   383  		versions[file] = v
   384  	}
   385  }
   386  
   387  func versionMax(a, b goVersion) goVersion {
   388  	if a.cmp(b) < 0 {
   389  		return b
   390  	}
   391  	return a
   392  }
   393  
   394  // A bailout panic is used for early termination.
   395  type bailout struct{}
   396  
   397  func (check *Checker) handleBailout(err *error) {
   398  	switch p := recover().(type) {
   399  	case nil, bailout:
   400  		// normal return or early exit
   401  		*err = check.firstErr
   402  	default:
   403  		// re-panic
   404  		panic(p)
   405  	}
   406  }
   407  
   408  // Files checks the provided files as part of the checker's package.
   409  func (check *Checker) Files(files []*ast.File) (err error) {
   410  	if check.pkg == Unsafe {
   411  		// Defensive handling for Unsafe, which cannot be type checked, and must
   412  		// not be mutated. See https://go.dev/issue/61212 for an example of where
   413  		// Unsafe is passed to NewChecker.
   414  		return nil
   415  	}
   416  
   417  	// Avoid early returns here! Nearly all errors can be
   418  	// localized to a piece of syntax and needn't prevent
   419  	// type-checking of the rest of the package.
   420  
   421  	defer check.handleBailout(&err)
   422  	check.checkFiles(files)
   423  	return
   424  }
   425  
   426  // checkFiles type-checks the specified files. Errors are reported as
   427  // a side effect, not by returning early, to ensure that well-formed
   428  // syntax is properly type annotated even in a package containing
   429  // errors.
   430  func (check *Checker) checkFiles(files []*ast.File) {
   431  	// Ensure that _EnableAlias is consistent among concurrent type checking
   432  	// operations. See the documentation of [_aliasAny] for details.
   433  	if check.conf._EnableAlias {
   434  		if atomic.AddInt32(&_aliasAny, 1) <= 0 {
   435  			panic("EnableAlias set while !EnableAlias type checking is ongoing")
   436  		}
   437  		defer atomic.AddInt32(&_aliasAny, -1)
   438  	} else {
   439  		if atomic.AddInt32(&_aliasAny, -1) >= 0 {
   440  			panic("!EnableAlias set while EnableAlias type checking is ongoing")
   441  		}
   442  		defer atomic.AddInt32(&_aliasAny, 1)
   443  	}
   444  
   445  	print := func(msg string) {
   446  		if check.conf._Trace {
   447  			fmt.Println()
   448  			fmt.Println(msg)
   449  		}
   450  	}
   451  
   452  	print("== initFiles ==")
   453  	check.initFiles(files)
   454  
   455  	print("== collectObjects ==")
   456  	check.collectObjects()
   457  
   458  	print("== packageObjects ==")
   459  	check.packageObjects()
   460  
   461  	print("== processDelayed ==")
   462  	check.processDelayed(0) // incl. all functions
   463  
   464  	print("== cleanup ==")
   465  	check.cleanup()
   466  
   467  	print("== initOrder ==")
   468  	check.initOrder()
   469  
   470  	if !check.conf.DisableUnusedImportCheck {
   471  		print("== unusedImports ==")
   472  		check.unusedImports()
   473  	}
   474  
   475  	print("== recordUntyped ==")
   476  	check.recordUntyped()
   477  
   478  	if check.firstErr == nil {
   479  		// TODO(mdempsky): Ensure monomorph is safe when errors exist.
   480  		check.monomorph()
   481  	}
   482  
   483  	check.pkg.goVersion = check.conf.GoVersion
   484  	check.pkg.complete = true
   485  
   486  	// no longer needed - release memory
   487  	check.imports = nil
   488  	check.dotImportMap = nil
   489  	check.pkgPathMap = nil
   490  	check.seenPkgMap = nil
   491  	check.recvTParamMap = nil
   492  	check.brokenAliases = nil
   493  	check.unionTypeSets = nil
   494  	check.ctxt = nil
   495  
   496  	// TODO(rFindley) There's more memory we should release at this point.
   497  }
   498  
   499  // processDelayed processes all delayed actions pushed after top.
   500  func (check *Checker) processDelayed(top int) {
   501  	// If each delayed action pushes a new action, the
   502  	// stack will continue to grow during this loop.
   503  	// However, it is only processing functions (which
   504  	// are processed in a delayed fashion) that may
   505  	// add more actions (such as nested functions), so
   506  	// this is a sufficiently bounded process.
   507  	for i := top; i < len(check.delayed); i++ {
   508  		a := &check.delayed[i]
   509  		if check.conf._Trace {
   510  			if a.desc != nil {
   511  				check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
   512  			} else {
   513  				check.trace(nopos, "-- delayed %p", a.f)
   514  			}
   515  		}
   516  		a.f() // may append to check.delayed
   517  		if check.conf._Trace {
   518  			fmt.Println()
   519  		}
   520  	}
   521  	assert(top <= len(check.delayed)) // stack must not have shrunk
   522  	check.delayed = check.delayed[:top]
   523  }
   524  
   525  // cleanup runs cleanup for all collected cleaners.
   526  func (check *Checker) cleanup() {
   527  	// Don't use a range clause since Named.cleanup may add more cleaners.
   528  	for i := 0; i < len(check.cleaners); i++ {
   529  		check.cleaners[i].cleanup()
   530  	}
   531  	check.cleaners = nil
   532  }
   533  
   534  func (check *Checker) record(x *operand) {
   535  	// convert x into a user-friendly set of values
   536  	// TODO(gri) this code can be simplified
   537  	var typ Type
   538  	var val constant.Value
   539  	switch x.mode {
   540  	case invalid:
   541  		typ = Typ[Invalid]
   542  	case novalue:
   543  		typ = (*Tuple)(nil)
   544  	case constant_:
   545  		typ = x.typ
   546  		val = x.val
   547  	default:
   548  		typ = x.typ
   549  	}
   550  	assert(x.expr != nil && typ != nil)
   551  
   552  	if isUntyped(typ) {
   553  		// delay type and value recording until we know the type
   554  		// or until the end of type checking
   555  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   556  	} else {
   557  		check.recordTypeAndValue(x.expr, x.mode, typ, val)
   558  	}
   559  }
   560  
   561  func (check *Checker) recordUntyped() {
   562  	if !debug && check.Types == nil {
   563  		return // nothing to do
   564  	}
   565  
   566  	for x, info := range check.untyped {
   567  		if debug && isTyped(info.typ) {
   568  			check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
   569  			panic("unreachable")
   570  		}
   571  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   572  	}
   573  }
   574  
   575  func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
   576  	assert(x != nil)
   577  	assert(typ != nil)
   578  	if mode == invalid {
   579  		return // omit
   580  	}
   581  	if mode == constant_ {
   582  		assert(val != nil)
   583  		// We check allBasic(typ, IsConstType) here as constant expressions may be
   584  		// recorded as type parameters.
   585  		assert(!isValid(typ) || allBasic(typ, IsConstType))
   586  	}
   587  	if m := check.Types; m != nil {
   588  		m[x] = TypeAndValue{mode, typ, val}
   589  	}
   590  }
   591  
   592  func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
   593  	// f must be a (possibly parenthesized, possibly qualified)
   594  	// identifier denoting a built-in (including unsafe's non-constant
   595  	// functions Add and Slice): record the signature for f and possible
   596  	// children.
   597  	for {
   598  		check.recordTypeAndValue(f, builtin, sig, nil)
   599  		switch p := f.(type) {
   600  		case *ast.Ident, *ast.SelectorExpr:
   601  			return // we're done
   602  		case *ast.ParenExpr:
   603  			f = p.X
   604  		default:
   605  			panic("unreachable")
   606  		}
   607  	}
   608  }
   609  
   610  // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
   611  // (and therefore has tuple type).
   612  func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
   613  	assert(x != nil)
   614  	assert(len(a) == 2)
   615  	if a[0].mode == invalid {
   616  		return
   617  	}
   618  	t0, t1 := a[0].typ, a[1].typ
   619  	assert(isTyped(t0) && isTyped(t1) && (allBoolean(t1) || t1 == universeError))
   620  	if m := check.Types; m != nil {
   621  		for {
   622  			tv := m[x]
   623  			assert(tv.Type != nil) // should have been recorded already
   624  			pos := x.Pos()
   625  			tv.Type = NewTuple(
   626  				NewVar(pos, check.pkg, "", t0),
   627  				NewVar(pos, check.pkg, "", t1),
   628  			)
   629  			m[x] = tv
   630  			// if x is a parenthesized expression (p.X), update p.X
   631  			p, _ := x.(*ast.ParenExpr)
   632  			if p == nil {
   633  				break
   634  			}
   635  			x = p.X
   636  		}
   637  	}
   638  }
   639  
   640  // recordInstance records instantiation information into check.Info, if the
   641  // Instances map is non-nil. The given expr must be an ident, selector, or
   642  // index (list) expr with ident or selector operand.
   643  //
   644  // TODO(rfindley): the expr parameter is fragile. See if we can access the
   645  // instantiated identifier in some other way.
   646  func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
   647  	ident := instantiatedIdent(expr)
   648  	assert(ident != nil)
   649  	assert(typ != nil)
   650  	if m := check.Instances; m != nil {
   651  		m[ident] = Instance{newTypeList(targs), typ}
   652  	}
   653  }
   654  
   655  func instantiatedIdent(expr ast.Expr) *ast.Ident {
   656  	var selOrIdent ast.Expr
   657  	switch e := expr.(type) {
   658  	case *ast.IndexExpr:
   659  		selOrIdent = e.X
   660  	case *ast.IndexListExpr:
   661  		selOrIdent = e.X
   662  	case *ast.SelectorExpr, *ast.Ident:
   663  		selOrIdent = e
   664  	}
   665  	switch x := selOrIdent.(type) {
   666  	case *ast.Ident:
   667  		return x
   668  	case *ast.SelectorExpr:
   669  		return x.Sel
   670  	}
   671  
   672  	// extra debugging of #63933
   673  	var buf strings.Builder
   674  	buf.WriteString("instantiated ident not found; please report: ")
   675  	ast.Fprint(&buf, token.NewFileSet(), expr, ast.NotNilFilter)
   676  	panic(buf.String())
   677  }
   678  
   679  func (check *Checker) recordDef(id *ast.Ident, obj Object) {
   680  	assert(id != nil)
   681  	if m := check.Defs; m != nil {
   682  		m[id] = obj
   683  	}
   684  }
   685  
   686  func (check *Checker) recordUse(id *ast.Ident, obj Object) {
   687  	assert(id != nil)
   688  	assert(obj != nil)
   689  	if m := check.Uses; m != nil {
   690  		m[id] = obj
   691  	}
   692  }
   693  
   694  func (check *Checker) recordImplicit(node ast.Node, obj Object) {
   695  	assert(node != nil)
   696  	assert(obj != nil)
   697  	if m := check.Implicits; m != nil {
   698  		m[node] = obj
   699  	}
   700  }
   701  
   702  func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   703  	assert(obj != nil && (recv == nil || len(index) > 0))
   704  	check.recordUse(x.Sel, obj)
   705  	if m := check.Selections; m != nil {
   706  		m[x] = &Selection{kind, recv, obj, index, indirect}
   707  	}
   708  }
   709  
   710  func (check *Checker) recordScope(node ast.Node, scope *Scope) {
   711  	assert(node != nil)
   712  	assert(scope != nil)
   713  	if m := check.Scopes; m != nil {
   714  		m[node] = scope
   715  	}
   716  }
   717  

View as plain text