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/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 {
   325  		if check.conf._EnableAlias {
   326  			if a, ok := tname.Type().(*Alias); ok {
   327  				a.fromRHS = Typ[Invalid]
   328  			}
   329  		} else {
   330  			if tname.IsAlias() {
   331  				check.validAlias(tname, Typ[Invalid])
   332  			}
   333  		}
   334  	}
   335  
   336  	// report a more concise error for self references
   337  	if len(cycle) == 1 {
   338  		if tname != nil {
   339  			check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", name(obj))
   340  		} else {
   341  			check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", name(obj))
   342  		}
   343  		return
   344  	}
   345  
   346  	err := check.newError(InvalidDeclCycle)
   347  	if tname != nil {
   348  		err.addf(obj, "invalid recursive type %s", name(obj))
   349  	} else {
   350  		err.addf(obj, "invalid cycle in declaration of %s", name(obj))
   351  	}
   352  	// "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.
   353  	for i := range cycle {
   354  		next := cycle[(start+i+1)%len(cycle)]
   355  		err.addf(obj, "%s refers to %s", name(obj), name(next))
   356  		obj = next
   357  	}
   358  	err.report()
   359  }
   360  
   361  // firstInSrc reports the index of the object with the "smallest"
   362  // source position in path. path must not be empty.
   363  func firstInSrc(path []Object) int {
   364  	fst, pos := 0, path[0].Pos()
   365  	for i, t := range path[1:] {
   366  		if cmpPos(t.Pos(), pos) < 0 {
   367  			fst, pos = i+1, t.Pos()
   368  		}
   369  	}
   370  	return fst
   371  }
   372  
   373  type (
   374  	decl interface {
   375  		node() ast.Node
   376  	}
   377  
   378  	importDecl struct{ spec *ast.ImportSpec }
   379  	constDecl  struct {
   380  		spec      *ast.ValueSpec
   381  		iota      int
   382  		typ       ast.Expr
   383  		init      []ast.Expr
   384  		inherited bool
   385  	}
   386  	varDecl  struct{ spec *ast.ValueSpec }
   387  	typeDecl struct{ spec *ast.TypeSpec }
   388  	funcDecl struct{ decl *ast.FuncDecl }
   389  )
   390  
   391  func (d importDecl) node() ast.Node { return d.spec }
   392  func (d constDecl) node() ast.Node  { return d.spec }
   393  func (d varDecl) node() ast.Node    { return d.spec }
   394  func (d typeDecl) node() ast.Node   { return d.spec }
   395  func (d funcDecl) node() ast.Node   { return d.decl }
   396  
   397  func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
   398  	for _, d := range decls {
   399  		check.walkDecl(d, f)
   400  	}
   401  }
   402  
   403  func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
   404  	switch d := d.(type) {
   405  	case *ast.BadDecl:
   406  		// ignore
   407  	case *ast.GenDecl:
   408  		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   409  		for iota, s := range d.Specs {
   410  			switch s := s.(type) {
   411  			case *ast.ImportSpec:
   412  				f(importDecl{s})
   413  			case *ast.ValueSpec:
   414  				switch d.Tok {
   415  				case token.CONST:
   416  					// determine which initialization expressions to use
   417  					inherited := true
   418  					switch {
   419  					case s.Type != nil || len(s.Values) > 0:
   420  						last = s
   421  						inherited = false
   422  					case last == nil:
   423  						last = new(ast.ValueSpec) // make sure last exists
   424  						inherited = false
   425  					}
   426  					check.arityMatch(s, last)
   427  					f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
   428  				case token.VAR:
   429  					check.arityMatch(s, nil)
   430  					f(varDecl{s})
   431  				default:
   432  					check.errorf(s, InvalidSyntaxTree, "invalid token %s", d.Tok)
   433  				}
   434  			case *ast.TypeSpec:
   435  				f(typeDecl{s})
   436  			default:
   437  				check.errorf(s, InvalidSyntaxTree, "unknown ast.Spec node %T", s)
   438  			}
   439  		}
   440  	case *ast.FuncDecl:
   441  		f(funcDecl{d})
   442  	default:
   443  		check.errorf(d, InvalidSyntaxTree, "unknown ast.Decl node %T", d)
   444  	}
   445  }
   446  
   447  func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
   448  	assert(obj.typ == nil)
   449  
   450  	// use the correct value of iota
   451  	defer func(iota constant.Value, errpos positioner) {
   452  		check.iota = iota
   453  		check.errpos = errpos
   454  	}(check.iota, check.errpos)
   455  	check.iota = obj.val
   456  	check.errpos = nil
   457  
   458  	// provide valid constant value under all circumstances
   459  	obj.val = constant.MakeUnknown()
   460  
   461  	// determine type, if any
   462  	if typ != nil {
   463  		t := check.typ(typ)
   464  		if !isConstType(t) {
   465  			// don't report an error if the type is an invalid C (defined) type
   466  			// (go.dev/issue/22090)
   467  			if isValid(under(t)) {
   468  				check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
   469  			}
   470  			obj.typ = Typ[Invalid]
   471  			return
   472  		}
   473  		obj.typ = t
   474  	}
   475  
   476  	// check initialization
   477  	var x operand
   478  	if init != nil {
   479  		if inherited {
   480  			// The initialization expression is inherited from a previous
   481  			// constant declaration, and (error) positions refer to that
   482  			// expression and not the current constant declaration. Use
   483  			// the constant identifier position for any errors during
   484  			// init expression evaluation since that is all we have
   485  			// (see issues go.dev/issue/42991, go.dev/issue/42992).
   486  			check.errpos = atPos(obj.pos)
   487  		}
   488  		check.expr(nil, &x, init)
   489  	}
   490  	check.initConst(obj, &x)
   491  }
   492  
   493  func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
   494  	assert(obj.typ == nil)
   495  
   496  	// determine type, if any
   497  	if typ != nil {
   498  		obj.typ = check.varType(typ)
   499  		// We cannot spread the type to all lhs variables if there
   500  		// are more than one since that would mark them as checked
   501  		// (see Checker.objDecl) and the assignment of init exprs,
   502  		// if any, would not be checked.
   503  		//
   504  		// TODO(gri) If we have no init expr, we should distribute
   505  		// a given type otherwise we need to re-evaluate the type
   506  		// expr for each lhs variable, leading to duplicate work.
   507  	}
   508  
   509  	// check initialization
   510  	if init == nil {
   511  		if typ == nil {
   512  			// error reported before by arityMatch
   513  			obj.typ = Typ[Invalid]
   514  		}
   515  		return
   516  	}
   517  
   518  	if lhs == nil || len(lhs) == 1 {
   519  		assert(lhs == nil || lhs[0] == obj)
   520  		var x operand
   521  		check.expr(newTarget(obj.typ, obj.name), &x, init)
   522  		check.initVar(obj, &x, "variable declaration")
   523  		return
   524  	}
   525  
   526  	if debug {
   527  		// obj must be one of lhs
   528  		if !slices.Contains(lhs, obj) {
   529  			panic("inconsistent lhs")
   530  		}
   531  	}
   532  
   533  	// We have multiple variables on the lhs and one init expr.
   534  	// Make sure all variables have been given the same type if
   535  	// one was specified, otherwise they assume the type of the
   536  	// init expression values (was go.dev/issue/15755).
   537  	if typ != nil {
   538  		for _, lhs := range lhs {
   539  			lhs.typ = obj.typ
   540  		}
   541  	}
   542  
   543  	check.initVars(lhs, []ast.Expr{init}, nil)
   544  }
   545  
   546  // isImportedConstraint reports whether typ is an imported type constraint.
   547  func (check *Checker) isImportedConstraint(typ Type) bool {
   548  	named := asNamed(typ)
   549  	if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
   550  		return false
   551  	}
   552  	u, _ := named.under().(*Interface)
   553  	return u != nil && !u.IsMethodSet()
   554  }
   555  
   556  func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *TypeName) {
   557  	assert(obj.typ == nil)
   558  
   559  	// Only report a version error if we have not reported one already.
   560  	versionErr := false
   561  
   562  	var rhs Type
   563  	check.later(func() {
   564  		if t := asNamed(obj.typ); t != nil { // type may be invalid
   565  			check.validType(t)
   566  		}
   567  		// If typ is local, an error was already reported where typ is specified/defined.
   568  		_ = !versionErr && check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
   569  	}).describef(obj, "validType(%s)", obj.Name())
   570  
   571  	// First type parameter, or nil.
   572  	var tparam0 *ast.Field
   573  	if tdecl.TypeParams.NumFields() > 0 {
   574  		tparam0 = tdecl.TypeParams.List[0]
   575  	}
   576  
   577  	// alias declaration
   578  	if tdecl.Assign.IsValid() {
   579  		// Report highest version requirement first so that fixing a version issue
   580  		// avoids possibly two -lang changes (first to Go 1.9 and then to Go 1.23).
   581  		if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_23, "generic type alias") {
   582  			versionErr = true
   583  		}
   584  		if !versionErr && !check.verifyVersionf(atPos(tdecl.Assign), go1_9, "type alias") {
   585  			versionErr = true
   586  		}
   587  
   588  		if check.conf._EnableAlias {
   589  			alias := check.newAlias(obj, nil)
   590  			setDefType(def, alias)
   591  
   592  			// If we could not type the RHS, set it to invalid. This should
   593  			// only ever happen if we panic before setting.
   594  			defer func() {
   595  				if alias.fromRHS == nil {
   596  					alias.fromRHS = Typ[Invalid]
   597  					unalias(alias)
   598  				}
   599  			}()
   600  
   601  			// handle type parameters even if not allowed (Alias type is supported)
   602  			if tparam0 != nil {
   603  				if !versionErr && !buildcfg.Experiment.AliasTypeParams {
   604  					check.error(tdecl, UnsupportedFeature, "generic type alias requires GOEXPERIMENT=aliastypeparams")
   605  					versionErr = true
   606  				}
   607  				check.openScope(tdecl, "type parameters")
   608  				defer check.closeScope()
   609  				check.collectTypeParams(&alias.tparams, tdecl.TypeParams)
   610  			}
   611  
   612  			rhs = check.definedType(tdecl.Type, obj)
   613  			assert(rhs != nil)
   614  
   615  			alias.fromRHS = rhs
   616  			unalias(alias) // resolve alias.actual
   617  		} else {
   618  			// With Go1.23, the default behavior is to use Alias nodes,
   619  			// reflected by check.enableAlias. Signal non-default behavior.
   620  			//
   621  			// TODO(gri) Testing runs tests in both modes. Do we need to exclude
   622  			//           tracking of non-default behavior for tests?
   623  			gotypesalias.IncNonDefault()
   624  
   625  			if !versionErr && tparam0 != nil {
   626  				check.error(tdecl, UnsupportedFeature, "generic type alias requires GODEBUG=gotypesalias=1 or unset")
   627  				versionErr = true
   628  			}
   629  
   630  			check.brokenAlias(obj)
   631  			rhs = check.typ(tdecl.Type)
   632  			check.validAlias(obj, rhs)
   633  		}
   634  		return
   635  	}
   636  
   637  	// type definition or generic type declaration
   638  	if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_18, "type parameter") {
   639  		versionErr = true
   640  	}
   641  
   642  	named := check.newNamed(obj, nil, nil)
   643  	setDefType(def, named)
   644  
   645  	if tdecl.TypeParams != nil {
   646  		check.openScope(tdecl, "type parameters")
   647  		defer check.closeScope()
   648  		check.collectTypeParams(&named.tparams, tdecl.TypeParams)
   649  	}
   650  
   651  	// determine underlying type of named
   652  	rhs = check.definedType(tdecl.Type, obj)
   653  	assert(rhs != nil)
   654  	named.fromRHS = rhs
   655  
   656  	// If the underlying type was not set while type-checking the right-hand
   657  	// side, it is invalid and an error should have been reported elsewhere.
   658  	if named.underlying == nil {
   659  		named.underlying = Typ[Invalid]
   660  	}
   661  
   662  	// Disallow a lone type parameter as the RHS of a type declaration (go.dev/issue/45639).
   663  	// We don't need this restriction anymore if we make the underlying type of a type
   664  	// parameter its constraint interface: if the RHS is a lone type parameter, we will
   665  	// use its underlying type (like we do for any RHS in a type declaration), and its
   666  	// underlying type is an interface and the type declaration is well defined.
   667  	if isTypeParam(rhs) {
   668  		check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
   669  		named.underlying = 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.under().(*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