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

View as plain text