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

View as plain text