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

View as plain text