Source file src/go/types/typexpr.go

     1  // Copyright 2013 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  // This file implements type-checking of identifiers and type expressions.
     6  
     7  package types
     8  
     9  import (
    10  	"fmt"
    11  	"go/ast"
    12  	"go/constant"
    13  	"go/internal/typeparams"
    14  	"strings"
    15  )
    16  
    17  // ident type-checks identifier e and initializes x with the value or type of e.
    18  // If an error occurred, x.mode is set to invalid.
    19  // For the meaning of def, see Checker.definedType, below.
    20  // If wantType is set, the identifier e is expected to denote a type.
    21  //
    22  func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
    23  	x.mode = invalid
    24  	x.expr = e
    25  
    26  	// Note that we cannot use check.lookup here because the returned scope
    27  	// may be different from obj.Parent(). See also Scope.LookupParent doc.
    28  	scope, obj := check.scope.LookupParent(e.Name, check.pos)
    29  	switch obj {
    30  	case nil:
    31  		if e.Name == "_" {
    32  			// Blank identifiers are never declared, but the current identifier may
    33  			// be a placeholder for a receiver type parameter. In this case we can
    34  			// resolve its type and object from Checker.recvTParamMap.
    35  			if tpar := check.recvTParamMap[e]; tpar != nil {
    36  				x.mode = typexpr
    37  				x.typ = tpar
    38  			} else {
    39  				check.error(e, _InvalidBlank, "cannot use _ as value or type")
    40  			}
    41  		} else {
    42  			check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
    43  		}
    44  		return
    45  	case universeAny, universeComparable:
    46  		if !check.allowVersion(check.pkg, 1, 18) {
    47  			check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
    48  			return // avoid follow-on errors
    49  		}
    50  	}
    51  	check.recordUse(e, obj)
    52  
    53  	// Type-check the object.
    54  	// Only call Checker.objDecl if the object doesn't have a type yet
    55  	// (in which case we must actually determine it) or the object is a
    56  	// TypeName and we also want a type (in which case we might detect
    57  	// a cycle which needs to be reported). Otherwise we can skip the
    58  	// call and avoid a possible cycle error in favor of the more
    59  	// informative "not a type/value" error that this function's caller
    60  	// will issue (see issue #25790).
    61  	typ := obj.Type()
    62  	if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
    63  		check.objDecl(obj, def)
    64  		typ = obj.Type() // type must have been assigned by Checker.objDecl
    65  	}
    66  	assert(typ != nil)
    67  
    68  	// The object may have been dot-imported.
    69  	// If so, mark the respective package as used.
    70  	// (This code is only needed for dot-imports. Without them,
    71  	// we only have to mark variables, see *Var case below).
    72  	if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
    73  		pkgName.used = true
    74  	}
    75  
    76  	switch obj := obj.(type) {
    77  	case *PkgName:
    78  		check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
    79  		return
    80  
    81  	case *Const:
    82  		check.addDeclDep(obj)
    83  		if typ == Typ[Invalid] {
    84  			return
    85  		}
    86  		if obj == universeIota {
    87  			if check.iota == nil {
    88  				check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
    89  				return
    90  			}
    91  			x.val = check.iota
    92  		} else {
    93  			x.val = obj.val
    94  		}
    95  		assert(x.val != nil)
    96  		x.mode = constant_
    97  
    98  	case *TypeName:
    99  		if check.isBrokenAlias(obj) {
   100  			check.errorf(e, _InvalidDeclCycle, "invalid use of type alias %s in recursive type (see issue #50729)", obj.name)
   101  			return
   102  		}
   103  		x.mode = typexpr
   104  
   105  	case *Var:
   106  		// It's ok to mark non-local variables, but ignore variables
   107  		// from other packages to avoid potential race conditions with
   108  		// dot-imported variables.
   109  		if obj.pkg == check.pkg {
   110  			obj.used = true
   111  		}
   112  		check.addDeclDep(obj)
   113  		if typ == Typ[Invalid] {
   114  			return
   115  		}
   116  		x.mode = variable
   117  
   118  	case *Func:
   119  		check.addDeclDep(obj)
   120  		x.mode = value
   121  
   122  	case *Builtin:
   123  		x.id = obj.id
   124  		x.mode = builtin
   125  
   126  	case *Nil:
   127  		x.mode = value
   128  
   129  	default:
   130  		unreachable()
   131  	}
   132  
   133  	x.typ = typ
   134  }
   135  
   136  // typ type-checks the type expression e and returns its type, or Typ[Invalid].
   137  // The type must not be an (uninstantiated) generic type.
   138  func (check *Checker) typ(e ast.Expr) Type {
   139  	return check.definedType(e, nil)
   140  }
   141  
   142  // varType type-checks the type expression e and returns its type, or Typ[Invalid].
   143  // The type must not be an (uninstantiated) generic type and it must not be a
   144  // constraint interface.
   145  func (check *Checker) varType(e ast.Expr) Type {
   146  	typ := check.definedType(e, nil)
   147  	check.validVarType(e, typ)
   148  	return typ
   149  }
   150  
   151  // validVarType reports an error if typ is a constraint interface.
   152  // The expression e is used for error reporting, if any.
   153  func (check *Checker) validVarType(e ast.Expr, typ Type) {
   154  	// If we have a type parameter there's nothing to do.
   155  	if isTypeParam(typ) {
   156  		return
   157  	}
   158  
   159  	// We don't want to call under() or complete interfaces while we are in
   160  	// the middle of type-checking parameter declarations that might belong
   161  	// to interface methods. Delay this check to the end of type-checking.
   162  	check.later(func() {
   163  		if t, _ := under(typ).(*Interface); t != nil {
   164  			tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
   165  			if !tset.IsMethodSet() {
   166  				if tset.comparable {
   167  					check.softErrorf(e, _MisplacedConstraintIface, "interface is (or embeds) comparable")
   168  				} else {
   169  					check.softErrorf(e, _MisplacedConstraintIface, "interface contains type constraints")
   170  				}
   171  			}
   172  		}
   173  	})
   174  }
   175  
   176  // definedType is like typ but also accepts a type name def.
   177  // If def != nil, e is the type specification for the defined type def, declared
   178  // in a type declaration, and def.underlying will be set to the type of e before
   179  // any components of e are type-checked.
   180  //
   181  func (check *Checker) definedType(e ast.Expr, def *Named) Type {
   182  	typ := check.typInternal(e, def)
   183  	assert(isTyped(typ))
   184  	if isGeneric(typ) {
   185  		check.errorf(e, _WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
   186  		typ = Typ[Invalid]
   187  	}
   188  	check.recordTypeAndValue(e, typexpr, typ, nil)
   189  	return typ
   190  }
   191  
   192  // genericType is like typ but the type must be an (uninstantiated) generic
   193  // type. If reason is non-nil and the type expression was a valid type but not
   194  // generic, reason will be populated with a message describing the error.
   195  func (check *Checker) genericType(e ast.Expr, reason *string) Type {
   196  	typ := check.typInternal(e, nil)
   197  	assert(isTyped(typ))
   198  	if typ != Typ[Invalid] && !isGeneric(typ) {
   199  		if reason != nil {
   200  			*reason = check.sprintf("%s is not a generic type", typ)
   201  		}
   202  		typ = Typ[Invalid]
   203  	}
   204  	// TODO(gri) what is the correct call below?
   205  	check.recordTypeAndValue(e, typexpr, typ, nil)
   206  	return typ
   207  }
   208  
   209  // goTypeName returns the Go type name for typ and
   210  // removes any occurrences of "types." from that name.
   211  func goTypeName(typ Type) string {
   212  	return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
   213  }
   214  
   215  // typInternal drives type checking of types.
   216  // Must only be called by definedType or genericType.
   217  //
   218  func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
   219  	if trace {
   220  		check.trace(e0.Pos(), "-- type %s", e0)
   221  		check.indent++
   222  		defer func() {
   223  			check.indent--
   224  			var under Type
   225  			if T != nil {
   226  				// Calling under() here may lead to endless instantiations.
   227  				// Test case: type T[P any] *T[P]
   228  				under = safeUnderlying(T)
   229  			}
   230  			if T == under {
   231  				check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
   232  			} else {
   233  				check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
   234  			}
   235  		}()
   236  	}
   237  
   238  	switch e := e0.(type) {
   239  	case *ast.BadExpr:
   240  		// ignore - error reported before
   241  
   242  	case *ast.Ident:
   243  		var x operand
   244  		check.ident(&x, e, def, true)
   245  
   246  		switch x.mode {
   247  		case typexpr:
   248  			typ := x.typ
   249  			def.setUnderlying(typ)
   250  			return typ
   251  		case invalid:
   252  			// ignore - error reported before
   253  		case novalue:
   254  			check.errorf(&x, _NotAType, "%s used as type", &x)
   255  		default:
   256  			check.errorf(&x, _NotAType, "%s is not a type", &x)
   257  		}
   258  
   259  	case *ast.SelectorExpr:
   260  		var x operand
   261  		check.selector(&x, e, def)
   262  
   263  		switch x.mode {
   264  		case typexpr:
   265  			typ := x.typ
   266  			def.setUnderlying(typ)
   267  			return typ
   268  		case invalid:
   269  			// ignore - error reported before
   270  		case novalue:
   271  			check.errorf(&x, _NotAType, "%s used as type", &x)
   272  		default:
   273  			check.errorf(&x, _NotAType, "%s is not a type", &x)
   274  		}
   275  
   276  	case *ast.IndexExpr, *ast.IndexListExpr:
   277  		ix := typeparams.UnpackIndexExpr(e)
   278  		if !check.allowVersion(check.pkg, 1, 18) {
   279  			check.softErrorf(inNode(e, ix.Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
   280  		}
   281  		return check.instantiatedType(ix, def)
   282  
   283  	case *ast.ParenExpr:
   284  		// Generic types must be instantiated before they can be used in any form.
   285  		// Consequently, generic types cannot be parenthesized.
   286  		return check.definedType(e.X, def)
   287  
   288  	case *ast.ArrayType:
   289  		if e.Len == nil {
   290  			typ := new(Slice)
   291  			def.setUnderlying(typ)
   292  			typ.elem = check.varType(e.Elt)
   293  			return typ
   294  		}
   295  
   296  		typ := new(Array)
   297  		def.setUnderlying(typ)
   298  		typ.len = check.arrayLength(e.Len)
   299  		typ.elem = check.varType(e.Elt)
   300  		if typ.len >= 0 {
   301  			return typ
   302  		}
   303  
   304  	case *ast.Ellipsis:
   305  		// dots are handled explicitly where they are legal
   306  		// (array composite literals and parameter lists)
   307  		check.error(e, _InvalidDotDotDot, "invalid use of '...'")
   308  		check.use(e.Elt)
   309  
   310  	case *ast.StructType:
   311  		typ := new(Struct)
   312  		def.setUnderlying(typ)
   313  		check.structType(typ, e)
   314  		return typ
   315  
   316  	case *ast.StarExpr:
   317  		typ := new(Pointer)
   318  		typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
   319  		def.setUnderlying(typ)
   320  		typ.base = check.varType(e.X)
   321  		return typ
   322  
   323  	case *ast.FuncType:
   324  		typ := new(Signature)
   325  		def.setUnderlying(typ)
   326  		check.funcType(typ, nil, e)
   327  		return typ
   328  
   329  	case *ast.InterfaceType:
   330  		typ := check.newInterface()
   331  		def.setUnderlying(typ)
   332  		if def != nil {
   333  			typ.obj = def.obj
   334  		}
   335  		check.interfaceType(typ, e, def)
   336  		return typ
   337  
   338  	case *ast.MapType:
   339  		typ := new(Map)
   340  		def.setUnderlying(typ)
   341  
   342  		typ.key = check.varType(e.Key)
   343  		typ.elem = check.varType(e.Value)
   344  
   345  		// spec: "The comparison operators == and != must be fully defined
   346  		// for operands of the key type; thus the key type must not be a
   347  		// function, map, or slice."
   348  		//
   349  		// Delay this check because it requires fully setup types;
   350  		// it is safe to continue in any case (was issue 6667).
   351  		check.later(func() {
   352  			if !Comparable(typ.key) {
   353  				var why string
   354  				if isTypeParam(typ.key) {
   355  					why = " (missing comparable constraint)"
   356  				}
   357  				check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
   358  			}
   359  		})
   360  
   361  		return typ
   362  
   363  	case *ast.ChanType:
   364  		typ := new(Chan)
   365  		def.setUnderlying(typ)
   366  
   367  		dir := SendRecv
   368  		switch e.Dir {
   369  		case ast.SEND | ast.RECV:
   370  			// nothing to do
   371  		case ast.SEND:
   372  			dir = SendOnly
   373  		case ast.RECV:
   374  			dir = RecvOnly
   375  		default:
   376  			check.invalidAST(e, "unknown channel direction %d", e.Dir)
   377  			// ok to continue
   378  		}
   379  
   380  		typ.dir = dir
   381  		typ.elem = check.varType(e.Value)
   382  		return typ
   383  
   384  	default:
   385  		check.errorf(e0, _NotAType, "%s is not a type", e0)
   386  	}
   387  
   388  	typ := Typ[Invalid]
   389  	def.setUnderlying(typ)
   390  	return typ
   391  }
   392  
   393  func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type) {
   394  	pos := ix.X.Pos()
   395  	if trace {
   396  		check.trace(pos, "-- instantiating %s with %s", ix.X, ix.Indices)
   397  		check.indent++
   398  		defer func() {
   399  			check.indent--
   400  			// Don't format the underlying here. It will always be nil.
   401  			check.trace(pos, "=> %s", res)
   402  		}()
   403  	}
   404  
   405  	var reason string
   406  	gtyp := check.genericType(ix.X, &reason)
   407  	if reason != "" {
   408  		check.invalidOp(ix.Orig, _NotAGenericType, "%s (%s)", ix.Orig, reason)
   409  	}
   410  	if gtyp == Typ[Invalid] {
   411  		return gtyp // error already reported
   412  	}
   413  
   414  	orig, _ := gtyp.(*Named)
   415  	if orig == nil {
   416  		panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
   417  	}
   418  
   419  	// evaluate arguments
   420  	targs := check.typeList(ix.Indices)
   421  	if targs == nil {
   422  		def.setUnderlying(Typ[Invalid]) // avoid errors later due to lazy instantiation
   423  		return Typ[Invalid]
   424  	}
   425  
   426  	// enableTypeTypeInference controls whether to infer missing type arguments
   427  	// using constraint type inference. See issue #51527.
   428  	const enableTypeTypeInference = false
   429  
   430  	// create the instance
   431  	ctxt := check.bestContext(nil)
   432  	h := ctxt.instanceHash(orig, targs)
   433  	// targs may be incomplete, and require inference. In any case we should de-duplicate.
   434  	inst, _ := ctxt.lookup(h, orig, targs).(*Named)
   435  	// If inst is non-nil, we can't just return here. Inst may have been
   436  	// constructed via recursive substitution, in which case we wouldn't do the
   437  	// validation below. Ensure that the validation (and resulting errors) runs
   438  	// for each instantiated type in the source.
   439  	if inst == nil {
   440  		// x may be a selector for an imported type; use its start pos rather than x.Pos().
   441  		tname := NewTypeName(ix.Pos(), orig.obj.pkg, orig.obj.name, nil)
   442  		inst = check.newNamed(tname, orig, nil, nil, nil) // underlying, methods and tparams are set when named is resolved
   443  		inst.targs = newTypeList(targs)
   444  		inst = ctxt.update(h, orig, targs, inst).(*Named)
   445  	}
   446  	def.setUnderlying(inst)
   447  
   448  	inst.resolver = func(ctxt *Context, n *Named) (*TypeParamList, Type, *methodList) {
   449  		tparams := n.orig.TypeParams().list()
   450  
   451  		targs := n.targs.list()
   452  		if enableTypeTypeInference && len(targs) < len(tparams) {
   453  			// If inference fails, len(inferred) will be 0, and inst.underlying will
   454  			// be set to Typ[Invalid] in expandNamed.
   455  			inferred := check.infer(ix.Orig, tparams, targs, nil, nil)
   456  			if len(inferred) > len(targs) {
   457  				n.targs = newTypeList(inferred)
   458  			}
   459  		}
   460  
   461  		return expandNamed(ctxt, n, pos)
   462  	}
   463  
   464  	// orig.tparams may not be set up, so we need to do expansion later.
   465  	check.later(func() {
   466  		// This is an instance from the source, not from recursive substitution,
   467  		// and so it must be resolved during type-checking so that we can report
   468  		// errors.
   469  		inst.resolve(ctxt)
   470  		// Since check is non-nil, we can still mutate inst. Unpinning the resolver
   471  		// frees some memory.
   472  		inst.resolver = nil
   473  		check.recordInstance(ix.Orig, inst.TypeArgs().list(), inst)
   474  
   475  		if check.validateTArgLen(pos, inst.tparams.Len(), inst.targs.Len()) {
   476  			if i, err := check.verify(pos, inst.tparams.list(), inst.targs.list()); err != nil {
   477  				// best position for error reporting
   478  				pos := ix.Pos()
   479  				if i < len(ix.Indices) {
   480  					pos = ix.Indices[i].Pos()
   481  				}
   482  				check.softErrorf(atPos(pos), _InvalidTypeArg, err.Error())
   483  			} else {
   484  				check.mono.recordInstance(check.pkg, pos, inst.tparams.list(), inst.targs.list(), ix.Indices)
   485  			}
   486  		}
   487  
   488  		check.validType(inst)
   489  	})
   490  
   491  	return inst
   492  }
   493  
   494  // arrayLength type-checks the array length expression e
   495  // and returns the constant length >= 0, or a value < 0
   496  // to indicate an error (and thus an unknown length).
   497  func (check *Checker) arrayLength(e ast.Expr) int64 {
   498  	// If e is an identifier, the array declaration might be an
   499  	// attempt at a parameterized type declaration with missing
   500  	// constraint. Provide an error message that mentions array
   501  	// length.
   502  	if name, _ := e.(*ast.Ident); name != nil {
   503  		obj := check.lookup(name.Name)
   504  		if obj == nil {
   505  			check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
   506  			return -1
   507  		}
   508  		if _, ok := obj.(*Const); !ok {
   509  			check.errorf(name, _InvalidArrayLen, "invalid array length %s", name.Name)
   510  			return -1
   511  		}
   512  	}
   513  
   514  	var x operand
   515  	check.expr(&x, e)
   516  	if x.mode != constant_ {
   517  		if x.mode != invalid {
   518  			check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
   519  		}
   520  		return -1
   521  	}
   522  
   523  	if isUntyped(x.typ) || isInteger(x.typ) {
   524  		if val := constant.ToInt(x.val); val.Kind() == constant.Int {
   525  			if representableConst(val, check, Typ[Int], nil) {
   526  				if n, ok := constant.Int64Val(val); ok && n >= 0 {
   527  					return n
   528  				}
   529  				check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
   530  				return -1
   531  			}
   532  		}
   533  	}
   534  
   535  	check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
   536  	return -1
   537  }
   538  
   539  // typeList provides the list of types corresponding to the incoming expression list.
   540  // If an error occurred, the result is nil, but all list elements were type-checked.
   541  func (check *Checker) typeList(list []ast.Expr) []Type {
   542  	res := make([]Type, len(list)) // res != nil even if len(list) == 0
   543  	for i, x := range list {
   544  		t := check.varType(x)
   545  		if t == Typ[Invalid] {
   546  			res = nil
   547  		}
   548  		if res != nil {
   549  			res[i] = t
   550  		}
   551  	}
   552  	return res
   553  }
   554  

View as plain text