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  		// include any type arguments in the reported error message
   261  		if n := asNamed(obj.Type()); n != nil && n.inst != nil {
   262  			return TypeString(n, check.qualifier)
   263  		}
   264  		return packagePrefix(obj.Pkg(), check.qualifier) + obj.Name()
   265  	}
   266  
   267  	// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
   268  	obj := cycle[start]
   269  	tname, _ := obj.(*TypeName)
   270  	if tname != nil {
   271  		if a, ok := tname.Type().(*Alias); ok {
   272  			a.fromRHS = Typ[Invalid]
   273  		}
   274  	}
   275  
   276  	// report a more concise error for self references
   277  	if len(cycle) == 1 {
   278  		if tname != nil {
   279  			check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", name(obj))
   280  		} else {
   281  			check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", name(obj))
   282  		}
   283  		return
   284  	}
   285  
   286  	err := check.newError(InvalidDeclCycle)
   287  	if tname != nil {
   288  		err.addf(obj, "invalid recursive type %s", name(obj))
   289  	} else {
   290  		err.addf(obj, "invalid cycle in declaration of %s", name(obj))
   291  	}
   292  	// "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.
   293  	for i := range cycle {
   294  		next := cycle[(start+i+1)%len(cycle)]
   295  		err.addf(obj, "%s refers to %s", name(obj), name(next))
   296  		obj = next
   297  	}
   298  	err.report()
   299  }
   300  
   301  // firstInSrc reports the index of the object with the "smallest"
   302  // source position in path. path must not be empty.
   303  func firstInSrc(path []Object) int {
   304  	fst, pos := 0, path[0].Pos()
   305  	for i, t := range path[1:] {
   306  		if cmpPos(t.Pos(), pos) < 0 {
   307  			fst, pos = i+1, t.Pos()
   308  		}
   309  	}
   310  	return fst
   311  }
   312  
   313  type (
   314  	decl interface {
   315  		node() ast.Node
   316  	}
   317  
   318  	importDecl struct{ spec *ast.ImportSpec }
   319  	constDecl  struct {
   320  		spec      *ast.ValueSpec
   321  		iota      int
   322  		typ       ast.Expr
   323  		init      []ast.Expr
   324  		inherited bool
   325  	}
   326  	varDecl  struct{ spec *ast.ValueSpec }
   327  	typeDecl struct{ spec *ast.TypeSpec }
   328  	funcDecl struct{ decl *ast.FuncDecl }
   329  )
   330  
   331  func (d importDecl) node() ast.Node { return d.spec }
   332  func (d constDecl) node() ast.Node  { return d.spec }
   333  func (d varDecl) node() ast.Node    { return d.spec }
   334  func (d typeDecl) node() ast.Node   { return d.spec }
   335  func (d funcDecl) node() ast.Node   { return d.decl }
   336  
   337  func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
   338  	for _, d := range decls {
   339  		check.walkDecl(d, f)
   340  	}
   341  }
   342  
   343  func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
   344  	switch d := d.(type) {
   345  	case *ast.BadDecl:
   346  		// ignore
   347  	case *ast.GenDecl:
   348  		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   349  		for iota, s := range d.Specs {
   350  			switch s := s.(type) {
   351  			case *ast.ImportSpec:
   352  				f(importDecl{s})
   353  			case *ast.ValueSpec:
   354  				switch d.Tok {
   355  				case token.CONST:
   356  					// determine which initialization expressions to use
   357  					inherited := true
   358  					switch {
   359  					case s.Type != nil || len(s.Values) > 0:
   360  						last = s
   361  						inherited = false
   362  					case last == nil:
   363  						last = new(ast.ValueSpec) // make sure last exists
   364  						inherited = false
   365  					}
   366  					check.arityMatch(s, last)
   367  					f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
   368  				case token.VAR:
   369  					check.arityMatch(s, nil)
   370  					f(varDecl{s})
   371  				default:
   372  					check.errorf(s, InvalidSyntaxTree, "invalid token %s", d.Tok)
   373  				}
   374  			case *ast.TypeSpec:
   375  				f(typeDecl{s})
   376  			default:
   377  				check.errorf(s, InvalidSyntaxTree, "unknown ast.Spec node %T", s)
   378  			}
   379  		}
   380  	case *ast.FuncDecl:
   381  		f(funcDecl{d})
   382  	default:
   383  		check.errorf(d, InvalidSyntaxTree, "unknown ast.Decl node %T", d)
   384  	}
   385  }
   386  
   387  func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
   388  	assert(obj.typ == nil)
   389  
   390  	// use the correct value of iota
   391  	defer func(iota constant.Value, errpos positioner) {
   392  		check.iota = iota
   393  		check.errpos = errpos
   394  	}(check.iota, check.errpos)
   395  	check.iota = obj.val
   396  	check.errpos = nil
   397  
   398  	// provide valid constant value under all circumstances
   399  	obj.val = constant.MakeUnknown()
   400  
   401  	// determine type, if any
   402  	if typ != nil {
   403  		t := check.typ(typ)
   404  		if !isConstType(t) {
   405  			// don't report an error if the type is an invalid C (defined) type
   406  			// (go.dev/issue/22090)
   407  			if isValid(t.Underlying()) {
   408  				check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
   409  			}
   410  			obj.typ = Typ[Invalid]
   411  			return
   412  		}
   413  		obj.typ = t
   414  	}
   415  
   416  	// check initialization
   417  	var x operand
   418  	if init != nil {
   419  		if inherited {
   420  			// The initialization expression is inherited from a previous
   421  			// constant declaration, and (error) positions refer to that
   422  			// expression and not the current constant declaration. Use
   423  			// the constant identifier position for any errors during
   424  			// init expression evaluation since that is all we have
   425  			// (see issues go.dev/issue/42991, go.dev/issue/42992).
   426  			check.errpos = atPos(obj.pos)
   427  		}
   428  		check.expr(nil, &x, init)
   429  	}
   430  	check.initConst(obj, &x)
   431  }
   432  
   433  func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
   434  	assert(obj.typ == nil)
   435  
   436  	// determine type, if any
   437  	if typ != nil {
   438  		obj.typ = check.varType(typ)
   439  		// We cannot spread the type to all lhs variables if there
   440  		// are more than one since that would mark them as checked
   441  		// (see Checker.objDecl) and the assignment of init exprs,
   442  		// if any, would not be checked.
   443  		//
   444  		// TODO(gri) If we have no init expr, we should distribute
   445  		// a given type otherwise we need to re-evaluate the type
   446  		// expr for each lhs variable, leading to duplicate work.
   447  	}
   448  
   449  	// check initialization
   450  	if init == nil {
   451  		if typ == nil {
   452  			// error reported before by arityMatch
   453  			obj.typ = Typ[Invalid]
   454  		}
   455  		return
   456  	}
   457  
   458  	if lhs == nil || len(lhs) == 1 {
   459  		assert(lhs == nil || lhs[0] == obj)
   460  		var x operand
   461  		check.expr(newTarget(obj.typ, obj.name), &x, init)
   462  		check.initVar(obj, &x, "variable declaration")
   463  		return
   464  	}
   465  
   466  	if debug {
   467  		// obj must be one of lhs
   468  		if !slices.Contains(lhs, obj) {
   469  			panic("inconsistent lhs")
   470  		}
   471  	}
   472  
   473  	// We have multiple variables on the lhs and one init expr.
   474  	// Make sure all variables have been given the same type if
   475  	// one was specified, otherwise they assume the type of the
   476  	// init expression values (was go.dev/issue/15755).
   477  	if typ != nil {
   478  		for _, lhs := range lhs {
   479  			lhs.typ = obj.typ
   480  		}
   481  	}
   482  
   483  	check.initVars(lhs, []ast.Expr{init}, nil)
   484  }
   485  
   486  // isImportedConstraint reports whether typ is an imported type constraint.
   487  func (check *Checker) isImportedConstraint(typ Type) bool {
   488  	named := asNamed(typ)
   489  	if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
   490  		return false
   491  	}
   492  	u, _ := named.Underlying().(*Interface)
   493  	return u != nil && !u.IsMethodSet()
   494  }
   495  
   496  func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec) {
   497  	assert(obj.typ == nil)
   498  
   499  	// Only report a version error if we have not reported one already.
   500  	versionErr := false
   501  
   502  	var rhs Type
   503  	check.later(func() {
   504  		if t := asNamed(obj.typ); t != nil { // type may be invalid
   505  			check.validType(t)
   506  		}
   507  		// If typ is local, an error was already reported where typ is specified/defined.
   508  		_ = !versionErr && check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
   509  	}).describef(obj, "validType(%s)", obj.Name())
   510  
   511  	// First type parameter, or nil.
   512  	var tparam0 *ast.Field
   513  	if tdecl.TypeParams.NumFields() > 0 {
   514  		tparam0 = tdecl.TypeParams.List[0]
   515  	}
   516  
   517  	// alias declaration
   518  	if tdecl.Assign.IsValid() {
   519  		// Report highest version requirement first so that fixing a version issue
   520  		// avoids possibly two -lang changes (first to Go 1.9 and then to Go 1.23).
   521  		if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_23, "generic type alias") {
   522  			versionErr = true
   523  		}
   524  		if !versionErr && !check.verifyVersionf(atPos(tdecl.Assign), go1_9, "type alias") {
   525  			versionErr = true
   526  		}
   527  
   528  		alias := check.newAlias(obj, nil)
   529  
   530  		// If we could not type the RHS, set it to invalid. This should
   531  		// only ever happen if we panic before setting.
   532  		defer func() {
   533  			if alias.fromRHS == nil {
   534  				alias.fromRHS = Typ[Invalid]
   535  				unalias(alias)
   536  			}
   537  		}()
   538  
   539  		// handle type parameters even if not allowed (Alias type is supported)
   540  		if tparam0 != nil {
   541  			check.openScope(tdecl, "type parameters")
   542  			defer check.closeScope()
   543  			check.collectTypeParams(&alias.tparams, tdecl.TypeParams)
   544  		}
   545  
   546  		rhs = check.declaredType(tdecl.Type, obj)
   547  		assert(rhs != nil)
   548  		alias.fromRHS = rhs
   549  
   550  		// spec: In an alias declaration the given type cannot be a type parameter declared in the same declaration."
   551  		// (see also go.dev/issue/75884, go.dev/issue/#75885)
   552  		if tpar, ok := rhs.(*TypeParam); ok && alias.tparams != nil && slices.Index(alias.tparams.list(), tpar) >= 0 {
   553  			check.error(tdecl.Type, MisplacedTypeParam, "cannot use type parameter declared in alias declaration as RHS")
   554  			alias.fromRHS = Typ[Invalid]
   555  		}
   556  
   557  		return
   558  	}
   559  
   560  	// type definition or generic type declaration
   561  	if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_18, "type parameter") {
   562  		versionErr = true
   563  	}
   564  
   565  	named := check.newNamed(obj, nil, nil)
   566  	if tdecl.TypeParams != nil {
   567  		check.openScope(tdecl, "type parameters")
   568  		defer check.closeScope()
   569  		check.collectTypeParams(&named.tparams, tdecl.TypeParams)
   570  	}
   571  
   572  	rhs = check.declaredType(tdecl.Type, obj)
   573  	assert(rhs != nil)
   574  	named.fromRHS = rhs
   575  
   576  	// spec: "In a type definition the given type cannot be a type parameter."
   577  	// (See also go.dev/issue/45639.)
   578  	if isTypeParam(rhs) {
   579  		check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
   580  		named.fromRHS = Typ[Invalid]
   581  	}
   582  }
   583  
   584  func (check *Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList) {
   585  	var tparams []*TypeParam
   586  	// Declare type parameters up-front, with empty interface as type bound.
   587  	// The scope of type parameters starts at the beginning of the type parameter
   588  	// list (so we can have mutually recursive parameterized interfaces).
   589  	scopePos := list.Pos()
   590  	for _, f := range list.List {
   591  		for _, name := range f.Names {
   592  			tparams = append(tparams, check.declareTypeParam(name, scopePos))
   593  		}
   594  	}
   595  
   596  	// Set the type parameters before collecting the type constraints because
   597  	// the parameterized type may be used by the constraints (go.dev/issue/47887).
   598  	// Example: type T[P T[P]] interface{}
   599  	*dst = bindTParams(tparams)
   600  
   601  	// Signal to cycle detection that we are in a type parameter list.
   602  	// We can only be inside one type parameter list at any given time:
   603  	// function closures may appear inside a type parameter list but they
   604  	// cannot be generic, and their bodies are processed in delayed and
   605  	// sequential fashion. Note that with each new declaration, we save
   606  	// the existing environment and restore it when done; thus inTPList is
   607  	// true exactly only when we are in a specific type parameter list.
   608  	assert(!check.inTParamList)
   609  	check.inTParamList = true
   610  	defer func() {
   611  		check.inTParamList = false
   612  	}()
   613  
   614  	index := 0
   615  	for _, f := range list.List {
   616  		var bound Type
   617  		// NOTE: we may be able to assert that f.Type != nil here, but this is not
   618  		// an invariant of the AST, so we are cautious.
   619  		if f.Type != nil {
   620  			bound = check.bound(f.Type)
   621  			if isTypeParam(bound) {
   622  				// We may be able to allow this since it is now well-defined what
   623  				// the underlying type and thus type set of a type parameter is.
   624  				// But we may need some additional form of cycle detection within
   625  				// type parameter lists.
   626  				check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
   627  				bound = Typ[Invalid]
   628  			}
   629  		} else {
   630  			bound = Typ[Invalid]
   631  		}
   632  		for i := range f.Names {
   633  			tparams[index+i].bound = bound
   634  		}
   635  		index += len(f.Names)
   636  	}
   637  }
   638  
   639  func (check *Checker) bound(x ast.Expr) Type {
   640  	// A type set literal of the form ~T and A|B may only appear as constraint;
   641  	// embed it in an implicit interface so that only interface type-checking
   642  	// needs to take care of such type expressions.
   643  	wrap := false
   644  	switch op := x.(type) {
   645  	case *ast.UnaryExpr:
   646  		wrap = op.Op == token.TILDE
   647  	case *ast.BinaryExpr:
   648  		wrap = op.Op == token.OR
   649  	}
   650  	if wrap {
   651  		x = &ast.InterfaceType{Methods: &ast.FieldList{List: []*ast.Field{{Type: x}}}}
   652  		t := check.typ(x)
   653  		// mark t as implicit interface if all went well
   654  		if t, _ := t.(*Interface); t != nil {
   655  			t.implicit = true
   656  		}
   657  		return t
   658  	}
   659  	return check.typ(x)
   660  }
   661  
   662  func (check *Checker) declareTypeParam(name *ast.Ident, scopePos token.Pos) *TypeParam {
   663  	// Use Typ[Invalid] for the type constraint to ensure that a type
   664  	// is present even if the actual constraint has not been assigned
   665  	// yet.
   666  	// TODO(gri) Need to systematically review all uses of type parameter
   667  	//           constraints to make sure we don't rely on them if they
   668  	//           are not properly set yet.
   669  	tname := NewTypeName(name.Pos(), check.pkg, name.Name, nil)
   670  	tpar := check.newTypeParam(tname, Typ[Invalid]) // assigns type to tname as a side-effect
   671  	check.declare(check.scope, name, tname, scopePos)
   672  	return tpar
   673  }
   674  
   675  func (check *Checker) collectMethods(obj *TypeName) {
   676  	// get associated methods
   677  	// (Checker.collectObjects only collects methods with non-blank names;
   678  	// Checker.resolveBaseTypeName ensures that obj is not an alias name
   679  	// if it has attached methods.)
   680  	methods := check.methods[obj]
   681  	if methods == nil {
   682  		return
   683  	}
   684  	delete(check.methods, obj)
   685  	assert(!check.objMap[obj].tdecl.Assign.IsValid()) // don't use TypeName.IsAlias (requires fully set up object)
   686  
   687  	// use an objset to check for name conflicts
   688  	var mset objset
   689  
   690  	// spec: "If the base type is a struct type, the non-blank method
   691  	// and field names must be distinct."
   692  	base := asNamed(obj.typ) // shouldn't fail but be conservative
   693  	if base != nil {
   694  		assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
   695  
   696  		// See go.dev/issue/52529: we must delay the expansion of underlying here, as
   697  		// base may not be fully set-up.
   698  		check.later(func() {
   699  			check.checkFieldUniqueness(base)
   700  		}).describef(obj, "verifying field uniqueness for %v", base)
   701  
   702  		// Checker.Files may be called multiple times; additional package files
   703  		// may add methods to already type-checked types. Add pre-existing methods
   704  		// so that we can detect redeclarations.
   705  		for i := 0; i < base.NumMethods(); i++ {
   706  			m := base.Method(i)
   707  			assert(m.name != "_")
   708  			assert(mset.insert(m) == nil)
   709  		}
   710  	}
   711  
   712  	// add valid methods
   713  	for _, m := range methods {
   714  		// spec: "For a base type, the non-blank names of methods bound
   715  		// to it must be unique."
   716  		assert(m.name != "_")
   717  		if alt := mset.insert(m); alt != nil {
   718  			if alt.Pos().IsValid() {
   719  				check.errorf(m, DuplicateMethod, "method %s.%s already declared at %v", obj.Name(), m.name, alt.Pos())
   720  			} else {
   721  				check.errorf(m, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
   722  			}
   723  			continue
   724  		}
   725  
   726  		if base != nil {
   727  			base.AddMethod(m)
   728  		}
   729  	}
   730  }
   731  
   732  func (check *Checker) checkFieldUniqueness(base *Named) {
   733  	if t, _ := base.Underlying().(*Struct); t != nil {
   734  		var mset objset
   735  		for i := 0; i < base.NumMethods(); i++ {
   736  			m := base.Method(i)
   737  			assert(m.name != "_")
   738  			assert(mset.insert(m) == nil)
   739  		}
   740  
   741  		// Check that any non-blank field names of base are distinct from its
   742  		// method names.
   743  		for _, fld := range t.fields {
   744  			if fld.name != "_" {
   745  				if alt := mset.insert(fld); alt != nil {
   746  					// Struct fields should already be unique, so we should only
   747  					// encounter an alternate via collision with a method name.
   748  					_ = alt.(*Func)
   749  
   750  					// For historical consistency, we report the primary error on the
   751  					// method, and the alt decl on the field.
   752  					err := check.newError(DuplicateFieldAndMethod)
   753  					err.addf(alt, "field and method with the same name %s", fld.name)
   754  					err.addAltDecl(fld)
   755  					err.report()
   756  				}
   757  			}
   758  		}
   759  	}
   760  }
   761  
   762  func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
   763  	assert(obj.typ == nil)
   764  
   765  	// func declarations cannot use iota
   766  	assert(check.iota == nil)
   767  
   768  	sig := new(Signature)
   769  	obj.typ = sig // guard against cycles
   770  
   771  	fdecl := decl.fdecl
   772  	check.funcType(sig, fdecl.Recv, fdecl.Type)
   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 = fdecl.End()
   778  
   779  	if fdecl.Type.TypeParams.NumFields() > 0 && fdecl.Body == nil {
   780  		check.softErrorf(fdecl.Name, 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(d ast.Decl) {
   793  	pkg := check.pkg
   794  
   795  	check.walkDecl(d, func(d decl) {
   796  		switch d := d.(type) {
   797  		case constDecl:
   798  			top := len(check.delayed)
   799  
   800  			// declare all constants
   801  			lhs := make([]*Const, len(d.spec.Names))
   802  			for i, name := range d.spec.Names {
   803  				obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
   804  				lhs[i] = obj
   805  
   806  				var init ast.Expr
   807  				if i < len(d.init) {
   808  					init = d.init[i]
   809  				}
   810  
   811  				check.constDecl(obj, d.typ, init, d.inherited)
   812  			}
   813  
   814  			// process function literals in init expressions before scope changes
   815  			check.processDelayed(top)
   816  
   817  			// spec: "The scope of a constant or variable identifier declared
   818  			// inside a function begins at the end of the ConstSpec or VarSpec
   819  			// (ShortVarDecl for short variable declarations) and ends at the
   820  			// end of the innermost containing block."
   821  			scopePos := d.spec.End()
   822  			for i, name := range d.spec.Names {
   823  				check.declare(check.scope, name, lhs[i], scopePos)
   824  			}
   825  
   826  		case varDecl:
   827  			top := len(check.delayed)
   828  
   829  			lhs0 := make([]*Var, len(d.spec.Names))
   830  			for i, name := range d.spec.Names {
   831  				lhs0[i] = newVar(LocalVar, name.Pos(), pkg, name.Name, nil)
   832  			}
   833  
   834  			// initialize all variables
   835  			for i, obj := range lhs0 {
   836  				var lhs []*Var
   837  				var init ast.Expr
   838  				switch len(d.spec.Values) {
   839  				case len(d.spec.Names):
   840  					// lhs and rhs match
   841  					init = d.spec.Values[i]
   842  				case 1:
   843  					// rhs is expected to be a multi-valued expression
   844  					lhs = lhs0
   845  					init = d.spec.Values[0]
   846  				default:
   847  					if i < len(d.spec.Values) {
   848  						init = d.spec.Values[i]
   849  					}
   850  				}
   851  				check.varDecl(obj, lhs, d.spec.Type, init)
   852  				if len(d.spec.Values) == 1 {
   853  					// If we have a single lhs variable we are done either way.
   854  					// If we have a single rhs expression, it must be a multi-
   855  					// valued expression, in which case handling the first lhs
   856  					// variable will cause all lhs variables to have a type
   857  					// assigned, and we are done as well.
   858  					if debug {
   859  						for _, obj := range lhs0 {
   860  							assert(obj.typ != nil)
   861  						}
   862  					}
   863  					break
   864  				}
   865  			}
   866  
   867  			// process function literals in init expressions before scope changes
   868  			check.processDelayed(top)
   869  
   870  			// declare all variables
   871  			// (only at this point are the variable scopes (parents) set)
   872  			scopePos := d.spec.End() // see constant declarations
   873  			for i, name := range d.spec.Names {
   874  				// see constant declarations
   875  				check.declare(check.scope, name, lhs0[i], scopePos)
   876  			}
   877  
   878  		case typeDecl:
   879  			obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
   880  			// spec: "The scope of a type identifier declared inside a function
   881  			// begins at the identifier in the TypeSpec and ends at the end of
   882  			// the innermost containing block."
   883  			scopePos := d.spec.Name.Pos()
   884  			check.declare(check.scope, d.spec.Name, obj, scopePos)
   885  			check.push(obj) // mark as grey
   886  			check.typeDecl(obj, d.spec)
   887  			check.pop()
   888  		default:
   889  			check.errorf(d.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", d.node())
   890  		}
   891  	})
   892  }
   893  

View as plain text