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

View as plain text