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

View as plain text