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

View as plain text