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

View as plain text