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

View as plain text