Source file src/go/types/decl.go

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

View as plain text