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

View as plain text