Source file src/go/types/decl.go

     1  // Copyright 2014 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  package types
     6  
     7  import (
     8  	"fmt"
     9  	"go/ast"
    10  	"go/constant"
    11  	"go/token"
    12  	. "internal/types/errors"
    13  	"slices"
    14  )
    15  
    16  func (check *Checker) declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos) {
    17  	// spec: "The blank identifier, represented by the underscore
    18  	// character _, may be used in a declaration like any other
    19  	// identifier but the declaration does not introduce a new
    20  	// binding."
    21  	if obj.Name() != "_" {
    22  		if alt := scope.Insert(obj); alt != nil {
    23  			err := check.newError(DuplicateDecl)
    24  			err.addf(obj, "%s redeclared in this block", obj.Name())
    25  			err.addAltDecl(alt)
    26  			err.report()
    27  			return
    28  		}
    29  		obj.setScopePos(pos)
    30  	}
    31  	if id != nil {
    32  		check.recordDef(id, obj)
    33  	}
    34  }
    35  
    36  // pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
    37  func pathString(path []Object) string {
    38  	var s string
    39  	for i, p := range path {
    40  		if i > 0 {
    41  			s += "->"
    42  		}
    43  		s += p.Name()
    44  	}
    45  	return s
    46  }
    47  
    48  // objDecl type-checks the declaration of obj in its respective (file) environment.
    49  // For the meaning of def, see Checker.definedType, in typexpr.go.
    50  func (check *Checker) objDecl(obj Object, def *TypeName) {
    51  	if tracePos {
    52  		check.pushPos(atPos(obj.Pos()))
    53  		defer func() {
    54  			// If we're panicking, keep stack of source positions.
    55  			if p := recover(); p != nil {
    56  				panic(p)
    57  			}
    58  			check.popPos()
    59  		}()
    60  	}
    61  
    62  	if check.conf._Trace && obj.Type() == nil {
    63  		if check.indent == 0 {
    64  			fmt.Println() // empty line between top-level objects for readability
    65  		}
    66  		check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
    67  		check.indent++
    68  		defer func() {
    69  			check.indent--
    70  			check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
    71  		}()
    72  	}
    73  
    74  	// Checking the declaration of obj means inferring its type
    75  	// (and possibly its value, for constants).
    76  	// An object's type (and thus the object) may be in one of
    77  	// three states which are expressed by colors:
    78  	//
    79  	// - an object whose type is not yet known is painted white (initial color)
    80  	// - an object whose type is in the process of being inferred is painted grey
    81  	// - an object whose type is fully inferred is painted black
    82  	//
    83  	// During type inference, an object's color changes from white to grey
    84  	// to black (pre-declared objects are painted black from the start).
    85  	// A black object (i.e., its type) can only depend on (refer to) other black
    86  	// ones. White and grey objects may depend on white and black objects.
    87  	// A dependency on a grey object indicates a cycle which may or may not be
    88  	// valid.
    89  	//
    90  	// When objects turn grey, they are pushed on the object path (a stack);
    91  	// they are popped again when they turn black. Thus, if a grey object (a
    92  	// cycle) is encountered, it is on the object path, and all the objects
    93  	// it depends on are the remaining objects on that path. Color encoding
    94  	// is such that the color value of a grey object indicates the index of
    95  	// that object in the object path.
    96  
    97  	// During type-checking, white objects may be assigned a type without
    98  	// traversing through objDecl; e.g., when initializing constants and
    99  	// variables. Update the colors of those objects here (rather than
   100  	// everywhere where we set the type) to satisfy the color invariants.
   101  	if obj.color() == white && obj.Type() != nil {
   102  		obj.setColor(black)
   103  		return
   104  	}
   105  
   106  	switch obj.color() {
   107  	case white:
   108  		assert(obj.Type() == nil)
   109  		// All color values other than white and black are considered grey.
   110  		// Because black and white are < grey, all values >= grey are grey.
   111  		// Use those values to encode the object's index into the object path.
   112  		obj.setColor(grey + color(check.push(obj)))
   113  		defer func() {
   114  			check.pop().setColor(black)
   115  		}()
   116  
   117  	case black:
   118  		assert(obj.Type() != nil)
   119  		return
   120  
   121  	default:
   122  		// Color values other than white or black are considered grey.
   123  		fallthrough
   124  
   125  	case grey:
   126  		// We have a (possibly invalid) cycle.
   127  		// In the existing code, this is marked by a non-nil type
   128  		// for the object except for constants and variables whose
   129  		// type may be non-nil (known), or nil if it depends on the
   130  		// not-yet known initialization value.
   131  		// In the former case, set the type to Typ[Invalid] because
   132  		// we have an initialization cycle. The cycle error will be
   133  		// reported later, when determining initialization order.
   134  		// TODO(gri) Report cycle here and simplify initialization
   135  		// order code.
   136  		switch obj := obj.(type) {
   137  		case *Const:
   138  			if !check.validCycle(obj) || obj.typ == nil {
   139  				obj.typ = Typ[Invalid]
   140  			}
   141  
   142  		case *Var:
   143  			if !check.validCycle(obj) || obj.typ == nil {
   144  				obj.typ = Typ[Invalid]
   145  			}
   146  
   147  		case *TypeName:
   148  			if !check.validCycle(obj) {
   149  				// break cycle
   150  				// (without this, calling underlying()
   151  				// below may lead to an endless loop
   152  				// if we have a cycle for a defined
   153  				// (*Named) type)
   154  				obj.typ = Typ[Invalid]
   155  			}
   156  
   157  		case *Func:
   158  			if !check.validCycle(obj) {
   159  				// Don't set obj.typ to Typ[Invalid] here
   160  				// because plenty of code type-asserts that
   161  				// functions have a *Signature type. Grey
   162  				// functions have their type set to an empty
   163  				// signature which makes it impossible to
   164  				// initialize a variable with the function.
   165  			}
   166  
   167  		default:
   168  			panic("unreachable")
   169  		}
   170  		assert(obj.Type() != nil)
   171  		return
   172  	}
   173  
   174  	d := check.objMap[obj]
   175  	if d == nil {
   176  		check.dump("%v: %s should have been declared", obj.Pos(), obj)
   177  		panic("unreachable")
   178  	}
   179  
   180  	// save/restore current environment and set up object environment
   181  	defer func(env environment) {
   182  		check.environment = env
   183  	}(check.environment)
   184  	check.environment = environment{scope: d.file, version: d.version}
   185  
   186  	// Const and var declarations must not have initialization
   187  	// cycles. We track them by remembering the current declaration
   188  	// in check.decl. Initialization expressions depending on other
   189  	// consts, vars, or functions, add dependencies to the current
   190  	// check.decl.
   191  	switch obj := obj.(type) {
   192  	case *Const:
   193  		check.decl = d // new package-level const decl
   194  		check.constDecl(obj, d.vtyp, d.init, d.inherited)
   195  	case *Var:
   196  		check.decl = d // new package-level var decl
   197  		check.varDecl(obj, d.lhs, d.vtyp, d.init)
   198  	case *TypeName:
   199  		// invalid recursive types are detected via path
   200  		check.typeDecl(obj, d.tdecl, def)
   201  		check.collectMethods(obj) // methods can only be added to top-level types
   202  	case *Func:
   203  		// functions may be recursive - no need to track dependencies
   204  		check.funcDecl(obj, d)
   205  	default:
   206  		panic("unreachable")
   207  	}
   208  }
   209  
   210  // validCycle checks if the cycle starting with obj is valid and
   211  // reports an error if it is not.
   212  func (check *Checker) validCycle(obj Object) (valid bool) {
   213  	// The object map contains the package scope objects and the non-interface methods.
   214  	if debug {
   215  		info := check.objMap[obj]
   216  		inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil) // exclude methods
   217  		isPkgObj := obj.Parent() == check.pkg.scope
   218  		if isPkgObj != inObjMap {
   219  			check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
   220  			panic("unreachable")
   221  		}
   222  	}
   223  
   224  	// Count cycle objects.
   225  	assert(obj.color() >= grey)
   226  	start := obj.color() - grey // index of obj in objPath
   227  	cycle := check.objPath[start:]
   228  	tparCycle := false // if set, the cycle is through a type parameter list
   229  	nval := 0          // number of (constant or variable) values in the cycle
   230  	ndef := 0          // number of type definitions in the cycle
   231  loop:
   232  	for _, obj := range cycle {
   233  		switch obj := obj.(type) {
   234  		case *Const, *Var:
   235  			nval++
   236  		case *TypeName:
   237  			// If we reach a generic type that is part of a cycle
   238  			// and we are in a type parameter list, we have a cycle
   239  			// through a type parameter list.
   240  			if check.inTParamList && isGeneric(obj.typ) {
   241  				tparCycle = true
   242  				break loop
   243  			}
   244  
   245  			// Determine if the type name is an alias or not. For
   246  			// package-level objects, use the object map which
   247  			// provides syntactic information (which doesn't rely
   248  			// on the order in which the objects are set up). For
   249  			// local objects, we can rely on the order, so use
   250  			// the object's predicate.
   251  			// TODO(gri) It would be less fragile to always access
   252  			// the syntactic information. We should consider storing
   253  			// this information explicitly in the object.
   254  			var alias bool
   255  			if check.conf._EnableAlias {
   256  				alias = obj.IsAlias()
   257  			} else {
   258  				if d := check.objMap[obj]; d != nil {
   259  					alias = d.tdecl.Assign.IsValid() // package-level object
   260  				} else {
   261  					alias = obj.IsAlias() // function local object
   262  				}
   263  			}
   264  			if !alias {
   265  				ndef++
   266  			}
   267  		case *Func:
   268  			// ignored for now
   269  		default:
   270  			panic("unreachable")
   271  		}
   272  	}
   273  
   274  	if check.conf._Trace {
   275  		check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
   276  		if tparCycle {
   277  			check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
   278  		} else {
   279  			check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
   280  		}
   281  		defer func() {
   282  			if valid {
   283  				check.trace(obj.Pos(), "=> cycle is valid")
   284  			} else {
   285  				check.trace(obj.Pos(), "=> error: cycle is invalid")
   286  			}
   287  		}()
   288  	}
   289  
   290  	// Cycles through type parameter lists are ok (go.dev/issue/68162).
   291  	if tparCycle {
   292  		return true
   293  	}
   294  
   295  	// A cycle involving only constants and variables is invalid but we
   296  	// ignore them here because they are reported via the initialization
   297  	// cycle check.
   298  	if nval == len(cycle) {
   299  		return true
   300  	}
   301  
   302  	// A cycle involving only types (and possibly functions) must have at least
   303  	// one type definition to be permitted: If there is no type definition, we
   304  	// have a sequence of alias type names which will expand ad infinitum.
   305  	if nval == 0 && ndef > 0 {
   306  		return true
   307  	}
   308  
   309  	check.cycleError(cycle, firstInSrc(cycle))
   310  	return false
   311  }
   312  
   313  // cycleError reports a declaration cycle starting with the object at cycle[start].
   314  func (check *Checker) cycleError(cycle []Object, start int) {
   315  	// name returns the (possibly qualified) object name.
   316  	// This is needed because with generic types, cycles
   317  	// may refer to imported types. See go.dev/issue/50788.
   318  	// TODO(gri) This functionality is used elsewhere. Factor it out.
   319  	name := func(obj Object) string {
   320  		return packagePrefix(obj.Pkg(), check.qualifier) + obj.Name()
   321  	}
   322  
   323  	// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
   324  	obj := cycle[start]
   325  	tname, _ := obj.(*TypeName)
   326  	if tname != nil {
   327  		if check.conf._EnableAlias {
   328  			if a, ok := tname.Type().(*Alias); ok {
   329  				a.fromRHS = Typ[Invalid]
   330  			}
   331  		} else {
   332  			if tname.IsAlias() {
   333  				check.validAlias(tname, Typ[Invalid])
   334  			}
   335  		}
   336  	}
   337  
   338  	// report a more concise error for self references
   339  	if len(cycle) == 1 {
   340  		if tname != nil {
   341  			check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", name(obj))
   342  		} else {
   343  			check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", name(obj))
   344  		}
   345  		return
   346  	}
   347  
   348  	err := check.newError(InvalidDeclCycle)
   349  	if tname != nil {
   350  		err.addf(obj, "invalid recursive type %s", name(obj))
   351  	} else {
   352  		err.addf(obj, "invalid cycle in declaration of %s", name(obj))
   353  	}
   354  	// "cycle[i] refers to cycle[j]" for (i,j) = (s,s+1), (s+1,s+2), ..., (n-1,0), (0,1), ..., (s-1,s) for len(cycle) = n, s = start.
   355  	for i := range cycle {
   356  		next := cycle[(start+i+1)%len(cycle)]
   357  		err.addf(obj, "%s refers to %s", name(obj), name(next))
   358  		obj = next
   359  	}
   360  	err.report()
   361  }
   362  
   363  // firstInSrc reports the index of the object with the "smallest"
   364  // source position in path. path must not be empty.
   365  func firstInSrc(path []Object) int {
   366  	fst, pos := 0, path[0].Pos()
   367  	for i, t := range path[1:] {
   368  		if cmpPos(t.Pos(), pos) < 0 {
   369  			fst, pos = i+1, t.Pos()
   370  		}
   371  	}
   372  	return fst
   373  }
   374  
   375  type (
   376  	decl interface {
   377  		node() ast.Node
   378  	}
   379  
   380  	importDecl struct{ spec *ast.ImportSpec }
   381  	constDecl  struct {
   382  		spec      *ast.ValueSpec
   383  		iota      int
   384  		typ       ast.Expr
   385  		init      []ast.Expr
   386  		inherited bool
   387  	}
   388  	varDecl  struct{ spec *ast.ValueSpec }
   389  	typeDecl struct{ spec *ast.TypeSpec }
   390  	funcDecl struct{ decl *ast.FuncDecl }
   391  )
   392  
   393  func (d importDecl) node() ast.Node { return d.spec }
   394  func (d constDecl) node() ast.Node  { return d.spec }
   395  func (d varDecl) node() ast.Node    { return d.spec }
   396  func (d typeDecl) node() ast.Node   { return d.spec }
   397  func (d funcDecl) node() ast.Node   { return d.decl }
   398  
   399  func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
   400  	for _, d := range decls {
   401  		check.walkDecl(d, f)
   402  	}
   403  }
   404  
   405  func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
   406  	switch d := d.(type) {
   407  	case *ast.BadDecl:
   408  		// ignore
   409  	case *ast.GenDecl:
   410  		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   411  		for iota, s := range d.Specs {
   412  			switch s := s.(type) {
   413  			case *ast.ImportSpec:
   414  				f(importDecl{s})
   415  			case *ast.ValueSpec:
   416  				switch d.Tok {
   417  				case token.CONST:
   418  					// determine which initialization expressions to use
   419  					inherited := true
   420  					switch {
   421  					case s.Type != nil || len(s.Values) > 0:
   422  						last = s
   423  						inherited = false
   424  					case last == nil:
   425  						last = new(ast.ValueSpec) // make sure last exists
   426  						inherited = false
   427  					}
   428  					check.arityMatch(s, last)
   429  					f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
   430  				case token.VAR:
   431  					check.arityMatch(s, nil)
   432  					f(varDecl{s})
   433  				default:
   434  					check.errorf(s, InvalidSyntaxTree, "invalid token %s", d.Tok)
   435  				}
   436  			case *ast.TypeSpec:
   437  				f(typeDecl{s})
   438  			default:
   439  				check.errorf(s, InvalidSyntaxTree, "unknown ast.Spec node %T", s)
   440  			}
   441  		}
   442  	case *ast.FuncDecl:
   443  		f(funcDecl{d})
   444  	default:
   445  		check.errorf(d, InvalidSyntaxTree, "unknown ast.Decl node %T", d)
   446  	}
   447  }
   448  
   449  func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
   450  	assert(obj.typ == nil)
   451  
   452  	// use the correct value of iota
   453  	defer func(iota constant.Value, errpos positioner) {
   454  		check.iota = iota
   455  		check.errpos = errpos
   456  	}(check.iota, check.errpos)
   457  	check.iota = obj.val
   458  	check.errpos = nil
   459  
   460  	// provide valid constant value under all circumstances
   461  	obj.val = constant.MakeUnknown()
   462  
   463  	// determine type, if any
   464  	if typ != nil {
   465  		t := check.typ(typ)
   466  		if !isConstType(t) {
   467  			// don't report an error if the type is an invalid C (defined) type
   468  			// (go.dev/issue/22090)
   469  			if isValid(t.Underlying()) {
   470  				check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
   471  			}
   472  			obj.typ = Typ[Invalid]
   473  			return
   474  		}
   475  		obj.typ = t
   476  	}
   477  
   478  	// check initialization
   479  	var x operand
   480  	if init != nil {
   481  		if inherited {
   482  			// The initialization expression is inherited from a previous
   483  			// constant declaration, and (error) positions refer to that
   484  			// expression and not the current constant declaration. Use
   485  			// the constant identifier position for any errors during
   486  			// init expression evaluation since that is all we have
   487  			// (see issues go.dev/issue/42991, go.dev/issue/42992).
   488  			check.errpos = atPos(obj.pos)
   489  		}
   490  		check.expr(nil, &x, init)
   491  	}
   492  	check.initConst(obj, &x)
   493  }
   494  
   495  func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
   496  	assert(obj.typ == nil)
   497  
   498  	// determine type, if any
   499  	if typ != nil {
   500  		obj.typ = check.varType(typ)
   501  		// We cannot spread the type to all lhs variables if there
   502  		// are more than one since that would mark them as checked
   503  		// (see Checker.objDecl) and the assignment of init exprs,
   504  		// if any, would not be checked.
   505  		//
   506  		// TODO(gri) If we have no init expr, we should distribute
   507  		// a given type otherwise we need to re-evaluate the type
   508  		// expr for each lhs variable, leading to duplicate work.
   509  	}
   510  
   511  	// check initialization
   512  	if init == nil {
   513  		if typ == nil {
   514  			// error reported before by arityMatch
   515  			obj.typ = Typ[Invalid]
   516  		}
   517  		return
   518  	}
   519  
   520  	if lhs == nil || len(lhs) == 1 {
   521  		assert(lhs == nil || lhs[0] == obj)
   522  		var x operand
   523  		check.expr(newTarget(obj.typ, obj.name), &x, init)
   524  		check.initVar(obj, &x, "variable declaration")
   525  		return
   526  	}
   527  
   528  	if debug {
   529  		// obj must be one of lhs
   530  		if !slices.Contains(lhs, obj) {
   531  			panic("inconsistent lhs")
   532  		}
   533  	}
   534  
   535  	// We have multiple variables on the lhs and one init expr.
   536  	// Make sure all variables have been given the same type if
   537  	// one was specified, otherwise they assume the type of the
   538  	// init expression values (was go.dev/issue/15755).
   539  	if typ != nil {
   540  		for _, lhs := range lhs {
   541  			lhs.typ = obj.typ
   542  		}
   543  	}
   544  
   545  	check.initVars(lhs, []ast.Expr{init}, nil)
   546  }
   547  
   548  // isImportedConstraint reports whether typ is an imported type constraint.
   549  func (check *Checker) isImportedConstraint(typ Type) bool {
   550  	named := asNamed(typ)
   551  	if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
   552  		return false
   553  	}
   554  	u, _ := named.Underlying().(*Interface)
   555  	return u != nil && !u.IsMethodSet()
   556  }
   557  
   558  func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *TypeName) {
   559  	assert(obj.typ == nil)
   560  
   561  	// Only report a version error if we have not reported one already.
   562  	versionErr := false
   563  
   564  	var rhs Type
   565  	check.later(func() {
   566  		if t := asNamed(obj.typ); t != nil { // type may be invalid
   567  			check.validType(t)
   568  		}
   569  		// If typ is local, an error was already reported where typ is specified/defined.
   570  		_ = !versionErr && check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
   571  	}).describef(obj, "validType(%s)", obj.Name())
   572  
   573  	// First type parameter, or nil.
   574  	var tparam0 *ast.Field
   575  	if tdecl.TypeParams.NumFields() > 0 {
   576  		tparam0 = tdecl.TypeParams.List[0]
   577  	}
   578  
   579  	// alias declaration
   580  	if tdecl.Assign.IsValid() {
   581  		// Report highest version requirement first so that fixing a version issue
   582  		// avoids possibly two -lang changes (first to Go 1.9 and then to Go 1.23).
   583  		if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_23, "generic type alias") {
   584  			versionErr = true
   585  		}
   586  		if !versionErr && !check.verifyVersionf(atPos(tdecl.Assign), go1_9, "type alias") {
   587  			versionErr = true
   588  		}
   589  
   590  		if check.conf._EnableAlias {
   591  			alias := check.newAlias(obj, nil)
   592  			setDefType(def, alias)
   593  
   594  			// If we could not type the RHS, set it to invalid. This should
   595  			// only ever happen if we panic before setting.
   596  			defer func() {
   597  				if alias.fromRHS == nil {
   598  					alias.fromRHS = Typ[Invalid]
   599  					unalias(alias)
   600  				}
   601  			}()
   602  
   603  			// handle type parameters even if not allowed (Alias type is supported)
   604  			if tparam0 != nil {
   605  				check.openScope(tdecl, "type parameters")
   606  				defer check.closeScope()
   607  				check.collectTypeParams(&alias.tparams, tdecl.TypeParams)
   608  			}
   609  
   610  			rhs = check.definedType(tdecl.Type, obj)
   611  			assert(rhs != nil)
   612  
   613  			alias.fromRHS = rhs
   614  			unalias(alias) // populate alias.actual
   615  		} else {
   616  			// With Go1.23, the default behavior is to use Alias nodes,
   617  			// reflected by check.enableAlias. Signal non-default behavior.
   618  			//
   619  			// TODO(gri) Testing runs tests in both modes. Do we need to exclude
   620  			//           tracking of non-default behavior for tests?
   621  			gotypesalias.IncNonDefault()
   622  
   623  			if !versionErr && tparam0 != nil {
   624  				check.error(tdecl, UnsupportedFeature, "generic type alias requires GODEBUG=gotypesalias=1 or unset")
   625  				versionErr = true
   626  			}
   627  
   628  			check.brokenAlias(obj)
   629  			rhs = check.typ(tdecl.Type)
   630  			check.validAlias(obj, rhs)
   631  		}
   632  		return
   633  	}
   634  
   635  	// type definition or generic type declaration
   636  	if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_18, "type parameter") {
   637  		versionErr = true
   638  	}
   639  
   640  	named := check.newNamed(obj, nil, nil)
   641  	setDefType(def, named)
   642  
   643  	// The RHS of a named N can be nil if, for example, N is defined as a cycle of aliases with
   644  	// gotypesalias=0. Consider:
   645  	//
   646  	//   type D N    // N.unpack() will panic
   647  	//   type N A
   648  	//   type A = N  // N.fromRHS is not set before N.unpack(), since A does not call setDefType
   649  	//
   650  	// There is likely a better way to detect such cases, but it may not be worth the effort.
   651  	// Instead, we briefly permit a nil N.fromRHS while type-checking D.
   652  	named.allowNilRHS = true
   653  	defer (func() { named.allowNilRHS = false })()
   654  
   655  	if tdecl.TypeParams != nil {
   656  		check.openScope(tdecl, "type parameters")
   657  		defer check.closeScope()
   658  		check.collectTypeParams(&named.tparams, tdecl.TypeParams)
   659  	}
   660  
   661  	rhs = check.definedType(tdecl.Type, obj)
   662  	assert(rhs != nil)
   663  	named.fromRHS = rhs
   664  
   665  	// spec: "In a type definition the given type cannot be a type parameter."
   666  	// (See also go.dev/issue/45639.)
   667  	if isTypeParam(rhs) {
   668  		check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
   669  		named.fromRHS = Typ[Invalid]
   670  	}
   671  }
   672  
   673  func (check *Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList) {
   674  	var tparams []*TypeParam
   675  	// Declare type parameters up-front, with empty interface as type bound.
   676  	// The scope of type parameters starts at the beginning of the type parameter
   677  	// list (so we can have mutually recursive parameterized interfaces).
   678  	scopePos := list.Pos()
   679  	for _, f := range list.List {
   680  		for _, name := range f.Names {
   681  			tparams = append(tparams, check.declareTypeParam(name, scopePos))
   682  		}
   683  	}
   684  
   685  	// Set the type parameters before collecting the type constraints because
   686  	// the parameterized type may be used by the constraints (go.dev/issue/47887).
   687  	// Example: type T[P T[P]] interface{}
   688  	*dst = bindTParams(tparams)
   689  
   690  	// Signal to cycle detection that we are in a type parameter list.
   691  	// We can only be inside one type parameter list at any given time:
   692  	// function closures may appear inside a type parameter list but they
   693  	// cannot be generic, and their bodies are processed in delayed and
   694  	// sequential fashion. Note that with each new declaration, we save
   695  	// the existing environment and restore it when done; thus inTPList is
   696  	// true exactly only when we are in a specific type parameter list.
   697  	assert(!check.inTParamList)
   698  	check.inTParamList = true
   699  	defer func() {
   700  		check.inTParamList = false
   701  	}()
   702  
   703  	index := 0
   704  	for _, f := range list.List {
   705  		var bound Type
   706  		// NOTE: we may be able to assert that f.Type != nil here, but this is not
   707  		// an invariant of the AST, so we are cautious.
   708  		if f.Type != nil {
   709  			bound = check.bound(f.Type)
   710  			if isTypeParam(bound) {
   711  				// We may be able to allow this since it is now well-defined what
   712  				// the underlying type and thus type set of a type parameter is.
   713  				// But we may need some additional form of cycle detection within
   714  				// type parameter lists.
   715  				check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
   716  				bound = Typ[Invalid]
   717  			}
   718  		} else {
   719  			bound = Typ[Invalid]
   720  		}
   721  		for i := range f.Names {
   722  			tparams[index+i].bound = bound
   723  		}
   724  		index += len(f.Names)
   725  	}
   726  }
   727  
   728  func (check *Checker) bound(x ast.Expr) Type {
   729  	// A type set literal of the form ~T and A|B may only appear as constraint;
   730  	// embed it in an implicit interface so that only interface type-checking
   731  	// needs to take care of such type expressions.
   732  	wrap := false
   733  	switch op := x.(type) {
   734  	case *ast.UnaryExpr:
   735  		wrap = op.Op == token.TILDE
   736  	case *ast.BinaryExpr:
   737  		wrap = op.Op == token.OR
   738  	}
   739  	if wrap {
   740  		x = &ast.InterfaceType{Methods: &ast.FieldList{List: []*ast.Field{{Type: x}}}}
   741  		t := check.typ(x)
   742  		// mark t as implicit interface if all went well
   743  		if t, _ := t.(*Interface); t != nil {
   744  			t.implicit = true
   745  		}
   746  		return t
   747  	}
   748  	return check.typ(x)
   749  }
   750  
   751  func (check *Checker) declareTypeParam(name *ast.Ident, scopePos token.Pos) *TypeParam {
   752  	// Use Typ[Invalid] for the type constraint to ensure that a type
   753  	// is present even if the actual constraint has not been assigned
   754  	// yet.
   755  	// TODO(gri) Need to systematically review all uses of type parameter
   756  	//           constraints to make sure we don't rely on them if they
   757  	//           are not properly set yet.
   758  	tname := NewTypeName(name.Pos(), check.pkg, name.Name, nil)
   759  	tpar := check.newTypeParam(tname, Typ[Invalid]) // assigns type to tname as a side-effect
   760  	check.declare(check.scope, name, tname, scopePos)
   761  	return tpar
   762  }
   763  
   764  func (check *Checker) collectMethods(obj *TypeName) {
   765  	// get associated methods
   766  	// (Checker.collectObjects only collects methods with non-blank names;
   767  	// Checker.resolveBaseTypeName ensures that obj is not an alias name
   768  	// if it has attached methods.)
   769  	methods := check.methods[obj]
   770  	if methods == nil {
   771  		return
   772  	}
   773  	delete(check.methods, obj)
   774  	assert(!check.objMap[obj].tdecl.Assign.IsValid()) // don't use TypeName.IsAlias (requires fully set up object)
   775  
   776  	// use an objset to check for name conflicts
   777  	var mset objset
   778  
   779  	// spec: "If the base type is a struct type, the non-blank method
   780  	// and field names must be distinct."
   781  	base := asNamed(obj.typ) // shouldn't fail but be conservative
   782  	if base != nil {
   783  		assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
   784  
   785  		// See go.dev/issue/52529: we must delay the expansion of underlying here, as
   786  		// base may not be fully set-up.
   787  		check.later(func() {
   788  			check.checkFieldUniqueness(base)
   789  		}).describef(obj, "verifying field uniqueness for %v", base)
   790  
   791  		// Checker.Files may be called multiple times; additional package files
   792  		// may add methods to already type-checked types. Add pre-existing methods
   793  		// so that we can detect redeclarations.
   794  		for i := 0; i < base.NumMethods(); i++ {
   795  			m := base.Method(i)
   796  			assert(m.name != "_")
   797  			assert(mset.insert(m) == nil)
   798  		}
   799  	}
   800  
   801  	// add valid methods
   802  	for _, m := range methods {
   803  		// spec: "For a base type, the non-blank names of methods bound
   804  		// to it must be unique."
   805  		assert(m.name != "_")
   806  		if alt := mset.insert(m); alt != nil {
   807  			if alt.Pos().IsValid() {
   808  				check.errorf(m, DuplicateMethod, "method %s.%s already declared at %v", obj.Name(), m.name, alt.Pos())
   809  			} else {
   810  				check.errorf(m, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
   811  			}
   812  			continue
   813  		}
   814  
   815  		if base != nil {
   816  			base.AddMethod(m)
   817  		}
   818  	}
   819  }
   820  
   821  func (check *Checker) checkFieldUniqueness(base *Named) {
   822  	if t, _ := base.Underlying().(*Struct); t != nil {
   823  		var mset objset
   824  		for i := 0; i < base.NumMethods(); i++ {
   825  			m := base.Method(i)
   826  			assert(m.name != "_")
   827  			assert(mset.insert(m) == nil)
   828  		}
   829  
   830  		// Check that any non-blank field names of base are distinct from its
   831  		// method names.
   832  		for _, fld := range t.fields {
   833  			if fld.name != "_" {
   834  				if alt := mset.insert(fld); alt != nil {
   835  					// Struct fields should already be unique, so we should only
   836  					// encounter an alternate via collision with a method name.
   837  					_ = alt.(*Func)
   838  
   839  					// For historical consistency, we report the primary error on the
   840  					// method, and the alt decl on the field.
   841  					err := check.newError(DuplicateFieldAndMethod)
   842  					err.addf(alt, "field and method with the same name %s", fld.name)
   843  					err.addAltDecl(fld)
   844  					err.report()
   845  				}
   846  			}
   847  		}
   848  	}
   849  }
   850  
   851  func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
   852  	assert(obj.typ == nil)
   853  
   854  	// func declarations cannot use iota
   855  	assert(check.iota == nil)
   856  
   857  	sig := new(Signature)
   858  	obj.typ = sig // guard against cycles
   859  
   860  	// Avoid cycle error when referring to method while type-checking the signature.
   861  	// This avoids a nuisance in the best case (non-parameterized receiver type) and
   862  	// since the method is not a type, we get an error. If we have a parameterized
   863  	// receiver type, instantiating the receiver type leads to the instantiation of
   864  	// its methods, and we don't want a cycle error in that case.
   865  	// TODO(gri) review if this is correct and/or whether we still need this?
   866  	saved := obj.color_
   867  	obj.color_ = black
   868  	fdecl := decl.fdecl
   869  	check.funcType(sig, fdecl.Recv, fdecl.Type)
   870  	obj.color_ = saved
   871  
   872  	// Set the scope's extent to the complete "func (...) { ... }"
   873  	// so that Scope.Innermost works correctly.
   874  	sig.scope.pos = fdecl.Pos()
   875  	sig.scope.end = fdecl.End()
   876  
   877  	if fdecl.Type.TypeParams.NumFields() > 0 && fdecl.Body == nil {
   878  		check.softErrorf(fdecl.Name, BadDecl, "generic function is missing function body")
   879  	}
   880  
   881  	// function body must be type-checked after global declarations
   882  	// (functions implemented elsewhere have no body)
   883  	if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
   884  		check.later(func() {
   885  			check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
   886  		}).describef(obj, "func %s", obj.name)
   887  	}
   888  }
   889  
   890  func (check *Checker) declStmt(d ast.Decl) {
   891  	pkg := check.pkg
   892  
   893  	check.walkDecl(d, func(d decl) {
   894  		switch d := d.(type) {
   895  		case constDecl:
   896  			top := len(check.delayed)
   897  
   898  			// declare all constants
   899  			lhs := make([]*Const, len(d.spec.Names))
   900  			for i, name := range d.spec.Names {
   901  				obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
   902  				lhs[i] = obj
   903  
   904  				var init ast.Expr
   905  				if i < len(d.init) {
   906  					init = d.init[i]
   907  				}
   908  
   909  				check.constDecl(obj, d.typ, init, d.inherited)
   910  			}
   911  
   912  			// process function literals in init expressions before scope changes
   913  			check.processDelayed(top)
   914  
   915  			// spec: "The scope of a constant or variable identifier declared
   916  			// inside a function begins at the end of the ConstSpec or VarSpec
   917  			// (ShortVarDecl for short variable declarations) and ends at the
   918  			// end of the innermost containing block."
   919  			scopePos := d.spec.End()
   920  			for i, name := range d.spec.Names {
   921  				check.declare(check.scope, name, lhs[i], scopePos)
   922  			}
   923  
   924  		case varDecl:
   925  			top := len(check.delayed)
   926  
   927  			lhs0 := make([]*Var, len(d.spec.Names))
   928  			for i, name := range d.spec.Names {
   929  				lhs0[i] = newVar(LocalVar, name.Pos(), pkg, name.Name, nil)
   930  			}
   931  
   932  			// initialize all variables
   933  			for i, obj := range lhs0 {
   934  				var lhs []*Var
   935  				var init ast.Expr
   936  				switch len(d.spec.Values) {
   937  				case len(d.spec.Names):
   938  					// lhs and rhs match
   939  					init = d.spec.Values[i]
   940  				case 1:
   941  					// rhs is expected to be a multi-valued expression
   942  					lhs = lhs0
   943  					init = d.spec.Values[0]
   944  				default:
   945  					if i < len(d.spec.Values) {
   946  						init = d.spec.Values[i]
   947  					}
   948  				}
   949  				check.varDecl(obj, lhs, d.spec.Type, init)
   950  				if len(d.spec.Values) == 1 {
   951  					// If we have a single lhs variable we are done either way.
   952  					// If we have a single rhs expression, it must be a multi-
   953  					// valued expression, in which case handling the first lhs
   954  					// variable will cause all lhs variables to have a type
   955  					// assigned, and we are done as well.
   956  					if debug {
   957  						for _, obj := range lhs0 {
   958  							assert(obj.typ != nil)
   959  						}
   960  					}
   961  					break
   962  				}
   963  			}
   964  
   965  			// process function literals in init expressions before scope changes
   966  			check.processDelayed(top)
   967  
   968  			// declare all variables
   969  			// (only at this point are the variable scopes (parents) set)
   970  			scopePos := d.spec.End() // see constant declarations
   971  			for i, name := range d.spec.Names {
   972  				// see constant declarations
   973  				check.declare(check.scope, name, lhs0[i], scopePos)
   974  			}
   975  
   976  		case typeDecl:
   977  			obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
   978  			// spec: "The scope of a type identifier declared inside a function
   979  			// begins at the identifier in the TypeSpec and ends at the end of
   980  			// the innermost containing block."
   981  			scopePos := d.spec.Name.Pos()
   982  			check.declare(check.scope, d.spec.Name, obj, scopePos)
   983  			// mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
   984  			obj.setColor(grey + color(check.push(obj)))
   985  			check.typeDecl(obj, d.spec, nil)
   986  			check.pop().setColor(black)
   987  		default:
   988  			check.errorf(d.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", d.node())
   989  		}
   990  	})
   991  }
   992  

View as plain text