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

View as plain text