decl.go raw

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