...

Source file src/cmd/compile/internal/types2/decl.go

Documentation: cmd/compile/internal/types2

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

View as plain text