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

View as plain text