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

View as plain text