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

View as plain text