...

Source file src/go/types/decl.go

Documentation: go/types

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

View as plain text