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

View as plain text