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  	"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 %s", quote(name), quote(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  	downgradeOk := check.version.cmp(go1_21) >= 0
   331  
   332  	// determine Go version for each file
   333  	for _, file := range check.files {
   334  		// use unaltered Config.GoVersion by default
   335  		// (This version string may contain dot-release numbers as in go1.20.1,
   336  		// unlike file versions which are Go language versions only, if valid.)
   337  		v := check.conf.GoVersion
   338  
   339  		fileVersion := asGoVersion(file.GoVersion)
   340  		if fileVersion.isValid() {
   341  			// use the file version, if applicable
   342  			// (file versions are either the empty string or of the form go1.dd)
   343  			if pkgVersionOk {
   344  				cmp := fileVersion.cmp(check.version)
   345  				// Go 1.21 introduced the feature of setting the go.mod
   346  				// go line to an early version of Go and allowing //go:build lines
   347  				// to “upgrade” (cmp > 0) the Go version in a given file.
   348  				// We can do that backwards compatibly.
   349  				//
   350  				// Go 1.21 also introduced the feature of allowing //go:build lines
   351  				// to “downgrade” (cmp < 0) the Go version in a given file.
   352  				// That can't be done compatibly in general, since before the
   353  				// build lines were ignored and code got the module's Go version.
   354  				// To work around this, downgrades are only allowed when the
   355  				// module's Go version is Go 1.21 or later.
   356  				//
   357  				// If there is no valid check.version, then we don't really know what
   358  				// Go version to apply.
   359  				// Legacy tools may do this, and they historically have accepted everything.
   360  				// Preserve that behavior by ignoring //go:build constraints entirely in that
   361  				// case (!pkgVersionOk).
   362  				if cmp > 0 || cmp < 0 && downgradeOk {
   363  					v = file.GoVersion
   364  				}
   365  			}
   366  
   367  			// Report a specific error for each tagged file that's too new.
   368  			// (Normally the build system will have filtered files by version,
   369  			// but clients can present arbitrary files to the type checker.)
   370  			if fileVersion.cmp(go_current) > 0 {
   371  				// Use position of 'package [p]' for types/types2 consistency.
   372  				// (Ideally we would use the //build tag itself.)
   373  				check.errorf(file.PkgName, TooNew, "file requires newer Go version %v", fileVersion)
   374  			}
   375  		}
   376  		versions[base(file.Pos())] = v // base(file.Pos()) may be nil for tests
   377  	}
   378  }
   379  
   380  // A bailout panic is used for early termination.
   381  type bailout struct{}
   382  
   383  func (check *Checker) handleBailout(err *error) {
   384  	switch p := recover().(type) {
   385  	case nil, bailout:
   386  		// normal return or early exit
   387  		*err = check.firstErr
   388  	default:
   389  		// re-panic
   390  		panic(p)
   391  	}
   392  }
   393  
   394  // Files checks the provided files as part of the checker's package.
   395  func (check *Checker) Files(files []*syntax.File) (err error) {
   396  	if check.pkg == Unsafe {
   397  		// Defensive handling for Unsafe, which cannot be type checked, and must
   398  		// not be mutated. See https://go.dev/issue/61212 for an example of where
   399  		// Unsafe is passed to NewChecker.
   400  		return nil
   401  	}
   402  
   403  	// Avoid early returns here! Nearly all errors can be
   404  	// localized to a piece of syntax and needn't prevent
   405  	// type-checking of the rest of the package.
   406  
   407  	defer check.handleBailout(&err)
   408  	check.checkFiles(files)
   409  	return
   410  }
   411  
   412  // checkFiles type-checks the specified files. Errors are reported as
   413  // a side effect, not by returning early, to ensure that well-formed
   414  // syntax is properly type annotated even in a package containing
   415  // errors.
   416  func (check *Checker) checkFiles(files []*syntax.File) {
   417  	// Ensure that EnableAlias is consistent among concurrent type checking
   418  	// operations. See the documentation of [_aliasAny] for details.
   419  	if check.conf.EnableAlias {
   420  		if atomic.AddInt32(&_aliasAny, 1) <= 0 {
   421  			panic("EnableAlias set while !EnableAlias type checking is ongoing")
   422  		}
   423  		defer atomic.AddInt32(&_aliasAny, -1)
   424  	} else {
   425  		if atomic.AddInt32(&_aliasAny, -1) >= 0 {
   426  			panic("!EnableAlias set while EnableAlias type checking is ongoing")
   427  		}
   428  		defer atomic.AddInt32(&_aliasAny, 1)
   429  	}
   430  
   431  	print := func(msg string) {
   432  		if check.conf.Trace {
   433  			fmt.Println()
   434  			fmt.Println(msg)
   435  		}
   436  	}
   437  
   438  	print("== initFiles ==")
   439  	check.initFiles(files)
   440  
   441  	print("== collectObjects ==")
   442  	check.collectObjects()
   443  
   444  	print("== packageObjects ==")
   445  	check.packageObjects()
   446  
   447  	print("== processDelayed ==")
   448  	check.processDelayed(0) // incl. all functions
   449  
   450  	print("== cleanup ==")
   451  	check.cleanup()
   452  
   453  	print("== initOrder ==")
   454  	check.initOrder()
   455  
   456  	if !check.conf.DisableUnusedImportCheck {
   457  		print("== unusedImports ==")
   458  		check.unusedImports()
   459  	}
   460  
   461  	print("== recordUntyped ==")
   462  	check.recordUntyped()
   463  
   464  	if check.firstErr == nil {
   465  		// TODO(mdempsky): Ensure monomorph is safe when errors exist.
   466  		check.monomorph()
   467  	}
   468  
   469  	check.pkg.goVersion = check.conf.GoVersion
   470  	check.pkg.complete = true
   471  
   472  	// no longer needed - release memory
   473  	check.imports = nil
   474  	check.dotImportMap = nil
   475  	check.pkgPathMap = nil
   476  	check.seenPkgMap = nil
   477  	check.recvTParamMap = nil
   478  	check.brokenAliases = nil
   479  	check.unionTypeSets = nil
   480  	check.ctxt = nil
   481  
   482  	// TODO(gri) There's more memory we should release at this point.
   483  }
   484  
   485  // processDelayed processes all delayed actions pushed after top.
   486  func (check *Checker) processDelayed(top int) {
   487  	// If each delayed action pushes a new action, the
   488  	// stack will continue to grow during this loop.
   489  	// However, it is only processing functions (which
   490  	// are processed in a delayed fashion) that may
   491  	// add more actions (such as nested functions), so
   492  	// this is a sufficiently bounded process.
   493  	for i := top; i < len(check.delayed); i++ {
   494  		a := &check.delayed[i]
   495  		if check.conf.Trace {
   496  			if a.desc != nil {
   497  				check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
   498  			} else {
   499  				check.trace(nopos, "-- delayed %p", a.f)
   500  			}
   501  		}
   502  		a.f() // may append to check.delayed
   503  		if check.conf.Trace {
   504  			fmt.Println()
   505  		}
   506  	}
   507  	assert(top <= len(check.delayed)) // stack must not have shrunk
   508  	check.delayed = check.delayed[:top]
   509  }
   510  
   511  // cleanup runs cleanup for all collected cleaners.
   512  func (check *Checker) cleanup() {
   513  	// Don't use a range clause since Named.cleanup may add more cleaners.
   514  	for i := 0; i < len(check.cleaners); i++ {
   515  		check.cleaners[i].cleanup()
   516  	}
   517  	check.cleaners = nil
   518  }
   519  
   520  func (check *Checker) record(x *operand) {
   521  	// convert x into a user-friendly set of values
   522  	// TODO(gri) this code can be simplified
   523  	var typ Type
   524  	var val constant.Value
   525  	switch x.mode {
   526  	case invalid:
   527  		typ = Typ[Invalid]
   528  	case novalue:
   529  		typ = (*Tuple)(nil)
   530  	case constant_:
   531  		typ = x.typ
   532  		val = x.val
   533  	default:
   534  		typ = x.typ
   535  	}
   536  	assert(x.expr != nil && typ != nil)
   537  
   538  	if isUntyped(typ) {
   539  		// delay type and value recording until we know the type
   540  		// or until the end of type checking
   541  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   542  	} else {
   543  		check.recordTypeAndValue(x.expr, x.mode, typ, val)
   544  	}
   545  }
   546  
   547  func (check *Checker) recordUntyped() {
   548  	if !debug && !check.recordTypes() {
   549  		return // nothing to do
   550  	}
   551  
   552  	for x, info := range check.untyped {
   553  		if debug && isTyped(info.typ) {
   554  			check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
   555  			panic("unreachable")
   556  		}
   557  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   558  	}
   559  }
   560  
   561  func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
   562  	assert(x != nil)
   563  	assert(typ != nil)
   564  	if mode == invalid {
   565  		return // omit
   566  	}
   567  	if mode == constant_ {
   568  		assert(val != nil)
   569  		// We check allBasic(typ, IsConstType) here as constant expressions may be
   570  		// recorded as type parameters.
   571  		assert(!isValid(typ) || allBasic(typ, IsConstType))
   572  	}
   573  	if m := check.Types; m != nil {
   574  		m[x] = TypeAndValue{mode, typ, val}
   575  	}
   576  	if check.StoreTypesInSyntax {
   577  		tv := TypeAndValue{mode, typ, val}
   578  		stv := syntax.TypeAndValue{Type: typ, Value: val}
   579  		if tv.IsVoid() {
   580  			stv.SetIsVoid()
   581  		}
   582  		if tv.IsType() {
   583  			stv.SetIsType()
   584  		}
   585  		if tv.IsBuiltin() {
   586  			stv.SetIsBuiltin()
   587  		}
   588  		if tv.IsValue() {
   589  			stv.SetIsValue()
   590  		}
   591  		if tv.IsNil() {
   592  			stv.SetIsNil()
   593  		}
   594  		if tv.Addressable() {
   595  			stv.SetAddressable()
   596  		}
   597  		if tv.Assignable() {
   598  			stv.SetAssignable()
   599  		}
   600  		if tv.HasOk() {
   601  			stv.SetHasOk()
   602  		}
   603  		x.SetTypeInfo(stv)
   604  	}
   605  }
   606  
   607  func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
   608  	// f must be a (possibly parenthesized, possibly qualified)
   609  	// identifier denoting a built-in (including unsafe's non-constant
   610  	// functions Add and Slice): record the signature for f and possible
   611  	// children.
   612  	for {
   613  		check.recordTypeAndValue(f, builtin, sig, nil)
   614  		switch p := f.(type) {
   615  		case *syntax.Name, *syntax.SelectorExpr:
   616  			return // we're done
   617  		case *syntax.ParenExpr:
   618  			f = p.X
   619  		default:
   620  			panic("unreachable")
   621  		}
   622  	}
   623  }
   624  
   625  // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
   626  // (and therefore has tuple type).
   627  func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
   628  	assert(x != nil)
   629  	assert(len(a) == 2)
   630  	if a[0].mode == invalid {
   631  		return
   632  	}
   633  	t0, t1 := a[0].typ, a[1].typ
   634  	assert(isTyped(t0) && isTyped(t1) && (allBoolean(t1) || t1 == universeError))
   635  	if m := check.Types; m != nil {
   636  		for {
   637  			tv := m[x]
   638  			assert(tv.Type != nil) // should have been recorded already
   639  			pos := x.Pos()
   640  			tv.Type = NewTuple(
   641  				NewVar(pos, check.pkg, "", t0),
   642  				NewVar(pos, check.pkg, "", t1),
   643  			)
   644  			m[x] = tv
   645  			// if x is a parenthesized expression (p.X), update p.X
   646  			p, _ := x.(*syntax.ParenExpr)
   647  			if p == nil {
   648  				break
   649  			}
   650  			x = p.X
   651  		}
   652  	}
   653  	if check.StoreTypesInSyntax {
   654  		// Note: this loop is duplicated because the type of tv is different.
   655  		// Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
   656  		for {
   657  			tv := x.GetTypeInfo()
   658  			assert(tv.Type != nil) // should have been recorded already
   659  			pos := x.Pos()
   660  			tv.Type = NewTuple(
   661  				NewVar(pos, check.pkg, "", t0),
   662  				NewVar(pos, check.pkg, "", t1),
   663  			)
   664  			x.SetTypeInfo(tv)
   665  			p, _ := x.(*syntax.ParenExpr)
   666  			if p == nil {
   667  				break
   668  			}
   669  			x = p.X
   670  		}
   671  	}
   672  }
   673  
   674  // recordInstance records instantiation information into check.Info, if the
   675  // Instances map is non-nil. The given expr must be an ident, selector, or
   676  // index (list) expr with ident or selector operand.
   677  //
   678  // TODO(rfindley): the expr parameter is fragile. See if we can access the
   679  // instantiated identifier in some other way.
   680  func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
   681  	ident := instantiatedIdent(expr)
   682  	assert(ident != nil)
   683  	assert(typ != nil)
   684  	if m := check.Instances; m != nil {
   685  		m[ident] = Instance{newTypeList(targs), typ}
   686  	}
   687  }
   688  
   689  func instantiatedIdent(expr syntax.Expr) *syntax.Name {
   690  	var selOrIdent syntax.Expr
   691  	switch e := expr.(type) {
   692  	case *syntax.IndexExpr:
   693  		selOrIdent = e.X
   694  	case *syntax.SelectorExpr, *syntax.Name:
   695  		selOrIdent = e
   696  	}
   697  	switch x := selOrIdent.(type) {
   698  	case *syntax.Name:
   699  		return x
   700  	case *syntax.SelectorExpr:
   701  		return x.Sel
   702  	}
   703  	panic("instantiated ident not found")
   704  }
   705  
   706  func (check *Checker) recordDef(id *syntax.Name, obj Object) {
   707  	assert(id != nil)
   708  	if m := check.Defs; m != nil {
   709  		m[id] = obj
   710  	}
   711  }
   712  
   713  func (check *Checker) recordUse(id *syntax.Name, obj Object) {
   714  	assert(id != nil)
   715  	assert(obj != nil)
   716  	if m := check.Uses; m != nil {
   717  		m[id] = obj
   718  	}
   719  }
   720  
   721  func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
   722  	assert(node != nil)
   723  	assert(obj != nil)
   724  	if m := check.Implicits; m != nil {
   725  		m[node] = obj
   726  	}
   727  }
   728  
   729  func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   730  	assert(obj != nil && (recv == nil || len(index) > 0))
   731  	check.recordUse(x.Sel, obj)
   732  	if m := check.Selections; m != nil {
   733  		m[x] = &Selection{kind, recv, obj, index, indirect}
   734  	}
   735  }
   736  
   737  func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
   738  	assert(node != nil)
   739  	assert(scope != nil)
   740  	if m := check.Scopes; m != nil {
   741  		m[node] = scope
   742  	}
   743  }
   744  

View as plain text