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

View as plain text