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

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

View as plain text