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

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

View as plain text