github.com/bir3/gocompiler@v0.3.205/src/go/types/typexpr.go (about)

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