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  			if !obj.IsAlias() {
   205  				ndef++
   206  			}
   207  		case *Func:
   208  			// ignored for now
   209  		default:
   210  			panic("unreachable")
   211  		}
   212  	}
   213  
   214  	if check.conf._Trace {
   215  		check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
   216  		if tparCycle {
   217  			check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
   218  		} else {
   219  			check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
   220  		}
   221  		defer func() {
   222  			if valid {
   223  				check.trace(obj.Pos(), "=> cycle is valid")
   224  			} else {
   225  				check.trace(obj.Pos(), "=> error: cycle is invalid")
   226  			}
   227  		}()
   228  	}
   229  
   230  	// Cycles through type parameter lists are ok (go.dev/issue/68162).
   231  	if tparCycle {
   232  		return true
   233  	}
   234  
   235  	// A cycle involving only constants and variables is invalid but we
   236  	// ignore them here because they are reported via the initialization
   237  	// cycle check.
   238  	if nval == len(cycle) {
   239  		return true
   240  	}
   241  
   242  	// A cycle involving only types (and possibly functions) must have at least
   243  	// one type definition to be permitted: If there is no type definition, we
   244  	// have a sequence of alias type names which will expand ad infinitum.
   245  	if nval == 0 && ndef > 0 {
   246  		return true
   247  	}
   248  
   249  	check.cycleError(cycle, true)
   250  	return false
   251  }
   252  
   253  // cycleError reports a declaration cycle; cycle must not be empty.
   254  // If firstInSrc is set, the reported cycle starts with the object
   255  // with the "smallest" source position; otherwise it starts with cycle[0].
   256  func (check *Checker) cycleError(cycle []Object, firstInSrc bool) {
   257  	// name returns the (possibly qualified) object name.
   258  	// This is needed because with generic types, cycles
   259  	// may refer to imported types. See go.dev/issue/50788.
   260  	// TODO(gri) This functionality is used elsewhere. Factor it out.
   261  	name := func(obj Object) string {
   262  		// include any type arguments in the reported error message
   263  		if n := asNamed(obj.Type()); n != nil && n.inst != nil {
   264  			return TypeString(n, check.qualifier)
   265  		}
   266  		return packagePrefix(obj.Pkg(), check.qualifier) + obj.Name()
   267  	}
   268  
   269  	// Determine start index.
   270  	start := 0
   271  	if firstInSrc {
   272  		pos := cycle[0].Pos()
   273  		for i, t := range cycle[1:] {
   274  			if cmpPos(t.Pos(), pos) < 0 {
   275  				start, pos = i+1, t.Pos()
   276  			}
   277  		}
   278  	}
   279  
   280  	// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
   281  	obj := cycle[start]
   282  	tname, _ := obj.(*TypeName)
   283  	if tname != nil {
   284  		if a, ok := tname.Type().(*Alias); ok {
   285  			a.fromRHS = Typ[Invalid]
   286  		}
   287  	}
   288  
   289  	// report a more concise error for self references
   290  	if len(cycle) == 1 {
   291  		if tname != nil {
   292  			check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", name(obj))
   293  		} else {
   294  			check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", name(obj))
   295  		}
   296  		return
   297  	}
   298  
   299  	err := check.newError(InvalidDeclCycle)
   300  	if tname != nil {
   301  		err.addf(obj, "invalid recursive type %s", name(obj))
   302  	} else {
   303  		err.addf(obj, "invalid cycle in declaration of %s", name(obj))
   304  	}
   305  	// "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.
   306  	for i := range cycle {
   307  		next := cycle[(start+i+1)%len(cycle)]
   308  		err.addf(obj, "%s refers to %s", name(obj), name(next))
   309  		obj = next
   310  	}
   311  	err.report()
   312  }
   313  
   314  type (
   315  	decl interface {
   316  		node() ast.Node
   317  	}
   318  
   319  	importDecl struct{ spec *ast.ImportSpec }
   320  	constDecl  struct {
   321  		spec      *ast.ValueSpec
   322  		iota      int
   323  		typ       ast.Expr
   324  		init      []ast.Expr
   325  		inherited bool
   326  	}
   327  	varDecl  struct{ spec *ast.ValueSpec }
   328  	typeDecl struct{ spec *ast.TypeSpec }
   329  	funcDecl struct{ decl *ast.FuncDecl }
   330  )
   331  
   332  func (d importDecl) node() ast.Node { return d.spec }
   333  func (d constDecl) node() ast.Node  { return d.spec }
   334  func (d varDecl) node() ast.Node    { return d.spec }
   335  func (d typeDecl) node() ast.Node   { return d.spec }
   336  func (d funcDecl) node() ast.Node   { return d.decl }
   337  
   338  func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
   339  	for _, d := range decls {
   340  		check.walkDecl(d, f)
   341  	}
   342  }
   343  
   344  func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
   345  	switch d := d.(type) {
   346  	case *ast.BadDecl:
   347  		// ignore
   348  	case *ast.GenDecl:
   349  		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   350  		for iota, s := range d.Specs {
   351  			switch s := s.(type) {
   352  			case *ast.ImportSpec:
   353  				f(importDecl{s})
   354  			case *ast.ValueSpec:
   355  				switch d.Tok {
   356  				case token.CONST:
   357  					// determine which initialization expressions to use
   358  					inherited := true
   359  					switch {
   360  					case s.Type != nil || len(s.Values) > 0:
   361  						last = s
   362  						inherited = false
   363  					case last == nil:
   364  						last = new(ast.ValueSpec) // make sure last exists
   365  						inherited = false
   366  					}
   367  					check.arityMatch(s, last)
   368  					f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
   369  				case token.VAR:
   370  					check.arityMatch(s, nil)
   371  					f(varDecl{s})
   372  				default:
   373  					check.errorf(s, InvalidSyntaxTree, "invalid token %s", d.Tok)
   374  				}
   375  			case *ast.TypeSpec:
   376  				f(typeDecl{s})
   377  			default:
   378  				check.errorf(s, InvalidSyntaxTree, "unknown ast.Spec node %T", s)
   379  			}
   380  		}
   381  	case *ast.FuncDecl:
   382  		f(funcDecl{d})
   383  	default:
   384  		check.errorf(d, InvalidSyntaxTree, "unknown ast.Decl node %T", d)
   385  	}
   386  }
   387  
   388  func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
   389  	assert(obj.typ == nil)
   390  
   391  	// use the correct value of iota
   392  	defer func(iota constant.Value, errpos positioner) {
   393  		check.iota = iota
   394  		check.errpos = errpos
   395  	}(check.iota, check.errpos)
   396  	check.iota = obj.val
   397  	check.errpos = nil
   398  
   399  	// provide valid constant value under all circumstances
   400  	obj.val = constant.MakeUnknown()
   401  
   402  	// determine type, if any
   403  	if typ != nil {
   404  		t := check.typ(typ)
   405  		if !isConstType(t) {
   406  			// don't report an error if the type is an invalid C (defined) type
   407  			// (go.dev/issue/22090)
   408  			if isValid(t.Underlying()) {
   409  				check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
   410  			}
   411  			obj.typ = Typ[Invalid]
   412  			return
   413  		}
   414  		obj.typ = t
   415  	}
   416  
   417  	// check initialization
   418  	var x operand
   419  	if init != nil {
   420  		if inherited {
   421  			// The initialization expression is inherited from a previous
   422  			// constant declaration, and (error) positions refer to that
   423  			// expression and not the current constant declaration. Use
   424  			// the constant identifier position for any errors during
   425  			// init expression evaluation since that is all we have
   426  			// (see issues go.dev/issue/42991, go.dev/issue/42992).
   427  			check.errpos = atPos(obj.pos)
   428  		}
   429  		check.expr(nil, &x, init)
   430  	}
   431  	check.initConst(obj, &x)
   432  }
   433  
   434  func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
   435  	assert(obj.typ == nil)
   436  
   437  	// determine type, if any
   438  	if typ != nil {
   439  		obj.typ = check.varType(typ)
   440  		// We cannot spread the type to all lhs variables if there
   441  		// are more than one since that would mark them as checked
   442  		// (see Checker.objDecl) and the assignment of init exprs,
   443  		// if any, would not be checked.
   444  		//
   445  		// TODO(gri) If we have no init expr, we should distribute
   446  		// a given type otherwise we need to re-evaluate the type
   447  		// expr for each lhs variable, leading to duplicate work.
   448  	}
   449  
   450  	// check initialization
   451  	if init == nil {
   452  		if typ == nil {
   453  			// error reported before by arityMatch
   454  			obj.typ = Typ[Invalid]
   455  		}
   456  		return
   457  	}
   458  
   459  	if lhs == nil || len(lhs) == 1 {
   460  		assert(lhs == nil || lhs[0] == obj)
   461  		var x operand
   462  		check.expr(newTarget(obj.typ, obj.name), &x, init)
   463  		check.initVar(obj, &x, "variable declaration")
   464  		return
   465  	}
   466  
   467  	if debug {
   468  		// obj must be one of lhs
   469  		if !slices.Contains(lhs, obj) {
   470  			panic("inconsistent lhs")
   471  		}
   472  	}
   473  
   474  	// We have multiple variables on the lhs and one init expr.
   475  	// Make sure all variables have been given the same type if
   476  	// one was specified, otherwise they assume the type of the
   477  	// init expression values (was go.dev/issue/15755).
   478  	if typ != nil {
   479  		for _, lhs := range lhs {
   480  			lhs.typ = obj.typ
   481  		}
   482  	}
   483  
   484  	check.initVars(lhs, []ast.Expr{init}, nil)
   485  }
   486  
   487  // isImportedConstraint reports whether typ is an imported type constraint.
   488  func (check *Checker) isImportedConstraint(typ Type) bool {
   489  	named := asNamed(typ)
   490  	if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
   491  		return false
   492  	}
   493  	u, _ := named.Underlying().(*Interface)
   494  	return u != nil && !u.IsMethodSet()
   495  }
   496  
   497  func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec) {
   498  	assert(obj.typ == nil)
   499  
   500  	// Only report a version error if we have not reported one already.
   501  	versionErr := false
   502  
   503  	var rhs Type
   504  	check.later(func() {
   505  		if t := asNamed(obj.typ); t != nil { // type may be invalid
   506  			check.isBoundedType(t)
   507  		}
   508  		// If typ is local, an error was already reported where typ is specified/defined.
   509  		_ = !versionErr && check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
   510  	}).describef(obj, "isBoundedType(%s)", obj.Name())
   511  
   512  	// First type parameter, or nil.
   513  	var tparam0 *ast.Field
   514  	if tdecl.TypeParams.NumFields() > 0 {
   515  		tparam0 = tdecl.TypeParams.List[0]
   516  	}
   517  
   518  	// alias declaration
   519  	if tdecl.Assign.IsValid() {
   520  		// Report highest version requirement first so that fixing a version issue
   521  		// avoids possibly two -lang changes (first to Go 1.9 and then to Go 1.24).
   522  		if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_24, "generic type alias") {
   523  			versionErr = true
   524  		}
   525  		if !versionErr && !check.verifyVersionf(atPos(tdecl.Assign), go1_9, "type alias") {
   526  			versionErr = true
   527  		}
   528  
   529  		alias := check.newAlias(obj, nil)
   530  
   531  		// If we could not type the RHS, set it to invalid. This should
   532  		// only ever happen if we panic before setting.
   533  		defer func() {
   534  			if alias.fromRHS == nil {
   535  				alias.fromRHS = Typ[Invalid]
   536  				unalias(alias)
   537  			}
   538  		}()
   539  
   540  		// handle type parameters even if not allowed (Alias type is supported)
   541  		if tparam0 != nil {
   542  			check.openScope(tdecl, "type parameters")
   543  			defer check.closeScope()
   544  			check.collectTypeParams(&alias.tparams, tdecl.TypeParams)
   545  		}
   546  
   547  		rhs = check.declaredType(tdecl.Type, obj)
   548  		assert(rhs != nil)
   549  		alias.fromRHS = rhs
   550  
   551  		// spec: In an alias declaration the given type cannot be a type parameter declared in the same declaration."
   552  		// (see also go.dev/issue/75884, go.dev/issue/#75885)
   553  		if tpar, ok := rhs.(*TypeParam); ok && alias.tparams != nil && slices.Index(alias.tparams.list(), tpar) >= 0 {
   554  			check.error(tdecl.Type, MisplacedTypeParam, "cannot use type parameter declared in alias declaration as RHS")
   555  			alias.fromRHS = Typ[Invalid]
   556  		}
   557  
   558  		return
   559  	}
   560  
   561  	// type definition or generic type declaration
   562  	if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_18, "type parameter") {
   563  		versionErr = true
   564  	}
   565  
   566  	named := check.newNamed(obj, nil, nil)
   567  	if tdecl.TypeParams != nil {
   568  		check.openScope(tdecl, "type parameters")
   569  		defer check.closeScope()
   570  		check.collectTypeParams(&named.tparams, tdecl.TypeParams)
   571  	}
   572  
   573  	rhs = check.declaredType(tdecl.Type, obj)
   574  	assert(rhs != nil)
   575  	named.fromRHS = rhs
   576  
   577  	// spec: "In a type definition the given type cannot be a type parameter."
   578  	// (See also go.dev/issue/45639.)
   579  	if isTypeParam(rhs) {
   580  		check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
   581  		named.fromRHS = Typ[Invalid]
   582  	}
   583  }
   584  
   585  func (check *Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList) {
   586  	var tparams []*TypeParam
   587  	// Declare type parameters up-front, with empty interface as type bound.
   588  	// The scope of type parameters starts at the beginning of the type parameter
   589  	// list (so we can have mutually recursive parameterized interfaces).
   590  	scopePos := list.Pos()
   591  	for _, f := range list.List {
   592  		for _, name := range f.Names {
   593  			tparams = append(tparams, check.declareTypeParam(name, scopePos))
   594  		}
   595  	}
   596  
   597  	// Set the type parameters before collecting the type constraints because
   598  	// the parameterized type may be used by the constraints (go.dev/issue/47887).
   599  	// Example: type T[P T[P]] interface{}
   600  	*dst = bindTParams(tparams)
   601  
   602  	// Signal to cycle detection that we are in a type parameter list.
   603  	// We can only be inside one type parameter list at any given time:
   604  	// function closures may appear inside a type parameter list but they
   605  	// cannot be generic, and their bodies are processed in delayed and
   606  	// sequential fashion. Note that with each new declaration, we save
   607  	// the existing environment and restore it when done; thus inTPList is
   608  	// true exactly only when we are in a specific type parameter list.
   609  	assert(!check.inTParamList)
   610  	check.inTParamList = true
   611  	defer func() {
   612  		check.inTParamList = false
   613  	}()
   614  
   615  	index := 0
   616  	for _, f := range list.List {
   617  		var bound Type
   618  		// NOTE: we may be able to assert that f.Type != nil here, but this is not
   619  		// an invariant of the AST, so we are cautious.
   620  		if f.Type != nil {
   621  			bound = check.bound(f.Type)
   622  			if isTypeParam(bound) {
   623  				// We may be able to allow this since it is now well-defined what
   624  				// the underlying type and thus type set of a type parameter is.
   625  				// But we may need some additional form of cycle detection within
   626  				// type parameter lists.
   627  				check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
   628  				bound = Typ[Invalid]
   629  			}
   630  		} else {
   631  			bound = Typ[Invalid]
   632  		}
   633  		for i := range f.Names {
   634  			tparams[index+i].bound = bound
   635  		}
   636  		index += len(f.Names)
   637  	}
   638  }
   639  
   640  func (check *Checker) bound(x ast.Expr) Type {
   641  	// A type set literal of the form ~T and A|B may only appear as constraint;
   642  	// embed it in an implicit interface so that only interface type-checking
   643  	// needs to take care of such type expressions.
   644  	wrap := false
   645  	switch op := x.(type) {
   646  	case *ast.UnaryExpr:
   647  		wrap = op.Op == token.TILDE
   648  	case *ast.BinaryExpr:
   649  		wrap = op.Op == token.OR
   650  	}
   651  	if wrap {
   652  		x = &ast.InterfaceType{Interface: x.Pos() /* for correct trace output */, Methods: &ast.FieldList{List: []*ast.Field{{Type: x}}}}
   653  		t := check.typ(x)
   654  		// mark t as implicit interface if all went well
   655  		if t, _ := t.(*Interface); t != nil {
   656  			t.implicit = true
   657  		}
   658  		return t
   659  	}
   660  	return check.typ(x)
   661  }
   662  
   663  func (check *Checker) declareTypeParam(name *ast.Ident, scopePos token.Pos) *TypeParam {
   664  	// Use Typ[Invalid] for the type constraint to ensure that a type
   665  	// is present even if the actual constraint has not been assigned
   666  	// yet.
   667  	// TODO(gri) Need to systematically review all uses of type parameter
   668  	//           constraints to make sure we don't rely on them if they
   669  	//           are not properly set yet.
   670  	tname := NewTypeName(name.Pos(), check.pkg, name.Name, nil)
   671  	tpar := check.newTypeParam(tname, Typ[Invalid]) // assigns type to tname as a side-effect
   672  	check.declare(check.scope, name, tname, scopePos)
   673  	return tpar
   674  }
   675  
   676  func (check *Checker) collectMethods(obj *TypeName) {
   677  	// get associated methods
   678  	// (Checker.collectObjects only collects methods with non-blank names;
   679  	// Checker.resolveBaseTypeName ensures that obj is not an alias name
   680  	// if it has attached methods.)
   681  	methods := check.methods[obj]
   682  	if methods == nil {
   683  		return
   684  	}
   685  	delete(check.methods, obj)
   686  	assert(!check.objMap[obj].tdecl.Assign.IsValid()) // don't use TypeName.IsAlias (requires fully set up object)
   687  
   688  	// use an objset to check for name conflicts
   689  	var mset objset
   690  
   691  	// spec: "If the base type is a struct type, the non-blank method
   692  	// and field names must be distinct."
   693  	base := asNamed(obj.typ) // shouldn't fail but be conservative
   694  	if base != nil {
   695  		assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
   696  
   697  		// See go.dev/issue/52529: we must delay the expansion of underlying here, as
   698  		// base may not be fully set-up.
   699  		check.later(func() {
   700  			check.checkFieldUniqueness(base)
   701  		}).describef(obj, "verifying field uniqueness for %v", base)
   702  
   703  		// Checker.Files may be called multiple times; additional package files
   704  		// may add methods to already type-checked types. Add pre-existing methods
   705  		// so that we can detect redeclarations.
   706  		for i := 0; i < base.NumMethods(); i++ {
   707  			m := base.Method(i)
   708  			assert(m.name != "_")
   709  			assert(mset.insert(m) == nil)
   710  		}
   711  	}
   712  
   713  	// add valid methods
   714  	for _, m := range methods {
   715  		// spec: "For a base type, the non-blank names of methods bound
   716  		// to it must be unique."
   717  		assert(m.name != "_")
   718  		if alt := mset.insert(m); alt != nil {
   719  			if alt.Pos().IsValid() {
   720  				check.errorf(m, DuplicateMethod, "method %s.%s already declared at %v", obj.Name(), m.name, alt.Pos())
   721  			} else {
   722  				check.errorf(m, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
   723  			}
   724  			continue
   725  		}
   726  
   727  		if base != nil {
   728  			base.AddMethod(m)
   729  		}
   730  	}
   731  }
   732  
   733  func (check *Checker) checkFieldUniqueness(base *Named) {
   734  	if t, _ := base.Underlying().(*Struct); t != nil {
   735  		var mset objset
   736  		for i := 0; i < base.NumMethods(); i++ {
   737  			m := base.Method(i)
   738  			assert(m.name != "_")
   739  			assert(mset.insert(m) == nil)
   740  		}
   741  
   742  		// Check that any non-blank field names of base are distinct from its
   743  		// method names.
   744  		for _, fld := range t.fields {
   745  			if fld.name != "_" {
   746  				if alt := mset.insert(fld); alt != nil {
   747  					// Struct fields should already be unique, so we should only
   748  					// encounter an alternate via collision with a method name.
   749  					_ = alt.(*Func)
   750  
   751  					// For historical consistency, we report the primary error on the
   752  					// method, and the alt decl on the field.
   753  					err := check.newError(DuplicateFieldAndMethod)
   754  					err.addf(alt, "field and method with the same name %s", fld.name)
   755  					err.addAltDecl(fld)
   756  					err.report()
   757  				}
   758  			}
   759  		}
   760  	}
   761  }
   762  
   763  func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
   764  	assert(obj.typ == nil)
   765  
   766  	// func declarations cannot use iota
   767  	assert(check.iota == nil)
   768  
   769  	sig := new(Signature)
   770  	obj.typ = sig // guard against cycles
   771  
   772  	fdecl := decl.fdecl
   773  	check.funcType(sig, fdecl.Recv, fdecl.Type)
   774  
   775  	// types2 handles go:nointerface pragma here by setting obj.nointerface.
   776  	// go/types currently doesn't handle pragmas.
   777  
   778  	// Set the scope's extent to the complete "func (...) { ... }"
   779  	// so that Scope.Innermost works correctly.
   780  	sig.scope.pos = fdecl.Pos()
   781  	sig.scope.end = fdecl.End()
   782  
   783  	if fdecl.Type.TypeParams.NumFields() > 0 && fdecl.Body == nil {
   784  		check.softErrorf(fdecl.Name, BadDecl, "generic function is missing function body")
   785  	}
   786  
   787  	// function body must be type-checked after global declarations
   788  	// (functions implemented elsewhere have no body)
   789  	if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
   790  		check.later(func() {
   791  			check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
   792  		}).describef(obj, "func %s", obj.name)
   793  	}
   794  }
   795  
   796  func (check *Checker) declStmt(d ast.Decl) {
   797  	pkg := check.pkg
   798  
   799  	check.walkDecl(d, func(d decl) {
   800  		switch d := d.(type) {
   801  		case constDecl:
   802  			top := len(check.delayed)
   803  
   804  			// declare all constants
   805  			lhs := make([]*Const, len(d.spec.Names))
   806  			for i, name := range d.spec.Names {
   807  				obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
   808  				lhs[i] = obj
   809  
   810  				var init ast.Expr
   811  				if i < len(d.init) {
   812  					init = d.init[i]
   813  				}
   814  
   815  				check.constDecl(obj, d.typ, init, d.inherited)
   816  			}
   817  			if !d.inherited && len(d.init) > len(d.spec.Names) {
   818  				prev := check.iota
   819  				check.iota = constant.MakeInt64(int64(d.iota))
   820  				check.use(d.init[len(d.spec.Names):]...)
   821  				check.iota = prev
   822  			}
   823  
   824  			// process function literals in init expressions before scope changes
   825  			check.processDelayed(top)
   826  
   827  			// spec: "The scope of a constant or variable identifier declared
   828  			// inside a function begins at the end of the ConstSpec or VarSpec
   829  			// (ShortVarDecl for short variable declarations) and ends at the
   830  			// end of the innermost containing block."
   831  			scopePos := d.spec.End()
   832  			for i, name := range d.spec.Names {
   833  				check.declare(check.scope, name, lhs[i], scopePos)
   834  			}
   835  
   836  		case varDecl:
   837  			top := len(check.delayed)
   838  
   839  			lhs0 := make([]*Var, len(d.spec.Names))
   840  			for i, name := range d.spec.Names {
   841  				lhs0[i] = newVar(LocalVar, name.Pos(), pkg, name.Name, nil)
   842  			}
   843  
   844  			// initialize all variables
   845  			for i, obj := range lhs0 {
   846  				var lhs []*Var
   847  				var init ast.Expr
   848  				switch len(d.spec.Values) {
   849  				case len(d.spec.Names):
   850  					// lhs and rhs match
   851  					init = d.spec.Values[i]
   852  				case 1:
   853  					// rhs is expected to be a multi-valued expression
   854  					lhs = lhs0
   855  					init = d.spec.Values[0]
   856  				default:
   857  					if i < len(d.spec.Values) {
   858  						init = d.spec.Values[i]
   859  					}
   860  				}
   861  				check.varDecl(obj, lhs, d.spec.Type, init)
   862  				if len(d.spec.Values) == 1 {
   863  					// If we have a single lhs variable we are done either way.
   864  					// If we have a single rhs expression, it must be a multi-
   865  					// valued expression, in which case handling the first lhs
   866  					// variable will cause all lhs variables to have a type
   867  					// assigned, and we are done as well.
   868  					if debug {
   869  						for _, obj := range lhs0 {
   870  							assert(obj.typ != nil)
   871  						}
   872  					}
   873  					break
   874  				}
   875  			}
   876  			if len(d.spec.Values) > len(d.spec.Names) {
   877  				check.use(d.spec.Values[len(d.spec.Names):]...)
   878  			}
   879  
   880  			// process function literals in init expressions before scope changes
   881  			check.processDelayed(top)
   882  
   883  			// declare all variables
   884  			// (only at this point are the variable scopes (parents) set)
   885  			scopePos := d.spec.End() // see constant declarations
   886  			for i, name := range d.spec.Names {
   887  				// see constant declarations
   888  				check.declare(check.scope, name, lhs0[i], scopePos)
   889  			}
   890  
   891  		case typeDecl:
   892  			obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
   893  			// spec: "The scope of a type identifier declared inside a function
   894  			// begins at the identifier in the TypeSpec and ends at the end of
   895  			// the innermost containing block."
   896  			scopePos := d.spec.Name.Pos()
   897  			check.declare(check.scope, d.spec.Name, obj, scopePos)
   898  			check.push(obj) // mark as grey
   899  			check.typeDecl(obj, d.spec)
   900  			check.pop()
   901  		default:
   902  			check.errorf(d.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", d.node())
   903  		}
   904  	})
   905  }
   906  

View as plain text