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

View as plain text