"go/ast"
"go/constant"
"go/internal/typeparams"
- "go/token"
+ . "internal/types/errors"
"strings"
)
// If an error occurred, x.mode is set to invalid.
// For the meaning of def, see Checker.definedType, below.
// If wantType is set, the identifier e is expected to denote a type.
-//
-func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
+func (check *Checker) ident(x *operand, e *ast.Ident, def *TypeName, wantType bool) {
x.mode = invalid
x.expr = e
switch obj {
case nil:
if e.Name == "_" {
- check.error(e, _InvalidBlank, "cannot use _ as value or type")
+ // Blank identifiers are never declared, but the current identifier may
+ // be a placeholder for a receiver type parameter. In this case we can
+ // resolve its type and object from Checker.recvTParamMap.
+ if tpar := check.recvTParamMap[e]; tpar != nil {
+ x.mode = typexpr
+ x.typ = tpar
+ } else {
+ check.error(e, InvalidBlank, "cannot use _ as value or type")
+ }
} else {
- check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
+ check.errorf(e, UndeclaredName, "undefined: %s", e.Name)
}
return
case universeAny, universeComparable:
- if !check.allowVersion(check.pkg, 1, 18) {
- check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
- return
- }
- // If we allow "any" for general use, this if-statement can be removed (issue #33232).
- if obj == universeAny {
- check.error(e, _Todo, "cannot use any outside constraint position")
- return
+ if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Name) {
+ return // avoid follow-on errors
}
}
check.recordUse(e, obj)
// a cycle which needs to be reported). Otherwise we can skip the
// call and avoid a possible cycle error in favor of the more
// informative "not a type/value" error that this function's caller
- // will issue (see issue #25790).
+ // will issue (see go.dev/issue/25790).
typ := obj.Type()
if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
check.objDecl(obj, def)
switch obj := obj.(type) {
case *PkgName:
- check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
+ check.errorf(e, InvalidPkgUse, "use of package %s not in selector", obj.name)
return
case *Const:
check.addDeclDep(obj)
- if typ == Typ[Invalid] {
+ if !isValid(typ) {
return
}
if obj == universeIota {
if check.iota == nil {
- check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
+ check.error(e, InvalidIota, "cannot use iota outside constant declaration")
return
}
x.val = check.iota
x.mode = constant_
case *TypeName:
+ if !check.enableAlias && check.isBrokenAlias(obj) {
+ check.errorf(e, InvalidDeclCycle, "invalid use of type alias %s in recursive type (see go.dev/issue/50729)", obj.name)
+ return
+ }
x.mode = typexpr
case *Var:
obj.used = true
}
check.addDeclDep(obj)
- if typ == Typ[Invalid] {
+ if !isValid(typ) {
return
}
x.mode = variable
}
// varType type-checks the type expression e and returns its type, or Typ[Invalid].
-// The type must not be an (uninstantiated) generic type and it must be ordinary
-// (see ordinaryType).
+// The type must not be an (uninstantiated) generic type and it must not be a
+// constraint interface.
func (check *Checker) varType(e ast.Expr) Type {
typ := check.definedType(e, nil)
- check.ordinaryType(e, typ)
+ check.validVarType(e, typ)
return typ
}
-// ordinaryType reports an error if typ is an interface type containing
-// type lists or is (or embeds) the predeclared type comparable.
-func (check *Checker) ordinaryType(pos positioner, typ Type) {
- // We don't want to call under() (via asInterface) or complete interfaces
- // while we are in the middle of type-checking parameter declarations that
- // might belong to interface methods. Delay this check to the end of
- // type-checking.
+// validVarType reports an error if typ is a constraint interface.
+// The expression e is used for error reporting, if any.
+func (check *Checker) validVarType(e ast.Expr, typ Type) {
+ // If we have a type parameter there's nothing to do.
+ if isTypeParam(typ) {
+ return
+ }
+
+ // We don't want to call under() or complete interfaces while we are in
+ // the middle of type-checking parameter declarations that might belong
+ // to interface methods. Delay this check to the end of type-checking.
check.later(func() {
- if t := asInterface(typ); t != nil {
- tset := computeTypeSet(check, pos.Pos(), t) // TODO(gri) is this the correct position?
- if tset.types != nil {
- check.softErrorf(pos, _Todo, "interface contains type constraints (%s)", tset.types)
- return
- }
- if tset.IsComparable() {
- check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
+ if t, _ := under(typ).(*Interface); t != nil {
+ tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
+ if !tset.IsMethodSet() {
+ if tset.comparable {
+ check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface is (or embeds) comparable", typ)
+ } else {
+ check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface contains type constraints", typ)
+ }
}
}
- })
-}
-
-// anyType type-checks the type expression e and returns its type, or Typ[Invalid].
-// The type may be generic or instantiated.
-func (check *Checker) anyType(e ast.Expr) Type {
- typ := check.typInternal(e, nil)
- assert(isTyped(typ))
- check.recordTypeAndValue(e, typexpr, typ, nil)
- return typ
+ }).describef(e, "check var type %s", typ)
}
// definedType is like typ but also accepts a type name def.
-// If def != nil, e is the type specification for the defined type def, declared
-// in a type declaration, and def.underlying will be set to the type of e before
-// any components of e are type-checked.
-//
-func (check *Checker) definedType(e ast.Expr, def *Named) Type {
+// If def != nil, e is the type specification for the type named def, declared
+// in a type declaration, and def.typ.underlying will be set to the type of e
+// before any components of e are type-checked.
+func (check *Checker) definedType(e ast.Expr, def *TypeName) Type {
typ := check.typInternal(e, def)
assert(isTyped(typ))
if isGeneric(typ) {
- check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
+ check.errorf(e, WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
typ = Typ[Invalid]
}
check.recordTypeAndValue(e, typexpr, typ, nil)
return typ
}
-// genericType is like typ but the type must be an (uninstantiated) generic type.
-func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
+// genericType is like typ but the type must be an (uninstantiated) generic
+// type. If cause is non-nil and the type expression was a valid type but not
+// generic, cause will be populated with a message describing the error.
+func (check *Checker) genericType(e ast.Expr, cause *string) Type {
typ := check.typInternal(e, nil)
assert(isTyped(typ))
- if typ != Typ[Invalid] && !isGeneric(typ) {
- if reportErr {
- check.errorf(e, _Todo, "%s is not a generic type", typ)
+ if isValid(typ) && !isGeneric(typ) {
+ if cause != nil {
+ *cause = check.sprintf("%s is not a generic type", typ)
}
typ = Typ[Invalid]
}
// typInternal drives type checking of types.
// Must only be called by definedType or genericType.
-//
-func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
- if trace {
- check.trace(e0.Pos(), "type %s", e0)
+func (check *Checker) typInternal(e0 ast.Expr, def *TypeName) (T Type) {
+ if check.conf._Trace {
+ check.trace(e0.Pos(), "-- type %s", e0)
check.indent++
defer func() {
check.indent--
if T != nil {
// Calling under() here may lead to endless instantiations.
// Test case: type T[P any] *T[P]
- // TODO(gri) investigate if that's a bug or to be expected
- // (see also analogous comment in Checker.instantiate).
- under = T.Underlying()
+ under = safeUnderlying(T)
}
if T == under {
check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
switch x.mode {
case typexpr:
typ := x.typ
- def.setUnderlying(typ)
+ setDefType(def, typ)
return typ
case invalid:
// ignore - error reported before
case novalue:
- check.errorf(&x, _NotAType, "%s used as type", &x)
+ check.errorf(&x, NotAType, "%s used as type", &x)
default:
- check.errorf(&x, _NotAType, "%s is not a type", &x)
+ check.errorf(&x, NotAType, "%s is not a type", &x)
}
case *ast.SelectorExpr:
var x operand
- check.selector(&x, e)
+ check.selector(&x, e, def, true)
switch x.mode {
case typexpr:
typ := x.typ
- def.setUnderlying(typ)
+ setDefType(def, typ)
return typ
case invalid:
// ignore - error reported before
case novalue:
- check.errorf(&x, _NotAType, "%s used as type", &x)
+ check.errorf(&x, NotAType, "%s used as type", &x)
default:
- check.errorf(&x, _NotAType, "%s is not a type", &x)
+ check.errorf(&x, NotAType, "%s is not a type", &x)
}
- case *ast.IndexExpr, *ast.MultiIndexExpr:
+ case *ast.IndexExpr, *ast.IndexListExpr:
ix := typeparams.UnpackIndexExpr(e)
- // TODO(rfindley): type instantiation should require go1.18
- return check.instantiatedType(ix.X, ix.Indices, def)
+ check.verifyVersionf(inNode(e, ix.Lbrack), go1_18, "type instantiation")
+ return check.instantiatedType(ix, def)
case *ast.ParenExpr:
// Generic types must be instantiated before they can be used in any form.
return check.definedType(e.X, def)
case *ast.ArrayType:
- if e.Len != nil {
- typ := new(Array)
- def.setUnderlying(typ)
- typ.len = check.arrayLength(e.Len)
+ if e.Len == nil {
+ typ := new(Slice)
+ setDefType(def, typ)
typ.elem = check.varType(e.Elt)
return typ
}
- typ := new(Slice)
- def.setUnderlying(typ)
+ typ := new(Array)
+ setDefType(def, typ)
+ // Provide a more specific error when encountering a [...] array
+ // rather than leaving it to the handling of the ... expression.
+ if _, ok := e.Len.(*ast.Ellipsis); ok {
+ check.error(e.Len, BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
+ typ.len = -1
+ } else {
+ typ.len = check.arrayLength(e.Len)
+ }
typ.elem = check.varType(e.Elt)
- return typ
+ if typ.len >= 0 {
+ return typ
+ }
+ // report error if we encountered [...]
case *ast.Ellipsis:
// dots are handled explicitly where they are legal
// (array composite literals and parameter lists)
- check.error(e, _InvalidDotDotDot, "invalid use of '...'")
+ check.error(e, InvalidDotDotDot, "invalid use of '...'")
check.use(e.Elt)
case *ast.StructType:
typ := new(Struct)
- def.setUnderlying(typ)
+ setDefType(def, typ)
check.structType(typ, e)
return typ
case *ast.StarExpr:
typ := new(Pointer)
- def.setUnderlying(typ)
+ typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
+ setDefType(def, typ)
typ.base = check.varType(e.X)
return typ
case *ast.FuncType:
typ := new(Signature)
- def.setUnderlying(typ)
+ setDefType(def, typ)
check.funcType(typ, nil, e)
return typ
case *ast.InterfaceType:
- typ := new(Interface)
- def.setUnderlying(typ)
- if def != nil {
- typ.obj = def.obj
- }
+ typ := check.newInterface()
+ setDefType(def, typ)
check.interfaceType(typ, e, def)
return typ
case *ast.MapType:
typ := new(Map)
- def.setUnderlying(typ)
+ setDefType(def, typ)
typ.key = check.varType(e.Key)
typ.elem = check.varType(e.Value)
// function, map, or slice."
//
// Delay this check because it requires fully setup types;
- // it is safe to continue in any case (was issue 6667).
+ // it is safe to continue in any case (was go.dev/issue/6667).
check.later(func() {
if !Comparable(typ.key) {
var why string
- if asTypeParam(typ.key) != nil {
+ if isTypeParam(typ.key) {
why = " (missing comparable constraint)"
}
- check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
+ check.errorf(e.Key, IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
}
- })
+ }).describef(e.Key, "check map key %s", typ.key)
return typ
case *ast.ChanType:
typ := new(Chan)
- def.setUnderlying(typ)
+ setDefType(def, typ)
dir := SendRecv
switch e.Dir {
case ast.RECV:
dir = RecvOnly
default:
- check.invalidAST(e, "unknown channel direction %d", e.Dir)
+ check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
// ok to continue
}
return typ
default:
- check.errorf(e0, _NotAType, "%s is not a type", e0)
+ check.errorf(e0, NotAType, "%s is not a type", e0)
+ check.use(e0)
}
typ := Typ[Invalid]
- def.setUnderlying(typ)
+ setDefType(def, typ)
return typ
}
-// typeOrNil type-checks the type expression (or nil value) e
-// and returns the type of e, or nil. If e is a type, it must
-// not be an (uninstantiated) generic type.
-// If e is neither a type nor nil, typeOrNil returns Typ[Invalid].
-// TODO(gri) should we also disallow non-var types?
-func (check *Checker) typeOrNil(e ast.Expr) Type {
- var x operand
- check.rawExpr(&x, e, nil)
- switch x.mode {
- case invalid:
- // ignore - error reported before
- case novalue:
- check.errorf(&x, _NotAType, "%s used as type", &x)
- case typexpr:
- check.instantiatedOperand(&x)
- return x.typ
- case value:
- if x.isNil() {
- return nil
+func setDefType(def *TypeName, typ Type) {
+ if def != nil {
+ switch t := def.typ.(type) {
+ case *Alias:
+ // t.fromRHS should always be set, either to an invalid type
+ // in the beginning, or to typ in certain cyclic declarations.
+ if t.fromRHS != Typ[Invalid] && t.fromRHS != typ {
+ panic(sprintf(nil, nil, true, "t.fromRHS = %s, typ = %s\n", t.fromRHS, typ))
+ }
+ t.fromRHS = typ
+ case *Basic:
+ assert(t == Typ[Invalid])
+ case *Named:
+ t.underlying = typ
+ default:
+ panic(fmt.Sprintf("unexpected type %T", t))
}
- fallthrough
- default:
- check.errorf(&x, _NotAType, "%s is not a type", &x)
}
- return Typ[Invalid]
}
-func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
- base := check.genericType(x, true)
- if base == Typ[Invalid] {
- return base // error already reported
+func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *TypeName) (res Type) {
+ if check.conf._Trace {
+ check.trace(ix.Pos(), "-- instantiating type %s with %s", ix.X, ix.Indices)
+ check.indent++
+ defer func() {
+ check.indent--
+ // Don't format the underlying here. It will always be nil.
+ check.trace(ix.Pos(), "=> %s", res)
+ }()
+ }
+
+ var cause string
+ gtyp := check.genericType(ix.X, &cause)
+ if cause != "" {
+ check.errorf(ix.Orig, NotAGenericType, invalidOp+"%s (%s)", ix.Orig, cause)
+ }
+ if !isValid(gtyp) {
+ return gtyp // error already reported
+ }
+
+ orig := asNamed(gtyp)
+ if orig == nil {
+ panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
}
// evaluate arguments
- targs := check.typeList(targsx)
+ targs := check.typeList(ix.Indices)
if targs == nil {
- def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
+ setDefType(def, Typ[Invalid]) // avoid errors later due to lazy instantiation
return Typ[Invalid]
}
- // determine argument positions
- posList := make([]token.Pos, len(targs))
- for i, arg := range targsx {
- posList[i] = arg.Pos()
- }
-
- typ := check.InstantiateLazy(x.Pos(), base, targs, posList, true)
- def.setUnderlying(typ)
+ // create the instance
+ inst := asNamed(check.instance(ix.Pos(), orig, targs, nil, check.context()))
+ setDefType(def, inst)
- // make sure we check instantiation works at least once
- // and that the resulting type is valid
+ // orig.tparams may not be set up, so we need to do expansion later.
check.later(func() {
- t := expand(typ)
- check.validType(t, nil)
- })
+ // This is an instance from the source, not from recursive substitution,
+ // and so it must be resolved during type-checking so that we can report
+ // errors.
+ check.recordInstance(ix.Orig, inst.TypeArgs().list(), inst)
+
+ if check.validateTArgLen(ix.Pos(), inst.TypeParams().Len(), inst.TypeArgs().Len()) {
+ if i, err := check.verify(ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), check.context()); err != nil {
+ // best position for error reporting
+ pos := ix.Pos()
+ if i < len(ix.Indices) {
+ pos = ix.Indices[i].Pos()
+ }
+ check.softErrorf(atPos(pos), InvalidTypeArg, err.Error())
+ } else {
+ check.mono.recordInstance(check.pkg, ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), ix.Indices)
+ }
+ }
- return typ
+ // TODO(rfindley): remove this call: we don't need to call validType here,
+ // as cycles can only occur for types used inside a Named type declaration,
+ // and so it suffices to call validType from declared types.
+ check.validType(inst)
+ }).describef(ix, "resolve instance %s", inst)
+
+ return inst
}
// arrayLength type-checks the array length expression e
// and returns the constant length >= 0, or a value < 0
// to indicate an error (and thus an unknown length).
func (check *Checker) arrayLength(e ast.Expr) int64 {
+ // If e is an identifier, the array declaration might be an
+ // attempt at a parameterized type declaration with missing
+ // constraint. Provide an error message that mentions array
+ // length.
+ if name, _ := e.(*ast.Ident); name != nil {
+ obj := check.lookup(name.Name)
+ if obj == nil {
+ check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Name)
+ return -1
+ }
+ if _, ok := obj.(*Const); !ok {
+ check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Name)
+ return -1
+ }
+ }
+
var x operand
- check.expr(&x, e)
+ check.expr(nil, &x, e)
if x.mode != constant_ {
if x.mode != invalid {
- check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
+ check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
}
return -1
}
+
if isUntyped(x.typ) || isInteger(x.typ) {
if val := constant.ToInt(x.val); val.Kind() == constant.Int {
if representableConst(val, check, Typ[Int], nil) {
if n, ok := constant.Int64Val(val); ok && n >= 0 {
return n
}
- check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
- return -1
}
}
}
- check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
+
+ var msg string
+ if isInteger(x.typ) {
+ msg = "invalid array length %s"
+ } else {
+ msg = "array length %s must be integer"
+ }
+ check.errorf(&x, InvalidArrayLen, msg, &x)
return -1
}
res := make([]Type, len(list)) // res != nil even if len(list) == 0
for i, x := range list {
t := check.varType(x)
- if t == Typ[Invalid] {
+ if !isValid(t) {
res = nil
}
if res != nil {