...

Source file src/cmd/compile/internal/types2/check.go

Documentation: cmd/compile/internal/types2

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

View as plain text