return
}
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
target := T
// spec: "If an untyped constant is assigned to a variable of interface
// type or the blank identifier, the constant is first converted to type
return
}
} else if T == nil || isNonTypeParamInterface(T) {
- target = Default(x.typ_)
+ target = Default(x.typ())
}
} else { // go/types
if T == nil || isNonTypeParamInterface(T) {
- if T == nil && x.typ_ == Typ[UntypedNil] {
+ if T == nil && x.typ() == Typ[UntypedNil] {
check.errorf(x, UntypedNilUse, "use of untyped nil in %s", context)
x.mode_ = invalid
return
}
- target = Default(x.typ_)
+ target = Default(x.typ())
}
}
newType, val, code := check.implicitTypeAndValue(x, target)
x.val = val
check.updateExprVal(x.expr, val)
}
- if newType != x.typ_ {
+ if newType != x.typ() {
x.typ_ = newType
check.updateExprType(x.expr, newType, false)
}
}
func (check *Checker) initConst(lhs *Const, x *operand) {
- if x.mode_ == invalid || !isValid(x.typ_) || !isValid(lhs.typ) {
+ if x.mode_ == invalid || !isValid(x.typ()) || !isValid(lhs.typ) {
if lhs.typ == nil {
lhs.typ = Typ[Invalid]
}
}
return
}
- assert(isConstType(x.typ_))
+ assert(isConstType(x.typ()))
// If the lhs doesn't have a type yet, use the type of x.
if lhs.typ == nil {
- lhs.typ = x.typ_
+ lhs.typ = x.typ()
}
check.assignment(x, lhs.typ, "constant declaration")
// or Typ[Invalid] in case of an error.
// If the initialization check fails, x.mode is set to invalid.
func (check *Checker) initVar(lhs *Var, x *operand, context string) {
- if x.mode_ == invalid || !isValid(x.typ_) || !isValid(lhs.typ) {
+ if x.mode_ == invalid || !isValid(x.typ()) || !isValid(lhs.typ) {
if lhs.typ == nil {
lhs.typ = Typ[Invalid]
}
// If lhs doesn't have a type yet, use the type of x.
if lhs.typ == nil {
- typ := x.typ_
+ typ := x.typ()
if isUntyped(typ) {
// convert untyped types to default types
if typ == Typ[UntypedNil] {
check.usedVars[v] = v_used // restore v.used
}
- if x.mode_ == invalid || !isValid(x.typ_) {
+ if x.mode_ == invalid || !isValid(x.typ()) {
return Typ[Invalid]
}
return Typ[Invalid]
}
- return x.typ_
+ return x.typ()
}
// assignVar checks the assignment lhs = rhs (if x == nil), or lhs = x (if x != nil).
// operandTypes returns the list of types for the given operands.
func operandTypes(list []*operand) (res []Type) {
for _, x := range list {
- res = append(res, x.typ_)
+ res = append(res, x.typ())
}
return res
}
if ok, _ := x.assignableTo(check, NewSlice(universeByte), nil); ok {
y := args[1]
hasString := false
- for _, u := range typeset(y.typ_) {
+ for _, u := range typeset(y.typ()) {
if s, _ := u.(*Slice); s != nil && Identical(s.elem, universeByte) {
// typeset ⊇ {[]byte}
} else if isString(u) {
}
if y != nil && hasString {
// setting the signature also signals that we're done
- sig = makeSig(x.typ_, x.typ_, y.typ_)
+ sig = makeSig(x.typ(), x.typ(), y.typ())
sig.variadic = true
}
}
// general case
if sig == nil {
// check arguments by creating custom signature
- sig = makeSig(x.typ_, x.typ_, NewSlice(E)) // []E required for variadic signature
+ sig = makeSig(x.typ(), x.typ(), NewSlice(E)) // []E required for variadic signature
sig.variadic = true
check.arguments(call, sig, nil, nil, args, nil) // discard result (we know the result type)
// ok to continue even if check.arguments reported errors
// len(x)
mode := invalid
var val constant.Value
- switch t := arrayPtrDeref(x.typ_.Underlying()).(type) {
+ switch t := arrayPtrDeref(x.typ().Underlying()).(type) {
case *Basic:
if isString(t) && id == _Len {
if x.mode_ == constant_ {
}
case *Interface:
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
break
}
- if underIs(x.typ_, func(u Type) bool {
+ if underIs(x.typ(), func(u Type) bool {
switch t := arrayPtrDeref(u).(type) {
case *Basic:
if isString(t) && id == _Len {
if mode == invalid {
// avoid error if underlying type is invalid
- if isValid(x.typ_.Underlying()) {
+ if isValid(x.typ().Underlying()) {
code := InvalidCap
if id == _Len {
code = InvalidLen
// record the signature before changing x.typ
if check.recordTypes() && mode != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ()))
}
x.mode_ = mode
// clear(m)
check.verifyVersionf(call.Fun, go1_21, "clear")
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
switch u.(type) {
case *Map, *Slice:
return true
x.mode_ = novalue
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(nil, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(nil, x.typ()))
}
case _Close:
// close(c)
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
uch, _ := u.(*Chan)
if uch == nil {
check.errorf(x, InvalidClose, invalidOp+"cannot close non-channel %s", x)
}
x.mode_ = novalue
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(nil, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(nil, x.typ()))
}
case _Complex:
// convert or check untyped arguments
d := 0
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
d |= 1
}
- if isUntyped(y.typ_) {
+ if isUntyped(y.typ()) {
d |= 2
}
switch d {
// x and y are typed => nothing to do
case 1:
// only x is untyped => convert to type of y
- check.convertUntyped(x, y.typ_)
+ check.convertUntyped(x, y.typ())
case 2:
// only y is untyped => convert to type of x
- check.convertUntyped(y, x.typ_)
+ check.convertUntyped(y, x.typ())
case 3:
// x and y are untyped =>
// 1) if both are constants, convert them to untyped
// because shifts of floats are not permitted)
if x.mode_ == constant_ && y.mode_ == constant_ {
toFloat := func(x *operand) {
- if isNumeric(x.typ_) && constant.Sign(constant.Imag(x.val)) == 0 {
+ if isNumeric(x.typ()) && constant.Sign(constant.Imag(x.val)) == 0 {
x.typ_ = Typ[UntypedFloat]
}
}
}
// both argument types must be identical
- if !Identical(x.typ_, y.typ_) {
- check.errorf(x, InvalidComplex, invalidOp+"%v (mismatched types %s and %s)", call, x.typ_, y.typ_)
+ if !Identical(x.typ(), y.typ()) {
+ check.errorf(x, InvalidComplex, invalidOp+"%v (mismatched types %s and %s)", call, x.typ(), y.typ())
return
}
}
resTyp := check.applyTypeFunc(f, x, id)
if resTyp == nil {
- check.errorf(x, InvalidComplex, invalidArg+"arguments have type %s, expected floating-point", x.typ_)
+ check.errorf(x, InvalidComplex, invalidArg+"arguments have type %s, expected floating-point", x.typ())
return
}
}
if check.recordTypes() && x.mode_ != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ_, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ(), x.typ()))
}
x.typ_ = resTyp
var special bool
if ok, _ := x.assignableTo(check, NewSlice(universeByte), nil); ok {
special = true
- for _, u := range typeset(y.typ_) {
+ for _, u := range typeset(y.typ()) {
if s, _ := u.(*Slice); s != nil && Identical(s.elem, universeByte) {
// typeset ⊇ {[]byte}
} else if isString(u) {
srcE, err := sliceElem(y)
if err != nil {
// If we have a string, for a better error message proceed with byte element type.
- if !allString(y.typ_) {
+ if !allString(y.typ()) {
check.errorf(y, InvalidCopy, "invalid copy: %s", err.format(check))
return
}
}
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ_, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ(), y.typ()))
}
x.mode_ = value
x.typ_ = Typ[Int]
// delete(map_, key)
// map_ must be a map type or a type parameter describing map types.
// The key cannot be a type parameter for now.
- map_ := x.typ_
+ map_ := x.typ()
var key Type
if !underIs(map_, func(u Type) bool {
map_, _ := u.(*Map)
// real(complexT) floatT
// convert or check untyped argument
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
if x.mode_ == constant_ {
// an untyped constant number can always be considered
// as a complex constant
- if isNumeric(x.typ_) {
+ if isNumeric(x.typ()) {
x.typ_ = Typ[UntypedComplex]
}
} else {
if id == _Real {
code = InvalidReal
}
- check.errorf(x, code, invalidArg+"argument has type %s, expected complex type", x.typ_)
+ check.errorf(x, code, invalidArg+"argument has type %s, expected complex type", x.typ())
return
}
}
if check.recordTypes() && x.mode_ != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ()))
}
x.typ_ = resTyp
x.mode_ = value
x.typ_ = T
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, types...))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), types...))
}
case _Max, _Min:
return
}
- if !allOrdered(a.typ_) {
+ if !allOrdered(a.typ()) {
check.errorf(a, InvalidMinMaxOperand, invalidArg+"%s cannot be ordered", a)
return
}
return
}
- if !Identical(x.typ_, a.typ_) {
- check.errorf(a, MismatchedTypes, invalidArg+"mismatched types %s (previous argument) and %s (type of %s)", x.typ_, a.typ_, a.expr)
+ if !Identical(x.typ(), a.typ()) {
+ check.errorf(a, MismatchedTypes, invalidArg+"mismatched types %s (previous argument) and %s (type of %s)", x.typ(), a.typ(), a.expr)
return
}
// Use the final type computed above for all arguments.
for _, a := range args {
- check.updateExprType(a.expr, x.typ_, true)
+ check.updateExprType(a.expr, x.typ(), true)
}
if check.recordTypes() && x.mode_ != constant_ {
types := make([]Type, nargs)
for i := range types {
- types[i] = x.typ_
+ types[i] = x.typ()
}
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, types...))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), types...))
}
case _New:
return
case typexpr:
// new(T)
- check.validVarType(arg, x.typ_)
+ check.validVarType(arg, x.typ())
default:
// new(expr)
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
// check for overflow and untyped nil
check.assignment(x, nil, "argument to new")
if x.mode_ == invalid {
return
}
- assert(isTyped(x.typ_))
+ assert(isTyped(x.typ()))
}
// report version error only if there are no other errors
check.verifyVersionf(call.Fun, go1_26, "new(%s)", arg)
}
- T := x.typ_
+ T := x.typ()
x.mode_ = value
x.typ_ = NewPointer(T)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, T))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), T))
}
case _Panic:
if a.mode_ == invalid {
return
}
- params[i] = a.typ_
+ params[i] = a.typ()
}
}
x.mode_ = value
x.typ_ = &emptyInterface
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ()))
}
case _Add:
x.mode_ = value
x.typ_ = Typ[UnsafePointer]
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, x.typ_, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), x.typ(), y.typ()))
}
case _Alignof:
return
}
- if check.hasVarSize(x.typ_) {
+ if check.hasVarSize(x.typ()) {
x.mode_ = value
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ()))
}
} else {
x.mode_ = constant_
- x.val = constant.MakeInt64(check.conf.alignof(x.typ_))
+ x.val = constant.MakeInt64(check.conf.alignof(x.typ()))
// result is constant - no need to record signature
}
x.typ_ = Typ[Uintptr]
return
}
- base := derefStructPtr(x.typ_)
+ base := derefStructPtr(x.typ())
sel := selx.Sel.Value
obj, index, indirect := lookupFieldOrMethod(base, false, check.pkg, sel, false)
switch obj.(type) {
return
}
- if check.hasVarSize(x.typ_) {
+ if check.hasVarSize(x.typ()) {
x.mode_ = value
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ()))
}
} else {
- size := check.conf.sizeof(x.typ_)
+ size := check.conf.sizeof(x.typ())
if size < 0 {
check.errorf(x, TypeTooLarge, "%s is too large", x)
return
// unsafe.Slice(ptr *T, len IntegerType) []T
check.verifyVersionf(call.Fun, go1_17, "unsafe.Slice")
- u, _ := commonUnder(x.typ_, nil)
+ u, _ := commonUnder(x.typ(), nil)
ptr, _ := u.(*Pointer)
if ptr == nil {
check.errorf(x, InvalidUnsafeSlice, invalidArg+"%s is not a pointer", x)
x.mode_ = value
x.typ_ = NewSlice(ptr.base)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, ptr, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), ptr, y.typ()))
}
case _SliceData:
// unsafe.SliceData(slice []T) *T
check.verifyVersionf(call.Fun, go1_20, "unsafe.SliceData")
- u, _ := commonUnder(x.typ_, nil)
+ u, _ := commonUnder(x.typ(), nil)
slice, _ := u.(*Slice)
if slice == nil {
check.errorf(x, InvalidUnsafeSliceData, invalidArg+"%s is not a slice", x)
x.mode_ = value
x.typ_ = NewPointer(slice.elem)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, slice))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), slice))
}
case _String:
x.mode_ = value
x.typ_ = Typ[String]
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, NewPointer(universeByte), y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), NewPointer(universeByte), y.typ()))
}
case _StringData:
x.mode_ = value
x.typ_ = NewPointer(universeByte)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, Typ[String]))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), Typ[String]))
}
case _Assert:
// assert(pred) causes a typechecker error if pred is false.
// The result of assert is the value of pred if there is no error.
// Note: assert is only available in self-test mode.
- if x.mode_ != constant_ || !isBoolean(x.typ_) {
+ if x.mode_ != constant_ || !isBoolean(x.typ()) {
check.errorf(x, Test, invalidArg+"%s is not a boolean constant", x)
return
}
// or a type error if x is not a slice (or a type set of slices).
func sliceElem(x *operand) (Type, *typeError) {
var E Type
- for _, u := range typeset(x.typ_) {
+ for _, u := range typeset(x.typ()) {
s, _ := u.(*Slice)
if s == nil {
if x.isNil() {
// applyTypeFunc returns nil.
// If x is not a type parameter, the result is f(x).
func (check *Checker) applyTypeFunc(f func(Type) Type, x *operand, id builtinId) Type {
- if tp, _ := Unalias(x.typ_).(*TypeParam); tp != nil {
+ if tp, _ := Unalias(x.typ()).(*TypeParam); tp != nil {
// Test if t satisfies the requirements for the argument
// type and collect possible result types at the same time.
var terms []*Term
return ptyp
}
- return f(x.typ_)
+ return f(x.typ())
}
// makeSig makes a signature for the given argument and result types.
// Check the number of type arguments (got) vs number of type parameters (want).
// Note that x is a function value, not a type expression, so we don't need to
// call Underlying below.
- sig := x.typ_.(*Signature)
+ sig := x.typ().(*Signature)
got, want := len(targs), sig.TypeParams().Len()
if got > want {
// Providing too many type arguments is always an error.
if x.mode_ == invalid {
return conversion
}
- T := x.typ_
+ T := x.typ()
x.mode_ = invalid
// We cannot convert a value to an incomplete type; make sure it's complete.
if !check.isComplete(T) {
// If the operand type is a type parameter, all types in its type set
// must have a common underlying type, which must be a signature.
- u, err := commonUnder(x.typ_, func(t, u Type) *typeError {
+ u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
if _, ok := u.(*Signature); u != nil && !ok {
return typeErrorf("%s is not a function", t)
}
// if type inference failed, a parameterized result must be invalidated
// (operands cannot have a parameterized type)
- if x.mode_ == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ_) {
+ if x.mode_ == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ()) {
x.mode_ = invalid
}
if i < len(targsList) {
if n := len(targsList[i]); n > 0 {
// x must be a partially instantiated function
- assert(n < x.typ_.(*Signature).TypeParams().Len())
+ assert(n < x.typ().(*Signature).TypeParams().Len())
}
}
}
// x is not a function instantiation (it may still be a generic function).
check.rawExpr(nil, &x, e, nil, true)
check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
- if t, ok := x.typ_.(*Tuple); ok && x.mode_ != invalid {
+ if t, ok := x.typ().(*Tuple); ok && x.mode_ != invalid {
// x is a function call returning multiple values; it cannot be generic.
resList = make([]*operand, t.Len())
for i, v := range t.vars {
if enableReverseTypeInference {
for i, arg := range args {
// generic arguments cannot have a defined (*Named) type - no need for underlying type below
- if asig, _ := arg.typ_.(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
+ if asig, _ := arg.typ().(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
// The argument type is a generic function signature. This type is
// pointer-identical with (it's copied from) the type of the generic
// function argument and thus the function object.
j := n
for _, i := range genericArgs {
arg := args[i]
- asig := arg.typ_.(*Signature)
+ asig := arg.typ().(*Signature)
k := j + asig.TypeParams().Len()
// targs[j:k] are the inferred type arguments for asig
arg.typ_ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations)
x.mode_ = variable
x.typ_ = exp.typ
if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
- x.typ_ = x.typ_.(*Pointer).base
+ x.typ_ = x.typ().(*Pointer).base
}
case *Func:
x.mode_ = funcMode
x.typ_ = exp.typ
if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
x.mode_ = value
- x.typ_ = x.typ_.(*Signature).results.vars[0].typ
+ x.typ_ = x.typ().(*Signature).results.vars[0].typ
}
case *Builtin:
x.mode_ = builtin
}
// We cannot select on an incomplete type; make sure it's complete.
- if !check.isComplete(x.typ_) {
+ if !check.isComplete(x.typ()) {
goto Error
}
// Additionally, if x.typ is a pointer type, selecting implicitly dereferences the value, meaning
// its base type must also be complete.
- if p, ok := x.typ_.Underlying().(*Pointer); ok && !check.isComplete(p.base) {
+ if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
goto Error
}
- obj, index, indirect = lookupFieldOrMethod(x.typ_, x.mode_ == variable, check.pkg, sel, false)
+ obj, index, indirect = lookupFieldOrMethod(x.typ(), x.mode_ == variable, check.pkg, sel, false)
if obj == nil {
// Don't report another error if the underlying type was invalid (go.dev/issue/49541).
- if !isValid(x.typ_.Underlying()) {
+ if !isValid(x.typ().Underlying()) {
goto Error
}
if indirect {
if x.mode_ == typexpr {
- check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ_, sel, x.typ_, sel)
+ check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ(), sel, x.typ(), sel)
} else {
- check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ_)
+ check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ())
}
goto Error
}
var why string
- if isInterfacePtr(x.typ_) {
- why = check.interfacePtrError(x.typ_)
+ if isInterfacePtr(x.typ()) {
+ why = check.interfacePtrError(x.typ())
} else {
- alt, _, _ := lookupFieldOrMethod(x.typ_, x.mode_ == variable, check.pkg, sel, true)
- why = check.lookupError(x.typ_, sel, alt, false)
+ alt, _, _ := lookupFieldOrMethod(x.typ(), x.mode_ == variable, check.pkg, sel, true)
+ why = check.lookupError(x.typ(), sel, alt, false)
}
check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
goto Error
switch obj := obj.(type) {
case *Var:
if x.mode_ == typexpr {
- check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ_)
+ check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ())
goto Error
}
// field value
- check.recordSelection(e, FieldVal, x.typ_, obj, index, indirect)
+ check.recordSelection(e, FieldVal, x.typ(), obj, index, indirect)
if x.mode_ == variable || indirect {
x.mode_ = variable
} else {
if x.mode_ == typexpr {
// method expression
- check.recordSelection(e, MethodExpr, x.typ_, obj, index, indirect)
+ check.recordSelection(e, MethodExpr, x.typ(), obj, index, indirect)
sig := obj.typ.(*Signature)
if sig.recv == nil {
name = "_"
}
}
- params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ_)}, params...)
+ params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ())}, params...)
x.mode_ = value
x.typ_ = &Signature{
tparams: sig.tparams,
// TODO(gri) If we needed to take into account the receiver's
// addressability, should we report the type &(x.typ) instead?
- check.recordSelection(e, MethodVal, x.typ_, obj, index, indirect)
+ check.recordSelection(e, MethodVal, x.typ(), obj, index, indirect)
x.mode_ = value
// their type after each constant operation.
// x.typ cannot be a type parameter (type
// parameters cannot be constant types).
- if isTyped(x.typ_) {
- check.representable(x, x.typ_.Underlying().(*Basic))
+ if isTyped(x.typ()) {
+ check.representable(x, x.typ().Underlying().(*Basic))
return
}
assert(x.mode_ == constant_)
v := x.val
if !representableConst(x.val, check, typ, &v) {
- if isNumeric(x.typ_) && isNumeric(typ) {
+ if isNumeric(x.typ()) && isNumeric(typ) {
// numeric conversion : error msg
//
// integer -> integer : overflows
// float -> integer : truncated
// float -> float : overflows
//
- if !isInteger(x.typ_) && isInteger(typ) {
+ if !isInteger(x.typ()) && isInteger(typ) {
return nil, TruncatedFloat
} else {
return nil, NumericOverflow
x.val = val
check.updateExprVal(x.expr, val)
}
- if newType != x.typ_ {
+ if newType != x.typ() {
x.typ_ = newType
check.updateExprType(x.expr, newType, false)
}
// nothing to do
case representableConst(x.val, check, t, val):
return true
- case isInteger(x.typ_) && isString(t):
+ case isInteger(x.typ()) && isString(t):
codepoint := unicode.ReplacementChar
if i, ok := constant.Uint64Val(x.val); ok && i <= unicode.MaxRune {
codepoint = rune(i)
// A conversion from an integer constant to an integer type
// can only fail if there's overflow. Give a concise error.
// (go.dev/issue/63563)
- if !ok && isInteger(x.typ_) && isInteger(T) {
+ if !ok && isInteger(x.typ()) && isInteger(T) {
check.errorf(x, InvalidConversion, "constant %s overflows %s", x.val, T)
x.mode_ = invalid
return
cause = check.sprintf("%s does not contain specific types", T)
return false
}
- if isString(x.typ_) && isBytesOrRunes(u) {
+ if isString(x.typ()) && isBytesOrRunes(u) {
return true
}
if !constConvertibleTo(u, nil) {
- if isInteger(x.typ_) && isInteger(u) {
+ if isInteger(x.typ()) && isInteger(u) {
// see comment above on constant conversion
cause = check.sprintf("constant %s overflows %s (in %s)", x.val, u, T)
} else {
// The conversion argument types are final. For untyped values the
// conversion provides the type, per the spec: "A constant may be
// given a type explicitly by a constant declaration or conversion,...".
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
final := T
// - For conversions to interfaces, except for untyped nil arguments
// and isTypes2, use the argument's default type.
// - If !isTypes2, keep untyped nil for untyped nil arguments.
// - For constant integer to string conversions, keep the argument type.
// (See also the TODO below.)
- if isTypes2 && x.typ_ == Typ[UntypedNil] {
+ if isTypes2 && x.typ() == Typ[UntypedNil] {
// ok
} else if isNonTypeParamInterface(T) || constArg && !isConstType(T) || !isTypes2 && x.isNil() {
- final = Default(x.typ_) // default type of untyped nil is untyped nil
- } else if x.mode_ == constant_ && isInteger(x.typ_) && allString(T) {
- final = x.typ_
+ final = Default(x.typ()) // default type of untyped nil is untyped nil
+ } else if x.mode_ == constant_ && isInteger(x.typ()) && allString(T) {
+ final = x.typ()
}
check.updateExprType(x.expr, final, true)
}
}
origT := T
- V := Unalias(x.typ_)
+ V := Unalias(x.typ())
T = Unalias(T)
Vu := V.Underlying()
Tu := T.Underlying()
return false // no specific types
}
if !x.convertibleTo(check, T.typ, cause) {
- errorf("cannot convert %s to type %s (in %s)", x.typ_, T.typ, Tp)
+ errorf("cannot convert %s to type %s (in %s)", x.typ(), T.typ, Tp)
return false
}
return true
func f(x *operand, e *syntax.Expr, ...)
where e is the expression to be checked, and x is the result of the check.
-The check performed by f may fail in which case x.mode == invalid, and
+The check performed by f may fail in which case x.mode_ == invalid, and
related error messages will have been issued by f.
If a hint argument is present, it is the composite literal element type
func (check *Checker) op(m opPredicates, x *operand, op syntax.Operator) bool {
if pred := m[op]; pred != nil {
- if !pred(x.typ_) {
+ if !pred(x.typ()) {
check.errorf(x, UndefinedOp, invalidOp+"operator %s not defined on %s", op, x)
return false
}
return
}
x.mode_ = value
- x.typ_ = &Pointer{base: x.typ_}
+ x.typ_ = &Pointer{base: x.typ()}
return
case syntax.Recv:
case syntax.Tilde:
// Provide a better error position and message than what check.op below would do.
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint")
x.mode_ = invalid
return
return
}
var prec uint
- if isUnsigned(x.typ_) {
- prec = uint(check.conf.sizeof(x.typ_) * 8)
+ if isUnsigned(x.typ()) {
+ prec = uint(check.conf.sizeof(x.typ()) * 8)
}
x.val = constant.UnaryOp(op2tok[op], x.val, prec)
x.expr = e
// or send to x (recv == false) operation. If the operation is not valid, chanElem
// reports an error and returns nil.
func (check *Checker) chanElem(pos poser, x *operand, recv bool) Type {
- u, err := commonUnder(x.typ_, func(t, u Type) *typeError {
+ u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
if u == nil {
return typeErrorf("no specific channel type")
}
cause := err.format(check)
if recv {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s: %s", x, cause)
} else {
// In this case, only the non-channel and send-only channel error are possible.
check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s %s", cause, x)
}
} else {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s: %s", x, cause)
} else {
// In this case, only the non-channel and receive-only channel error are possible.
// If x is a constant operand, the returned constant.Value will be the
// representation of x in this context.
func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code) {
- if x.mode_ == invalid || isTyped(x.typ_) || !isValid(target) {
- return x.typ_, nil, 0
+ if x.mode_ == invalid || isTyped(x.typ()) || !isValid(target) {
+ return x.typ(), nil, 0
}
// x is untyped
if isUntyped(target) {
// both x and target are untyped
- if m := maxType(x.typ_, target); m != nil {
+ if m := maxType(x.typ(), target); m != nil {
return m, nil, 0
}
return nil, nil, InvalidUntypedConversion
}
if x.isNil() {
- assert(isUntyped(x.typ_))
+ assert(isUntyped(x.typ()))
if hasNil(target) {
return target, nil, 0
}
// result of comparisons (untyped bool), intermediate
// (delayed-checked) rhs operands of shifts, and as
// the value nil.
- switch x.typ_.(*Basic).kind {
+ switch x.typ().(*Basic).kind {
case UntypedBool:
if !isBoolean(target) {
return nil, nil, InvalidUntypedConversion
if !u.Empty() {
return nil, nil, InvalidUntypedConversion // cannot assign untyped values to non-empty interfaces
}
- return Default(x.typ_), nil, 0 // default type for nil is nil
+ return Default(x.typ()), nil, 0 // default type for nil is nil
default:
return nil, nil, InvalidUntypedConversion
}
// If switchCase is true, the operator op is ignored.
func (check *Checker) comparison(x, y *operand, op syntax.Operator, switchCase bool) {
// Avoid spurious errors if any of the operands has an invalid type (go.dev/issue/54405).
- if !isValid(x.typ_) || !isValid(y.typ_) {
+ if !isValid(x.typ()) || !isValid(y.typ()) {
x.mode_ = invalid
return
}
// spec: "In any comparison, the first operand must be assignable
// to the type of the second operand, or vice versa."
code := MismatchedTypes
- ok, _ := x.assignableTo(check, y.typ_, nil)
+ ok, _ := x.assignableTo(check, y.typ(), nil)
if !ok {
- ok, _ = y.assignableTo(check, x.typ_, nil)
+ ok, _ = y.assignableTo(check, x.typ(), nil)
}
if !ok {
// Report the error on the 2nd operand since we only
// know after seeing the 2nd operand whether we have
// a type mismatch.
errOp = y
- cause = check.sprintf("mismatched types %s and %s", x.typ_, y.typ_)
+ cause = check.sprintf("mismatched types %s and %s", x.typ(), y.typ())
goto Error
}
switch {
case x.isNil() || y.isNil():
// Comparison against nil requires that the other operand type has nil.
- typ := x.typ_
+ typ := x.typ()
if x.isNil() {
- typ = y.typ_
+ typ = y.typ()
}
if !hasNil(typ) {
// This case should only be possible for "nil == nil".
goto Error
}
- case !Comparable(x.typ_):
+ case !Comparable(x.typ()):
errOp = x
- cause = check.incomparableCause(x.typ_)
+ cause = check.incomparableCause(x.typ())
goto Error
- case !Comparable(y.typ_):
+ case !Comparable(y.typ()):
errOp = y
- cause = check.incomparableCause(y.typ_)
+ cause = check.incomparableCause(y.typ())
goto Error
}
case syntax.Lss, syntax.Leq, syntax.Gtr, syntax.Geq:
// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
switch {
- case !allOrdered(x.typ_):
+ case !allOrdered(x.typ()):
errOp = x
goto Error
- case !allOrdered(y.typ_):
+ case !allOrdered(y.typ()):
errOp = y
goto Error
}
// time will be materialized. Update the expression trees.
// If the current types are untyped, the materialized type
// is the respective default type.
- check.updateExprType(x.expr, Default(x.typ_), true)
- check.updateExprType(y.expr, Default(y.typ_), true)
+ check.updateExprType(x.expr, Default(x.typ()), true)
+ check.updateExprType(y.expr, Default(y.typ()), true)
}
// spec: "Comparison operators compare two operands and yield
Error:
// We have an offending operand errOp and possibly an error cause.
if cause == "" {
- if isTypeParam(x.typ_) || isTypeParam(y.typ_) {
+ if isTypeParam(x.typ()) || isTypeParam(y.typ()) {
// TODO(gri) should report the specific type causing the problem, if any
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
errOp = y
}
- cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ_, op)
+ cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ(), op)
} else {
// catch-all: neither x nor y is a type parameter
- what := compositeKind(errOp.typ_)
+ what := compositeKind(errOp.typ())
if what == "" {
- what = check.sprintf("%s", errOp.typ_)
+ what = check.sprintf("%s", errOp.typ())
}
cause = check.sprintf("operator %s not defined on %s", op, what)
}
xval = constant.ToInt(x.val)
}
- if allInteger(x.typ_) || isUntyped(x.typ_) && xval != nil && xval.Kind() == constant.Int {
+ if allInteger(x.typ()) || isUntyped(x.typ()) && xval != nil && xval.Kind() == constant.Int {
// The lhs is of integer type or an untyped constant representable
// as an integer. Nothing to do.
} else {
return
}
- if isUntyped(y.typ_) {
+ if isUntyped(y.typ()) {
// Caution: Check for representability here, rather than in the switch
// below, because isInteger includes untyped integers (was bug go.dev/issue/43697).
check.representable(y, Typ[Uint])
} else {
// Check that RHS is otherwise at least of integer type.
switch {
- case allInteger(y.typ_):
- if !allUnsigned(y.typ_) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
+ case allInteger(y.typ()):
+ if !allUnsigned(y.typ()) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
x.mode_ = invalid
return
}
- case isUntyped(y.typ_):
+ case isUntyped(y.typ()):
// This is incorrect, but preserves pre-existing behavior.
// See also go.dev/issue/47410.
check.convertUntyped(y, Typ[Uint])
if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
x.val = constant.MakeUnknown()
// ensure the correct type - see comment below
- if !isInteger(x.typ_) {
+ if !isInteger(x.typ()) {
x.typ_ = Typ[UntypedInt]
}
return
// (e.g., 2.0, an untyped float) - this can only happen for untyped
// non-integer numeric constants. Correct the type so that the shift
// result is of integer type.
- if !isInteger(x.typ_) {
+ if !isInteger(x.typ()) {
x.typ_ = Typ[UntypedInt]
}
// x is a constant so xval != nil and it must be of Int kind.
}
// non-constant shift with constant lhs
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
// spec: "If the left operand of a non-constant shift
// expression is an untyped constant, the type of the
// constant is what it would be if the shift expression
}
// non-constant shift - lhs must be an integer
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
x.mode_ = invalid
return
return
}
- if !Identical(x.typ_, y.typ_) {
+ if !Identical(x.typ(), y.typ()) {
// only report an error if we have valid types
// (otherwise we had an error reported elsewhere already)
- if isValid(x.typ_) && isValid(y.typ_) {
+ if isValid(x.typ()) && isValid(y.typ()) {
if e != nil {
- check.errorf(x, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ_, y.typ_)
+ check.errorf(x, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ(), y.typ())
} else {
- check.errorf(x, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ_, y.typ_)
+ check.errorf(x, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ(), y.typ())
}
}
x.mode_ = invalid
if op == syntax.Div || op == syntax.Rem {
// check for zero divisor
- if (x.mode_ == constant_ || allInteger(x.typ_)) && y.mode_ == constant_ && constant.Sign(y.val) == 0 {
+ if (x.mode_ == constant_ || allInteger(x.typ())) && y.mode_ == constant_ && constant.Sign(y.val) == 0 {
check.error(&y, DivByZero, invalidOp+"division by zero")
x.mode_ = invalid
return
}
// check for divisor underflow in complex division (see go.dev/issue/20227)
- if x.mode_ == constant_ && y.mode_ == constant_ && isComplex(x.typ_) {
+ if x.mode_ == constant_ && y.mode_ == constant_ && isComplex(x.typ()) {
re, im := constant.Real(y.val), constant.Imag(y.val)
re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
}
// force integer division for integer operands
tok := op2tok[op]
- if op == syntax.Div && isInteger(x.typ_) {
+ if op == syntax.Div && isInteger(x.typ()) {
tok = token.QUO_ASSIGN
}
x.val = constant.BinaryOp(x.val, tok, y.val)
// not compatible, we report a type mismatch error.
mayConvert := func(x, y *operand) bool {
// If both operands are typed, there's no need for an implicit conversion.
- if isTyped(x.typ_) && isTyped(y.typ_) {
+ if isTyped(x.typ()) && isTyped(y.typ()) {
return false
}
// A numeric type can only convert to another numeric type.
- if allNumeric(x.typ_) != allNumeric(y.typ_) {
+ if allNumeric(x.typ()) != allNumeric(y.typ()) {
return false
}
// An untyped operand may convert to its default type when paired with an empty interface
// TODO(gri) This should only matter for comparisons (the only binary operation that is
// valid with interfaces), but in that case the assignability check should take
// care of the conversion. Verify and possibly eliminate this extra test.
- if isNonTypeParamInterface(x.typ_) || isNonTypeParamInterface(y.typ_) {
+ if isNonTypeParamInterface(x.typ()) || isNonTypeParamInterface(y.typ()) {
return true
}
// A boolean type can only convert to another boolean type.
- if allBoolean(x.typ_) != allBoolean(y.typ_) {
+ if allBoolean(x.typ()) != allBoolean(y.typ()) {
return false
}
// A string type can only convert to another string type.
- if allString(x.typ_) != allString(y.typ_) {
+ if allString(x.typ()) != allString(y.typ()) {
return false
}
// Untyped nil can only convert to a type that has a nil.
if x.isNil() {
- return hasNil(y.typ_)
+ return hasNil(y.typ())
}
if y.isNil() {
- return hasNil(x.typ_)
+ return hasNil(x.typ())
}
// An untyped operand cannot convert to a pointer.
// TODO(gri) generalize to type parameters
- if isPointer(x.typ_) || isPointer(y.typ_) {
+ if isPointer(x.typ()) || isPointer(y.typ()) {
return false
}
return true
}
if mayConvert(x, y) {
- check.convertUntyped(x, y.typ_)
+ check.convertUntyped(x, y.typ())
if x.mode_ == invalid {
return
}
- check.convertUntyped(y, x.typ_)
+ check.convertUntyped(y, x.typ())
if y.mode_ == invalid {
x.mode_ = invalid
return
return
}
var what string
- switch t := x.typ_.(type) {
+ switch t := x.typ().(type) {
case *Alias, *Named:
if isGeneric(t) {
what = "type"
check.error(e, InvalidSyntaxTree, "invalid use of AssertExpr")
goto Error
}
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(x, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", x)
goto Error
}
- if _, ok := x.typ_.Underlying().(*Interface); !ok {
+ if _, ok := x.typ().Underlying().(*Interface); !ok {
check.errorf(x, InvalidAssert, invalidOp+"%s is not an interface", x)
goto Error
}
case invalid:
goto Error
case typexpr:
- check.validVarType(e.X, x.typ_)
- x.typ_ = &Pointer{base: x.typ_}
+ check.validVarType(e.X, x.typ())
+ x.typ_ = &Pointer{base: x.typ()}
default:
var base Type
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
p, _ := u.(*Pointer)
if p == nil {
check.errorf(x, InvalidIndirection, invalidOp+"cannot indirect %s", x)
// typeAssertion checks x.(T). The type of x must be an interface.
func (check *Checker) typeAssertion(e syntax.Expr, x *operand, T Type, typeSwitch bool) {
var cause string
- if check.assertableTo(x.typ_, T, &cause) {
+ if check.assertableTo(x.typ(), T, &cause) {
return // success
}
return
}
- check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ_, cause)
+ check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ(), cause)
}
// expr typechecks expression e and initializes x with the expression value.
check.rawExpr(nil, &x, e, nil, false)
check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
- if t, ok := x.typ_.(*Tuple); ok && x.mode_ != invalid {
+ if t, ok := x.typ().(*Tuple); ok && x.mode_ != invalid {
// multiple values
list = make([]*operand, t.Len())
for i, v := range t.vars {
func (check *Checker) singleValue(x *operand) {
if x.mode_ == value {
// tuple types are never named - no need for underlying type below
- if t, ok := x.typ_.(*Tuple); ok {
+ if t, ok := x.typ().(*Tuple); ok {
assert(t.Len() != 1)
check.errorf(x, TooManyValues, "multiple-value %s in single-value context", x)
x.mode_ = invalid
x.mode_ = invalid
// TODO(gri) here we re-evaluate e.X - try to avoid this
x.typ_ = check.varType(e)
- if isValid(x.typ_) {
+ if isValid(x.typ()) {
x.mode_ = typexpr
}
return false
case value:
- if sig, _ := x.typ_.Underlying().(*Signature); sig != nil && sig.TypeParams().Len() > 0 {
+ if sig, _ := x.typ().Underlying().(*Signature); sig != nil && sig.TypeParams().Len() > 0 {
// function instantiation
return true
}
}
// We cannot index on an incomplete type; make sure it's complete.
- if !check.isComplete(x.typ_) {
+ if !check.isComplete(x.typ()) {
x.mode_ = invalid
return false
}
- switch typ := x.typ_.Underlying().(type) {
+ switch typ := x.typ().Underlying().(type) {
case *Pointer:
// Additionally, if x.typ is a pointer to an array type, indexing implicitly dereferences the value, meaning
// its base type must also be complete.
// ordinary index expression
valid := false
length := int64(-1) // valid if >= 0
- switch typ := x.typ_.Underlying().(type) {
+ switch typ := x.typ().Underlying().(type) {
case *Basic:
if isString(typ) {
valid = true
return false
case *Interface:
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
break
}
// TODO(gri) report detailed failure cause for better error messages
var key, elem Type // key != nil: we must have all maps
mode := variable // non-maps result mode
// TODO(gri) factor out closure and use it for non-typeparam cases as well
- if underIs(x.typ_, func(u Type) bool {
+ if underIs(x.typ(), func(u Type) bool {
l := int64(-1) // valid if >= 0
var k, e Type // k is only set for maps
switch t := u.(type) {
// In pathological (invalid) cases (e.g.: type T1 [][[]T1{}[0][0]]T0)
// the element type may be accessed before it's set. Make sure we have
// a valid type.
- if x.typ_ == nil {
+ if x.typ() == nil {
x.typ_ = Typ[Invalid]
}
// determine common underlying type cu
var ct, cu Type // type and respective common underlying type
var hasString bool
- for t, u := range typeset(x.typ_) {
+ for t, u := range typeset(x.typ()) {
if u == nil {
- check.errorf(x, NonSliceableOperand, "cannot slice %s: no specific type in %s", x, x.typ_)
+ check.errorf(x, NonSliceableOperand, "cannot slice %s: no specific type in %s", x, x.typ())
cu = nil
break
}
// If we saw a string, proceed with string type,
// but don't go from untyped string to string.
cu = Typ[String]
- if !isTypeParam(x.typ_) {
- cu = x.typ_.Underlying() // untyped string remains untyped
+ if !isTypeParam(x.typ()) {
+ cu = x.typ().Underlying() // untyped string remains untyped
}
}
// Note that we don't permit slice expressions where x is a type expression, so we don't check for that here.
// However, if x.typ is a pointer to an array type, slicing implicitly dereferences the value, meaning
// its base type must also be complete.
- if p, ok := x.typ_.Underlying().(*Pointer); ok && !check.isComplete(p.base) {
+ if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
x.mode_ = invalid
return
}
}
// spec: "For untyped string operands the result
// is a non-constant value of type string."
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
x.typ_ = Typ[String]
}
}
}
if x.mode_ != constant_ {
- return x.typ_, -1
+ return x.typ(), -1
}
if x.val.Kind() == constant.Unknown {
}
// 0 <= v [ && v < max ]
- return x.typ_, v
+ return x.typ(), v
}
// isValidIndex checks whether operand x satisfies the criteria for integer
}
// spec: "the index x must be of integer type or an untyped constant"
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.errorf(x, code, invalidArg+"%s %s must be integer", what, x)
return false
}
continue
}
par := params.At(i)
- if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ_) {
+ if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ()) {
// Function parameters are always typed. Arguments may be untyped.
// Collect the indices of untyped arguments and handle them later.
- if isTyped(arg.typ_) {
- if !u.unify(par.typ, arg.typ_, assign) {
- errorf(par.typ, arg.typ_, arg)
+ if isTyped(arg.typ()) {
+ if !u.unify(par.typ, arg.typ(), assign) {
+ errorf(par.typ, arg.typ(), arg)
return nil
}
} else if _, ok := par.typ.(*TypeParam); ok && !arg.isNil() {
}
max := maxUntyped[tpar]
if max == nil {
- max = arg.typ_
+ max = arg.typ()
} else {
- m := maxType(max, arg.typ_)
+ m := maxType(max, arg.typ())
if m == nil {
- err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ_, tpar)
+ err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ(), tpar)
return nil
}
max = m
xkey := keyVal(x.val)
if keyIsInterface {
for _, vtyp := range visited[xkey] {
- if Identical(vtyp, x.typ_) {
+ if Identical(vtyp, x.typ()) {
duplicate = true
break
}
}
- visited[xkey] = append(visited[xkey], x.typ_)
+ visited[xkey] = append(visited[xkey], x.typ())
} else {
_, duplicate = visited[xkey]
visited[xkey] = nil
id builtinId
}
+func (x *operand) typ() Type {
+ return x.typ_
+}
+
+func (x *operand) isValid() bool {
+ return x.mode_ != invalid
+}
+
// Pos returns the position of the expression corresponding to x.
// If x is invalid the position is nopos.
func (x *operand) Pos() syntax.Pos {
// special-case nil
if isTypes2 {
if x.mode_ == nilvalue {
- switch x.typ_ {
+ switch x.typ() {
case nil, Typ[Invalid]:
return "nil (with invalid type)"
case Typ[UntypedNil]:
return "nil"
default:
- return fmt.Sprintf("nil (of type %s)", TypeString(x.typ_, qf))
+ return fmt.Sprintf("nil (of type %s)", TypeString(x.typ(), qf))
}
}
} else { // go/types
- if x.mode_ == value && x.typ_ == Typ[UntypedNil] {
+ if x.mode_ == value && x.typ() == Typ[UntypedNil] {
return "nil"
}
}
case builtin:
expr = predeclaredFuncs[x.id].name
case typexpr:
- expr = TypeString(x.typ_, qf)
+ expr = TypeString(x.typ(), qf)
case constant_:
expr = x.val.String()
}
// no type
default:
// should have a type, but be cautious (don't crash during printing)
- if x.typ_ != nil {
- if isUntyped(x.typ_) {
- buf.WriteString(x.typ_.(*Basic).name)
+ if x.typ() != nil {
+ if isUntyped(x.typ()) {
+ buf.WriteString(x.typ().(*Basic).name)
buf.WriteByte(' ')
break
}
// <typ>
if hasType {
- if isValid(x.typ_) {
+ if isValid(x.typ()) {
var desc string
- if isGeneric(x.typ_) {
+ if isGeneric(x.typ()) {
desc = "generic "
}
// If the type is a renamed basic type, describe the basic type,
// as in "int32 type MyInt" for a *Named type MyInt.
// If it is a type parameter, describe the constraint instead.
- tpar, _ := Unalias(x.typ_).(*TypeParam)
+ tpar, _ := Unalias(x.typ()).(*TypeParam)
if tpar == nil {
- switch x.typ_.(type) {
+ switch x.typ().(type) {
case *Alias, *Named:
- what := compositeKind(x.typ_)
+ what := compositeKind(x.typ())
if what == "" {
// x.typ must be basic type
- what = x.typ_.Underlying().(*Basic).name
+ what = x.typ().Underlying().(*Basic).name
}
desc += what + " "
}
// desc is "" or has a trailing space at the end
buf.WriteString(" of " + desc + "type ")
- WriteType(&buf, x.typ_, qf)
+ WriteType(&buf, x.typ(), qf)
if tpar != nil {
buf.WriteString(" constrained by ")
if isTypes2 {
return x.mode_ == nilvalue
} else { // go/types
- return x.mode_ == value && x.typ_ == Typ[UntypedNil]
+ return x.mode_ == value && x.typ() == Typ[UntypedNil]
}
}
}
origT := T
- V := Unalias(x.typ_)
+ V := Unalias(x.typ())
T = Unalias(T)
// x's type is identical to T
}
ok, code = x.assignableTo(check, T.typ, cause)
if !ok {
- errorf("cannot assign %s to %s (in %s)", x.typ_, T.typ, Tp)
+ errorf("cannot assign %s to %s (in %s)", x.typ(), T.typ, Tp)
return false
}
return true
check.expr(nil, &x, rangeVar)
if isTypes2 && x.mode_ != invalid && sValue == nil && !check.hasCallOrRecv {
- if t, ok := arrayPtrDeref(x.typ_.Underlying()).(*Array); ok {
+ if t, ok := arrayPtrDeref(x.typ().Underlying()).(*Array); ok {
for {
// Put constant info on the thing inside parentheses.
// That's where (*../noder/writer).expr expects it.
// determine key/value types
var key, val Type
if x.mode_ != invalid {
- k, v, cause, ok := rangeKeyVal(check, x.typ_, func(v goVersion) bool {
+ k, v, cause, ok := rangeKeyVal(check, x.typ(), func(v goVersion) bool {
return check.allowVersion(v)
})
switch {
lhs := [2]syntax.Expr{sKey, sValue} // sKey, sValue may be nil
rhs := [2]Type{key, val} // key, val may be nil
- rangeOverInt := isInteger(x.typ_)
+ rangeOverInt := isInteger(x.typ())
if isDef {
// short variable declaration
// If the assignment succeeded, if x was untyped before, it now
// has a type inferred via the assignment. It must be an integer.
// (go.dev/issues/67027)
- if x.mode_ != invalid && !isInteger(x.typ_) {
- check.softErrorf(lhs, InvalidRangeExpr, "cannot use iteration variable of type %s", x.typ_)
+ if x.mode_ != invalid && !isInteger(x.typ()) {
+ check.softErrorf(lhs, InvalidRangeExpr, "cannot use iteration variable of type %s", x.typ())
}
} else {
var y operand
case novalue:
typ = (*Tuple)(nil)
case constant_:
- typ = x.typ_
+ typ = x.typ()
val = x.val
default:
- typ = x.typ_
+ typ = x.typ()
}
assert(x.expr != nil && typ != nil)
if a[0].mode_ == invalid {
return
}
- t0, t1 := a[0].typ_, a[1].typ_
+ t0, t1 := a[0].typ(), a[1].typ()
assert(isTyped(t0) && isTyped(t1) && (allBoolean(t1) || t1 == universeError))
if m := check.Types; m != nil {
for {
if x.mode_ == invalid || v.mode_ == invalid {
continue L
}
- check.convertUntyped(&v, x.typ_)
+ check.convertUntyped(&v, x.typ())
if v.mode_ == invalid {
continue L
}
// look for duplicate types for a given value
// (quadratic algorithm, but these lists tend to be very short)
for _, vt := range seen[val] {
- if Identical(v.typ_, vt.typ) {
+ if Identical(v.typ(), vt.typ) {
err := check.newError(DuplicateCase)
err.addf(&v, "duplicate case %s in expression switch", &v)
err.addf(vt.pos, "previous case")
continue L
}
}
- seen[val] = append(seen[val], valueType{v.Pos(), v.typ_})
+ seen[val] = append(seen[val], valueType{v.Pos(), v.typ()})
}
}
}
if len(types) != 1 || T == nil {
T = Typ[Invalid]
if x != nil {
- T = x.typ_
+ T = x.typ()
}
}
if len(types) != 1 || T == nil {
T = Typ[Invalid]
if x != nil {
- T = x.typ_
+ T = x.typ()
}
}
if x.mode_ == invalid {
return
}
- if !allNumeric(x.typ_) {
- check.errorf(s.Lhs, NonNumericIncDec, invalidOp+"%s%s%s (non-numeric type %s)", s.Lhs, s.Op, s.Op, x.typ_)
+ if !allNumeric(x.typ()) {
+ check.errorf(s.Lhs, NonNumericIncDec, invalidOp+"%s%s%s (non-numeric type %s)", s.Lhs, s.Op, s.Op, x.typ())
return
}
check.assignVar(s.Lhs, nil, &x, "assignment")
check.simpleStmt(s.Init)
var x operand
check.expr(nil, &x, s.Cond)
- if x.mode_ != invalid && !allBoolean(x.typ_) {
+ if x.mode_ != invalid && !allBoolean(x.typ()) {
check.error(s.Cond, InvalidCond, "non-boolean condition in if statement")
}
check.stmt(inner, s.Then)
if s.Cond != nil {
var x operand
check.expr(nil, &x, s.Cond)
- if x.mode_ != invalid && !allBoolean(x.typ_) {
+ if x.mode_ != invalid && !allBoolean(x.typ()) {
check.error(s.Cond, InvalidCond, "non-boolean condition in for statement")
}
}
// By checking assignment of x to an invisible temporary
// (as a compiler would), we get all the relevant checks.
check.assignment(&x, nil, "switch expression")
- if x.mode_ != invalid && !Comparable(x.typ_) && !hasNil(x.typ_) {
- check.errorf(&x, InvalidExprSwitch, "cannot switch on %s (%s is not comparable)", &x, x.typ_)
+ if x.mode_ != invalid && !Comparable(x.typ()) && !hasNil(x.typ()) {
+ check.errorf(&x, InvalidExprSwitch, "cannot switch on %s (%s is not comparable)", &x, x.typ())
x.mode_ = invalid
}
} else {
var x operand
check.expr(nil, &x, guard.X)
if x.mode_ != invalid {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(&x, InvalidTypeSwitch, "cannot use type switch on type parameter value %s", &x)
- } else if IsInterface(x.typ_) {
+ } else if IsInterface(x.typ()) {
sx = &x
} else {
check.errorf(&x, InvalidTypeSwitch, "%s is not an interface", &x)
switch x.mode_ {
case typexpr:
- return x.typ_
+ return x.typ()
case invalid:
// ignore - error reported before
case novalue:
switch x.mode_ {
case typexpr:
- return x.typ_
+ return x.typ()
case invalid:
// ignore - error reported before
case novalue:
return -1
}
- if isUntyped(x.typ_) || isInteger(x.typ_) {
+ 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 {
}
var msg string
- if isInteger(x.typ_) {
+ if isInteger(x.typ()) {
msg = "invalid array length %s"
} else {
msg = "array length %s must be integer"
return
}
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
target := T
// spec: "If an untyped constant is assigned to a variable of interface
// type or the blank identifier, the constant is first converted to type
return
}
} else if T == nil || isNonTypeParamInterface(T) {
- target = Default(x.typ_)
+ target = Default(x.typ())
}
} else { // go/types
if T == nil || isNonTypeParamInterface(T) {
- if T == nil && x.typ_ == Typ[UntypedNil] {
+ if T == nil && x.typ() == Typ[UntypedNil] {
check.errorf(x, UntypedNilUse, "use of untyped nil in %s", context)
x.mode_ = invalid
return
}
- target = Default(x.typ_)
+ target = Default(x.typ())
}
}
newType, val, code := check.implicitTypeAndValue(x, target)
x.val = val
check.updateExprVal(x.expr, val)
}
- if newType != x.typ_ {
+ if newType != x.typ() {
x.typ_ = newType
check.updateExprType(x.expr, newType, false)
}
}
func (check *Checker) initConst(lhs *Const, x *operand) {
- if x.mode_ == invalid || !isValid(x.typ_) || !isValid(lhs.typ) {
+ if x.mode_ == invalid || !isValid(x.typ()) || !isValid(lhs.typ) {
if lhs.typ == nil {
lhs.typ = Typ[Invalid]
}
}
return
}
- assert(isConstType(x.typ_))
+ assert(isConstType(x.typ()))
// If the lhs doesn't have a type yet, use the type of x.
if lhs.typ == nil {
- lhs.typ = x.typ_
+ lhs.typ = x.typ()
}
check.assignment(x, lhs.typ, "constant declaration")
// or Typ[Invalid] in case of an error.
// If the initialization check fails, x.mode is set to invalid.
func (check *Checker) initVar(lhs *Var, x *operand, context string) {
- if x.mode_ == invalid || !isValid(x.typ_) || !isValid(lhs.typ) {
+ if x.mode_ == invalid || !isValid(x.typ()) || !isValid(lhs.typ) {
if lhs.typ == nil {
lhs.typ = Typ[Invalid]
}
// If lhs doesn't have a type yet, use the type of x.
if lhs.typ == nil {
- typ := x.typ_
+ typ := x.typ()
if isUntyped(typ) {
// convert untyped types to default types
if typ == Typ[UntypedNil] {
check.usedVars[v] = v_used // restore v.used
}
- if x.mode_ == invalid || !isValid(x.typ_) {
+ if x.mode_ == invalid || !isValid(x.typ()) {
return Typ[Invalid]
}
return Typ[Invalid]
}
- return x.typ_
+ return x.typ()
}
// assignVar checks the assignment lhs = rhs (if x == nil), or lhs = x (if x != nil).
// operandTypes returns the list of types for the given operands.
func operandTypes(list []*operand) (res []Type) {
for _, x := range list {
- res = append(res, x.typ_)
+ res = append(res, x.typ())
}
return res
}
if ok, _ := x.assignableTo(check, NewSlice(universeByte), nil); ok {
y := args[1]
hasString := false
- for _, u := range typeset(y.typ_) {
+ for _, u := range typeset(y.typ()) {
if s, _ := u.(*Slice); s != nil && Identical(s.elem, universeByte) {
// typeset ⊇ {[]byte}
} else if isString(u) {
}
if y != nil && hasString {
// setting the signature also signals that we're done
- sig = makeSig(x.typ_, x.typ_, y.typ_)
+ sig = makeSig(x.typ(), x.typ(), y.typ())
sig.variadic = true
}
}
// general case
if sig == nil {
// check arguments by creating custom signature
- sig = makeSig(x.typ_, x.typ_, NewSlice(E)) // []E required for variadic signature
+ sig = makeSig(x.typ(), x.typ(), NewSlice(E)) // []E required for variadic signature
sig.variadic = true
check.arguments(call, sig, nil, nil, args, nil) // discard result (we know the result type)
// ok to continue even if check.arguments reported errors
// len(x)
mode := invalid
var val constant.Value
- switch t := arrayPtrDeref(x.typ_.Underlying()).(type) {
+ switch t := arrayPtrDeref(x.typ().Underlying()).(type) {
case *Basic:
if isString(t) && id == _Len {
if x.mode_ == constant_ {
}
case *Interface:
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
break
}
- if underIs(x.typ_, func(u Type) bool {
+ if underIs(x.typ(), func(u Type) bool {
switch t := arrayPtrDeref(u).(type) {
case *Basic:
if isString(t) && id == _Len {
if mode == invalid {
// avoid error if underlying type is invalid
- if isValid(x.typ_.Underlying()) {
+ if isValid(x.typ().Underlying()) {
code := InvalidCap
if id == _Len {
code = InvalidLen
// record the signature before changing x.typ
if check.recordTypes() && mode != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ()))
}
x.mode_ = mode
// clear(m)
check.verifyVersionf(call.Fun, go1_21, "clear")
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
switch u.(type) {
case *Map, *Slice:
return true
x.mode_ = novalue
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(nil, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(nil, x.typ()))
}
case _Close:
// close(c)
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
uch, _ := u.(*Chan)
if uch == nil {
check.errorf(x, InvalidClose, invalidOp+"cannot close non-channel %s", x)
}
x.mode_ = novalue
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(nil, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(nil, x.typ()))
}
case _Complex:
// convert or check untyped arguments
d := 0
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
d |= 1
}
- if isUntyped(y.typ_) {
+ if isUntyped(y.typ()) {
d |= 2
}
switch d {
// x and y are typed => nothing to do
case 1:
// only x is untyped => convert to type of y
- check.convertUntyped(x, y.typ_)
+ check.convertUntyped(x, y.typ())
case 2:
// only y is untyped => convert to type of x
- check.convertUntyped(y, x.typ_)
+ check.convertUntyped(y, x.typ())
case 3:
// x and y are untyped =>
// 1) if both are constants, convert them to untyped
// because shifts of floats are not permitted)
if x.mode_ == constant_ && y.mode_ == constant_ {
toFloat := func(x *operand) {
- if isNumeric(x.typ_) && constant.Sign(constant.Imag(x.val)) == 0 {
+ if isNumeric(x.typ()) && constant.Sign(constant.Imag(x.val)) == 0 {
x.typ_ = Typ[UntypedFloat]
}
}
}
// both argument types must be identical
- if !Identical(x.typ_, y.typ_) {
- check.errorf(x, InvalidComplex, invalidOp+"%v (mismatched types %s and %s)", call, x.typ_, y.typ_)
+ if !Identical(x.typ(), y.typ()) {
+ check.errorf(x, InvalidComplex, invalidOp+"%v (mismatched types %s and %s)", call, x.typ(), y.typ())
return
}
}
resTyp := check.applyTypeFunc(f, x, id)
if resTyp == nil {
- check.errorf(x, InvalidComplex, invalidArg+"arguments have type %s, expected floating-point", x.typ_)
+ check.errorf(x, InvalidComplex, invalidArg+"arguments have type %s, expected floating-point", x.typ())
return
}
}
if check.recordTypes() && x.mode_ != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ_, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ(), x.typ()))
}
x.typ_ = resTyp
var special bool
if ok, _ := x.assignableTo(check, NewSlice(universeByte), nil); ok {
special = true
- for _, u := range typeset(y.typ_) {
+ for _, u := range typeset(y.typ()) {
if s, _ := u.(*Slice); s != nil && Identical(s.elem, universeByte) {
// typeset ⊇ {[]byte}
} else if isString(u) {
srcE, err := sliceElem(y)
if err != nil {
// If we have a string, for a better error message proceed with byte element type.
- if !allString(y.typ_) {
+ if !allString(y.typ()) {
check.errorf(y, InvalidCopy, "invalid copy: %s", err.format(check))
return
}
}
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ_, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ(), y.typ()))
}
x.mode_ = value
x.typ_ = Typ[Int]
// delete(map_, key)
// map_ must be a map type or a type parameter describing map types.
// The key cannot be a type parameter for now.
- map_ := x.typ_
+ map_ := x.typ()
var key Type
if !underIs(map_, func(u Type) bool {
map_, _ := u.(*Map)
// real(complexT) floatT
// convert or check untyped argument
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
if x.mode_ == constant_ {
// an untyped constant number can always be considered
// as a complex constant
- if isNumeric(x.typ_) {
+ if isNumeric(x.typ()) {
x.typ_ = Typ[UntypedComplex]
}
} else {
if id == _Real {
code = InvalidReal
}
- check.errorf(x, code, invalidArg+"argument has type %s, expected complex type", x.typ_)
+ check.errorf(x, code, invalidArg+"argument has type %s, expected complex type", x.typ())
return
}
}
if check.recordTypes() && x.mode_ != constant_ {
- check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ()))
}
x.typ_ = resTyp
x.mode_ = value
x.typ_ = T
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, types...))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), types...))
}
case _Max, _Min:
return
}
- if !allOrdered(a.typ_) {
+ if !allOrdered(a.typ()) {
check.errorf(a, InvalidMinMaxOperand, invalidArg+"%s cannot be ordered", a)
return
}
return
}
- if !Identical(x.typ_, a.typ_) {
- check.errorf(a, MismatchedTypes, invalidArg+"mismatched types %s (previous argument) and %s (type of %s)", x.typ_, a.typ_, a.expr)
+ if !Identical(x.typ(), a.typ()) {
+ check.errorf(a, MismatchedTypes, invalidArg+"mismatched types %s (previous argument) and %s (type of %s)", x.typ(), a.typ(), a.expr)
return
}
// Use the final type computed above for all arguments.
for _, a := range args {
- check.updateExprType(a.expr, x.typ_, true)
+ check.updateExprType(a.expr, x.typ(), true)
}
if check.recordTypes() && x.mode_ != constant_ {
types := make([]Type, nargs)
for i := range types {
- types[i] = x.typ_
+ types[i] = x.typ()
}
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, types...))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), types...))
}
case _New:
return
case typexpr:
// new(T)
- check.validVarType(arg, x.typ_)
+ check.validVarType(arg, x.typ())
default:
// new(expr)
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
// check for overflow and untyped nil
check.assignment(x, nil, "argument to new")
if x.mode_ == invalid {
return
}
- assert(isTyped(x.typ_))
+ assert(isTyped(x.typ()))
}
// report version error only if there are no other errors
check.verifyVersionf(call.Fun, go1_26, "new(%s)", arg)
}
- T := x.typ_
+ T := x.typ()
x.mode_ = value
x.typ_ = NewPointer(T)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, T))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), T))
}
case _Panic:
if a.mode_ == invalid {
return
}
- params[i] = a.typ_
+ params[i] = a.typ()
}
}
x.mode_ = value
x.typ_ = &emptyInterface
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ()))
}
case _Add:
x.mode_ = value
x.typ_ = Typ[UnsafePointer]
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, x.typ_, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), x.typ(), y.typ()))
}
case _Alignof:
return
}
- if check.hasVarSize(x.typ_) {
+ if check.hasVarSize(x.typ()) {
x.mode_ = value
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ()))
}
} else {
x.mode_ = constant_
- x.val = constant.MakeInt64(check.conf.alignof(x.typ_))
+ x.val = constant.MakeInt64(check.conf.alignof(x.typ()))
// result is constant - no need to record signature
}
x.typ_ = Typ[Uintptr]
return
}
- base := derefStructPtr(x.typ_)
+ base := derefStructPtr(x.typ())
sel := selx.Sel.Name
obj, index, indirect := lookupFieldOrMethod(base, false, check.pkg, sel, false)
switch obj.(type) {
return
}
- if check.hasVarSize(x.typ_) {
+ if check.hasVarSize(x.typ()) {
x.mode_ = value
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ()))
}
} else {
- size := check.conf.sizeof(x.typ_)
+ size := check.conf.sizeof(x.typ())
if size < 0 {
check.errorf(x, TypeTooLarge, "%s is too large", x)
return
// unsafe.Slice(ptr *T, len IntegerType) []T
check.verifyVersionf(call.Fun, go1_17, "unsafe.Slice")
- u, _ := commonUnder(x.typ_, nil)
+ u, _ := commonUnder(x.typ(), nil)
ptr, _ := u.(*Pointer)
if ptr == nil {
check.errorf(x, InvalidUnsafeSlice, invalidArg+"%s is not a pointer", x)
x.mode_ = value
x.typ_ = NewSlice(ptr.base)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, ptr, y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), ptr, y.typ()))
}
case _SliceData:
// unsafe.SliceData(slice []T) *T
check.verifyVersionf(call.Fun, go1_20, "unsafe.SliceData")
- u, _ := commonUnder(x.typ_, nil)
+ u, _ := commonUnder(x.typ(), nil)
slice, _ := u.(*Slice)
if slice == nil {
check.errorf(x, InvalidUnsafeSliceData, invalidArg+"%s is not a slice", x)
x.mode_ = value
x.typ_ = NewPointer(slice.elem)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, slice))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), slice))
}
case _String:
x.mode_ = value
x.typ_ = Typ[String]
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, NewPointer(universeByte), y.typ_))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), NewPointer(universeByte), y.typ()))
}
case _StringData:
x.mode_ = value
x.typ_ = NewPointer(universeByte)
if check.recordTypes() {
- check.recordBuiltinType(call.Fun, makeSig(x.typ_, Typ[String]))
+ check.recordBuiltinType(call.Fun, makeSig(x.typ(), Typ[String]))
}
case _Assert:
// assert(pred) causes a typechecker error if pred is false.
// The result of assert is the value of pred if there is no error.
// Note: assert is only available in self-test mode.
- if x.mode_ != constant_ || !isBoolean(x.typ_) {
+ if x.mode_ != constant_ || !isBoolean(x.typ()) {
check.errorf(x, Test, invalidArg+"%s is not a boolean constant", x)
return
}
// or a type error if x is not a slice (or a type set of slices).
func sliceElem(x *operand) (Type, *typeError) {
var E Type
- for _, u := range typeset(x.typ_) {
+ for _, u := range typeset(x.typ()) {
s, _ := u.(*Slice)
if s == nil {
if x.isNil() {
// applyTypeFunc returns nil.
// If x is not a type parameter, the result is f(x).
func (check *Checker) applyTypeFunc(f func(Type) Type, x *operand, id builtinId) Type {
- if tp, _ := Unalias(x.typ_).(*TypeParam); tp != nil {
+ if tp, _ := Unalias(x.typ()).(*TypeParam); tp != nil {
// Test if t satisfies the requirements for the argument
// type and collect possible result types at the same time.
var terms []*Term
return ptyp
}
- return f(x.typ_)
+ return f(x.typ())
}
// makeSig makes a signature for the given argument and result types.
// Check the number of type arguments (got) vs number of type parameters (want).
// Note that x is a function value, not a type expression, so we don't need to
// call Underlying below.
- sig := x.typ_.(*Signature)
+ sig := x.typ().(*Signature)
got, want := len(targs), sig.TypeParams().Len()
if got > want {
// Providing too many type arguments is always an error.
if x.mode_ == invalid {
return conversion
}
- T := x.typ_
+ T := x.typ()
x.mode_ = invalid
// We cannot convert a value to an incomplete type; make sure it's complete.
if !check.isComplete(T) {
// If the operand type is a type parameter, all types in its type set
// must have a common underlying type, which must be a signature.
- u, err := commonUnder(x.typ_, func(t, u Type) *typeError {
+ u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
if _, ok := u.(*Signature); u != nil && !ok {
return typeErrorf("%s is not a function", t)
}
// if type inference failed, a parameterized result must be invalidated
// (operands cannot have a parameterized type)
- if x.mode_ == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ_) {
+ if x.mode_ == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ()) {
x.mode_ = invalid
}
if i < len(targsList) {
if n := len(targsList[i]); n > 0 {
// x must be a partially instantiated function
- assert(n < x.typ_.(*Signature).TypeParams().Len())
+ assert(n < x.typ().(*Signature).TypeParams().Len())
}
}
}
// x is not a function instantiation (it may still be a generic function).
check.rawExpr(nil, &x, e, nil, true)
check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
- if t, ok := x.typ_.(*Tuple); ok && x.mode_ != invalid {
+ if t, ok := x.typ().(*Tuple); ok && x.mode_ != invalid {
// x is a function call returning multiple values; it cannot be generic.
resList = make([]*operand, t.Len())
for i, v := range t.vars {
if enableReverseTypeInference {
for i, arg := range args {
// generic arguments cannot have a defined (*Named) type - no need for underlying type below
- if asig, _ := arg.typ_.(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
+ if asig, _ := arg.typ().(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
// The argument type is a generic function signature. This type is
// pointer-identical with (it's copied from) the type of the generic
// function argument and thus the function object.
j := n
for _, i := range genericArgs {
arg := args[i]
- asig := arg.typ_.(*Signature)
+ asig := arg.typ().(*Signature)
k := j + asig.TypeParams().Len()
// targs[j:k] are the inferred type arguments for asig
arg.typ_ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations)
x.mode_ = variable
x.typ_ = exp.typ
if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
- x.typ_ = x.typ_.(*Pointer).base
+ x.typ_ = x.typ().(*Pointer).base
}
case *Func:
x.mode_ = funcMode
x.typ_ = exp.typ
if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
x.mode_ = value
- x.typ_ = x.typ_.(*Signature).results.vars[0].typ
+ x.typ_ = x.typ().(*Signature).results.vars[0].typ
}
case *Builtin:
x.mode_ = builtin
}
// We cannot select on an incomplete type; make sure it's complete.
- if !check.isComplete(x.typ_) {
+ if !check.isComplete(x.typ()) {
goto Error
}
// Additionally, if x.typ is a pointer type, selecting implicitly dereferences the value, meaning
// its base type must also be complete.
- if p, ok := x.typ_.Underlying().(*Pointer); ok && !check.isComplete(p.base) {
+ if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
goto Error
}
- obj, index, indirect = lookupFieldOrMethod(x.typ_, x.mode_ == variable, check.pkg, sel, false)
+ obj, index, indirect = lookupFieldOrMethod(x.typ(), x.mode_ == variable, check.pkg, sel, false)
if obj == nil {
// Don't report another error if the underlying type was invalid (go.dev/issue/49541).
- if !isValid(x.typ_.Underlying()) {
+ if !isValid(x.typ().Underlying()) {
goto Error
}
if indirect {
if x.mode_ == typexpr {
- check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ_, sel, x.typ_, sel)
+ check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ(), sel, x.typ(), sel)
} else {
- check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ_)
+ check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ())
}
goto Error
}
var why string
- if isInterfacePtr(x.typ_) {
- why = check.interfacePtrError(x.typ_)
+ if isInterfacePtr(x.typ()) {
+ why = check.interfacePtrError(x.typ())
} else {
- alt, _, _ := lookupFieldOrMethod(x.typ_, x.mode_ == variable, check.pkg, sel, true)
- why = check.lookupError(x.typ_, sel, alt, false)
+ alt, _, _ := lookupFieldOrMethod(x.typ(), x.mode_ == variable, check.pkg, sel, true)
+ why = check.lookupError(x.typ(), sel, alt, false)
}
check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
goto Error
switch obj := obj.(type) {
case *Var:
if x.mode_ == typexpr {
- check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ_)
+ check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ())
goto Error
}
// field value
- check.recordSelection(e, FieldVal, x.typ_, obj, index, indirect)
+ check.recordSelection(e, FieldVal, x.typ(), obj, index, indirect)
if x.mode_ == variable || indirect {
x.mode_ = variable
} else {
if x.mode_ == typexpr {
// method expression
- check.recordSelection(e, MethodExpr, x.typ_, obj, index, indirect)
+ check.recordSelection(e, MethodExpr, x.typ(), obj, index, indirect)
sig := obj.typ.(*Signature)
if sig.recv == nil {
name = "_"
}
}
- params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ_)}, params...)
+ params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ())}, params...)
x.mode_ = value
x.typ_ = &Signature{
tparams: sig.tparams,
// TODO(gri) If we needed to take into account the receiver's
// addressability, should we report the type &(x.typ) instead?
- check.recordSelection(e, MethodVal, x.typ_, obj, index, indirect)
+ check.recordSelection(e, MethodVal, x.typ(), obj, index, indirect)
// TODO(gri) The verification pass below is disabled for now because
// method sets don't match method lookup in some cases.
// their type after each constant operation.
// x.typ cannot be a type parameter (type
// parameters cannot be constant types).
- if isTyped(x.typ_) {
- check.representable(x, x.typ_.Underlying().(*Basic))
+ if isTyped(x.typ()) {
+ check.representable(x, x.typ().Underlying().(*Basic))
return
}
assert(x.mode_ == constant_)
v := x.val
if !representableConst(x.val, check, typ, &v) {
- if isNumeric(x.typ_) && isNumeric(typ) {
+ if isNumeric(x.typ()) && isNumeric(typ) {
// numeric conversion : error msg
//
// integer -> integer : overflows
// float -> integer : truncated
// float -> float : overflows
//
- if !isInteger(x.typ_) && isInteger(typ) {
+ if !isInteger(x.typ()) && isInteger(typ) {
return nil, TruncatedFloat
} else {
return nil, NumericOverflow
x.val = val
check.updateExprVal(x.expr, val)
}
- if newType != x.typ_ {
+ if newType != x.typ() {
x.typ_ = newType
check.updateExprType(x.expr, newType, false)
}
// nothing to do
case representableConst(x.val, check, t, val):
return true
- case isInteger(x.typ_) && isString(t):
+ case isInteger(x.typ()) && isString(t):
codepoint := unicode.ReplacementChar
if i, ok := constant.Uint64Val(x.val); ok && i <= unicode.MaxRune {
codepoint = rune(i)
// A conversion from an integer constant to an integer type
// can only fail if there's overflow. Give a concise error.
// (go.dev/issue/63563)
- if !ok && isInteger(x.typ_) && isInteger(T) {
+ if !ok && isInteger(x.typ()) && isInteger(T) {
check.errorf(x, InvalidConversion, "constant %s overflows %s", x.val, T)
x.mode_ = invalid
return
cause = check.sprintf("%s does not contain specific types", T)
return false
}
- if isString(x.typ_) && isBytesOrRunes(u) {
+ if isString(x.typ()) && isBytesOrRunes(u) {
return true
}
if !constConvertibleTo(u, nil) {
- if isInteger(x.typ_) && isInteger(u) {
+ if isInteger(x.typ()) && isInteger(u) {
// see comment above on constant conversion
cause = check.sprintf("constant %s overflows %s (in %s)", x.val, u, T)
} else {
// The conversion argument types are final. For untyped values the
// conversion provides the type, per the spec: "A constant may be
// given a type explicitly by a constant declaration or conversion,...".
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
final := T
// - For conversions to interfaces, except for untyped nil arguments
// and isTypes2, use the argument's default type.
// - If !isTypes2, keep untyped nil for untyped nil arguments.
// - For constant integer to string conversions, keep the argument type.
// (See also the TODO below.)
- if isTypes2 && x.typ_ == Typ[UntypedNil] {
+ if isTypes2 && x.typ() == Typ[UntypedNil] {
// ok
} else if isNonTypeParamInterface(T) || constArg && !isConstType(T) || !isTypes2 && x.isNil() {
- final = Default(x.typ_) // default type of untyped nil is untyped nil
- } else if x.mode_ == constant_ && isInteger(x.typ_) && allString(T) {
- final = x.typ_
+ final = Default(x.typ()) // default type of untyped nil is untyped nil
+ } else if x.mode_ == constant_ && isInteger(x.typ()) && allString(T) {
+ final = x.typ()
}
check.updateExprType(x.expr, final, true)
}
}
origT := T
- V := Unalias(x.typ_)
+ V := Unalias(x.typ())
T = Unalias(T)
Vu := V.Underlying()
Tu := T.Underlying()
return false // no specific types
}
if !x.convertibleTo(check, T.typ, cause) {
- errorf("cannot convert %s to type %s (in %s)", x.typ_, T.typ, Tp)
+ errorf("cannot convert %s to type %s (in %s)", x.typ(), T.typ, Tp)
return false
}
return true
func f(x *operand, e *ast.Expr, ...)
where e is the expression to be checked, and x is the result of the check.
-The check performed by f may fail in which case x.mode == invalid, and
+The check performed by f may fail in which case x.mode_ == invalid, and
related error messages will have been issued by f.
If a hint argument is present, it is the composite literal element type
func (check *Checker) op(m opPredicates, x *operand, op token.Token) bool {
if pred := m[op]; pred != nil {
- if !pred(x.typ_) {
+ if !pred(x.typ()) {
check.errorf(x, UndefinedOp, invalidOp+"operator %s not defined on %s", op, x)
return false
}
return
}
x.mode_ = value
- x.typ_ = &Pointer{base: x.typ_}
+ x.typ_ = &Pointer{base: x.typ()}
return
case token.ARROW:
case token.TILDE:
// Provide a better error position and message than what check.op below would do.
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint")
x.mode_ = invalid
return
return
}
var prec uint
- if isUnsigned(x.typ_) {
- prec = uint(check.conf.sizeof(x.typ_) * 8)
+ if isUnsigned(x.typ()) {
+ prec = uint(check.conf.sizeof(x.typ()) * 8)
}
x.val = constant.UnaryOp(op, x.val, prec)
x.expr = e
// or send to x (recv == false) operation. If the operation is not valid, chanElem
// reports an error and returns nil.
func (check *Checker) chanElem(pos positioner, x *operand, recv bool) Type {
- u, err := commonUnder(x.typ_, func(t, u Type) *typeError {
+ u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
if u == nil {
return typeErrorf("no specific channel type")
}
cause := err.format(check)
if recv {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s: %s", x, cause)
} else {
// In this case, only the non-channel and send-only channel error are possible.
check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s %s", cause, x)
}
} else {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s: %s", x, cause)
} else {
// In this case, only the non-channel and receive-only channel error are possible.
// If x is a constant operand, the returned constant.Value will be the
// representation of x in this context.
func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code) {
- if x.mode_ == invalid || isTyped(x.typ_) || !isValid(target) {
- return x.typ_, nil, 0
+ if x.mode_ == invalid || isTyped(x.typ()) || !isValid(target) {
+ return x.typ(), nil, 0
}
// x is untyped
if isUntyped(target) {
// both x and target are untyped
- if m := maxType(x.typ_, target); m != nil {
+ if m := maxType(x.typ(), target); m != nil {
return m, nil, 0
}
return nil, nil, InvalidUntypedConversion
// result of comparisons (untyped bool), intermediate
// (delayed-checked) rhs operands of shifts, and as
// the value nil.
- switch x.typ_.(*Basic).kind {
+ switch x.typ().(*Basic).kind {
case UntypedBool:
if !isBoolean(target) {
return nil, nil, InvalidUntypedConversion
if !u.Empty() {
return nil, nil, InvalidUntypedConversion
}
- return Default(x.typ_), nil, 0
+ return Default(x.typ()), nil, 0
case *Pointer, *Signature, *Slice, *Map, *Chan:
if !x.isNil() {
return nil, nil, InvalidUntypedConversion
// If switchCase is true, the operator op is ignored.
func (check *Checker) comparison(x, y *operand, op token.Token, switchCase bool) {
// Avoid spurious errors if any of the operands has an invalid type (go.dev/issue/54405).
- if !isValid(x.typ_) || !isValid(y.typ_) {
+ if !isValid(x.typ()) || !isValid(y.typ()) {
x.mode_ = invalid
return
}
// spec: "In any comparison, the first operand must be assignable
// to the type of the second operand, or vice versa."
code := MismatchedTypes
- ok, _ := x.assignableTo(check, y.typ_, nil)
+ ok, _ := x.assignableTo(check, y.typ(), nil)
if !ok {
- ok, _ = y.assignableTo(check, x.typ_, nil)
+ ok, _ = y.assignableTo(check, x.typ(), nil)
}
if !ok {
// Report the error on the 2nd operand since we only
// know after seeing the 2nd operand whether we have
// a type mismatch.
errOp = y
- cause = check.sprintf("mismatched types %s and %s", x.typ_, y.typ_)
+ cause = check.sprintf("mismatched types %s and %s", x.typ(), y.typ())
goto Error
}
switch {
case x.isNil() || y.isNil():
// Comparison against nil requires that the other operand type has nil.
- typ := x.typ_
+ typ := x.typ()
if x.isNil() {
- typ = y.typ_
+ typ = y.typ()
}
if !hasNil(typ) {
// This case should only be possible for "nil == nil".
goto Error
}
- case !Comparable(x.typ_):
+ case !Comparable(x.typ()):
errOp = x
- cause = check.incomparableCause(x.typ_)
+ cause = check.incomparableCause(x.typ())
goto Error
- case !Comparable(y.typ_):
+ case !Comparable(y.typ()):
errOp = y
- cause = check.incomparableCause(y.typ_)
+ cause = check.incomparableCause(y.typ())
goto Error
}
case token.LSS, token.LEQ, token.GTR, token.GEQ:
// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
switch {
- case !allOrdered(x.typ_):
+ case !allOrdered(x.typ()):
errOp = x
goto Error
- case !allOrdered(y.typ_):
+ case !allOrdered(y.typ()):
errOp = y
goto Error
}
// time will be materialized. Update the expression trees.
// If the current types are untyped, the materialized type
// is the respective default type.
- check.updateExprType(x.expr, Default(x.typ_), true)
- check.updateExprType(y.expr, Default(y.typ_), true)
+ check.updateExprType(x.expr, Default(x.typ()), true)
+ check.updateExprType(y.expr, Default(y.typ()), true)
}
// spec: "Comparison operators compare two operands and yield
Error:
// We have an offending operand errOp and possibly an error cause.
if cause == "" {
- if isTypeParam(x.typ_) || isTypeParam(y.typ_) {
+ if isTypeParam(x.typ()) || isTypeParam(y.typ()) {
// TODO(gri) should report the specific type causing the problem, if any
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
errOp = y
}
- cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ_, op)
+ cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ(), op)
} else {
// catch-all neither x nor y is a type parameter
- what := compositeKind(errOp.typ_)
+ what := compositeKind(errOp.typ())
if what == "" {
- what = check.sprintf("%s", errOp.typ_)
+ what = check.sprintf("%s", errOp.typ())
}
cause = check.sprintf("operator %s not defined on %s", op, what)
}
xval = constant.ToInt(x.val)
}
- if allInteger(x.typ_) || isUntyped(x.typ_) && xval != nil && xval.Kind() == constant.Int {
+ if allInteger(x.typ()) || isUntyped(x.typ()) && xval != nil && xval.Kind() == constant.Int {
// The lhs is of integer type or an untyped constant representable
// as an integer. Nothing to do.
} else {
return
}
- if isUntyped(y.typ_) {
+ if isUntyped(y.typ()) {
// Caution: Check for representability here, rather than in the switch
// below, because isInteger includes untyped integers (was bug go.dev/issue/43697).
check.representable(y, Typ[Uint])
} else {
// Check that RHS is otherwise at least of integer type.
switch {
- case allInteger(y.typ_):
- if !allUnsigned(y.typ_) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
+ case allInteger(y.typ()):
+ if !allUnsigned(y.typ()) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
x.mode_ = invalid
return
}
- case isUntyped(y.typ_):
+ case isUntyped(y.typ()):
// This is incorrect, but preserves pre-existing behavior.
// See also go.dev/issue/47410.
check.convertUntyped(y, Typ[Uint])
if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
x.val = constant.MakeUnknown()
// ensure the correct type - see comment below
- if !isInteger(x.typ_) {
+ if !isInteger(x.typ()) {
x.typ_ = Typ[UntypedInt]
}
return
// (e.g., 2.0, an untyped float) - this can only happen for untyped
// non-integer numeric constants. Correct the type so that the shift
// result is of integer type.
- if !isInteger(x.typ_) {
+ if !isInteger(x.typ()) {
x.typ_ = Typ[UntypedInt]
}
// x is a constant so xval != nil and it must be of Int kind.
}
// non-constant shift with constant lhs
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
// spec: "If the left operand of a non-constant shift
// expression is an untyped constant, the type of the
// constant is what it would be if the shift expression
}
// non-constant shift - lhs must be an integer
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
x.mode_ = invalid
return
return
}
- if !Identical(x.typ_, y.typ_) {
+ if !Identical(x.typ(), y.typ()) {
// only report an error if we have valid types
// (otherwise we had an error reported elsewhere already)
- if isValid(x.typ_) && isValid(y.typ_) {
+ if isValid(x.typ()) && isValid(y.typ()) {
var posn positioner = x
if e != nil {
posn = e
}
if e != nil {
- check.errorf(posn, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ_, y.typ_)
+ check.errorf(posn, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ(), y.typ())
} else {
- check.errorf(posn, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ_, y.typ_)
+ check.errorf(posn, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ(), y.typ())
}
}
x.mode_ = invalid
if op == token.QUO || op == token.REM {
// check for zero divisor
- if (x.mode_ == constant_ || allInteger(x.typ_)) && y.mode_ == constant_ && constant.Sign(y.val) == 0 {
+ if (x.mode_ == constant_ || allInteger(x.typ())) && y.mode_ == constant_ && constant.Sign(y.val) == 0 {
check.error(&y, DivByZero, invalidOp+"division by zero")
x.mode_ = invalid
return
}
// check for divisor underflow in complex division (see go.dev/issue/20227)
- if x.mode_ == constant_ && y.mode_ == constant_ && isComplex(x.typ_) {
+ if x.mode_ == constant_ && y.mode_ == constant_ && isComplex(x.typ()) {
re, im := constant.Real(y.val), constant.Imag(y.val)
re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
return
}
// force integer division of integer operands
- if op == token.QUO && isInteger(x.typ_) {
+ if op == token.QUO && isInteger(x.typ()) {
op = token.QUO_ASSIGN
}
x.val = constant.BinaryOp(x.val, op, y.val)
// not compatible, we report a type mismatch error.
mayConvert := func(x, y *operand) bool {
// If both operands are typed, there's no need for an implicit conversion.
- if isTyped(x.typ_) && isTyped(y.typ_) {
+ if isTyped(x.typ()) && isTyped(y.typ()) {
return false
}
// A numeric type can only convert to another numeric type.
- if allNumeric(x.typ_) != allNumeric(y.typ_) {
+ if allNumeric(x.typ()) != allNumeric(y.typ()) {
return false
}
// An untyped operand may convert to its default type when paired with an empty interface
// TODO(gri) This should only matter for comparisons (the only binary operation that is
// valid with interfaces), but in that case the assignability check should take
// care of the conversion. Verify and possibly eliminate this extra test.
- if isNonTypeParamInterface(x.typ_) || isNonTypeParamInterface(y.typ_) {
+ if isNonTypeParamInterface(x.typ()) || isNonTypeParamInterface(y.typ()) {
return true
}
// A boolean type can only convert to another boolean type.
- if allBoolean(x.typ_) != allBoolean(y.typ_) {
+ if allBoolean(x.typ()) != allBoolean(y.typ()) {
return false
}
// A string type can only convert to another string type.
- if allString(x.typ_) != allString(y.typ_) {
+ if allString(x.typ()) != allString(y.typ()) {
return false
}
// Untyped nil can only convert to a type that has a nil.
if x.isNil() {
- return hasNil(y.typ_)
+ return hasNil(y.typ())
}
if y.isNil() {
- return hasNil(x.typ_)
+ return hasNil(x.typ())
}
// An untyped operand cannot convert to a pointer.
// TODO(gri) generalize to type parameters
- if isPointer(x.typ_) || isPointer(y.typ_) {
+ if isPointer(x.typ()) || isPointer(y.typ()) {
return false
}
return true
}
if mayConvert(x, y) {
- check.convertUntyped(x, y.typ_)
+ check.convertUntyped(x, y.typ())
if x.mode_ == invalid {
return
}
- check.convertUntyped(y, x.typ_)
+ check.convertUntyped(y, x.typ())
if y.mode_ == invalid {
x.mode_ = invalid
return
return
}
var what string
- switch t := x.typ_.(type) {
+ switch t := x.typ().(type) {
case *Alias, *Named:
if isGeneric(t) {
what = "type"
check.error(e, BadTypeKeyword, "use of .(type) outside type switch")
goto Error
}
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(x, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", x)
goto Error
}
- if _, ok := x.typ_.Underlying().(*Interface); !ok {
+ if _, ok := x.typ().Underlying().(*Interface); !ok {
check.errorf(x, InvalidAssert, invalidOp+"%s is not an interface", x)
goto Error
}
case invalid:
goto Error
case typexpr:
- check.validVarType(e.X, x.typ_)
- x.typ_ = &Pointer{base: x.typ_}
+ check.validVarType(e.X, x.typ())
+ x.typ_ = &Pointer{base: x.typ()}
default:
var base Type
- if !underIs(x.typ_, func(u Type) bool {
+ if !underIs(x.typ(), func(u Type) bool {
p, _ := u.(*Pointer)
if p == nil {
check.errorf(x, InvalidIndirection, invalidOp+"cannot indirect %s", x)
// typeAssertion checks x.(T). The type of x must be an interface.
func (check *Checker) typeAssertion(e ast.Expr, x *operand, T Type, typeSwitch bool) {
var cause string
- if check.assertableTo(x.typ_, T, &cause) {
+ if check.assertableTo(x.typ(), T, &cause) {
return // success
}
return
}
- check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ_, cause)
+ check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ(), cause)
}
// expr typechecks expression e and initializes x with the expression value.
check.rawExpr(nil, &x, e, nil, false)
check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
- if t, ok := x.typ_.(*Tuple); ok && x.mode_ != invalid {
+ if t, ok := x.typ().(*Tuple); ok && x.mode_ != invalid {
// multiple values
list = make([]*operand, t.Len())
for i, v := range t.vars {
func (check *Checker) singleValue(x *operand) {
if x.mode_ == value {
// tuple types are never named - no need for underlying type below
- if t, ok := x.typ_.(*Tuple); ok {
+ if t, ok := x.typ().(*Tuple); ok {
assert(t.Len() != 1)
check.errorf(x, TooManyValues, "multiple-value %s in single-value context", x)
x.mode_ = invalid
x.mode_ = invalid
// TODO(gri) here we re-evaluate e.X - try to avoid this
x.typ_ = check.varType(e.orig)
- if isValid(x.typ_) {
+ if isValid(x.typ()) {
x.mode_ = typexpr
}
return false
case value:
- if sig, _ := x.typ_.Underlying().(*Signature); sig != nil && sig.TypeParams().Len() > 0 {
+ if sig, _ := x.typ().Underlying().(*Signature); sig != nil && sig.TypeParams().Len() > 0 {
// function instantiation
return true
}
}
// We cannot index on an incomplete type; make sure it's complete.
- if !check.isComplete(x.typ_) {
+ if !check.isComplete(x.typ()) {
x.mode_ = invalid
return false
}
- switch typ := x.typ_.Underlying().(type) {
+ switch typ := x.typ().Underlying().(type) {
case *Pointer:
// Additionally, if x.typ is a pointer to an array type, indexing implicitly dereferences the value, meaning
// its base type must also be complete.
// ordinary index expression
valid := false
length := int64(-1) // valid if >= 0
- switch typ := x.typ_.Underlying().(type) {
+ switch typ := x.typ().Underlying().(type) {
case *Basic:
if isString(typ) {
valid = true
return false
case *Interface:
- if !isTypeParam(x.typ_) {
+ if !isTypeParam(x.typ()) {
break
}
// TODO(gri) report detailed failure cause for better error messages
var key, elem Type // key != nil: we must have all maps
mode := variable // non-maps result mode
// TODO(gri) factor out closure and use it for non-typeparam cases as well
- if underIs(x.typ_, func(u Type) bool {
+ if underIs(x.typ(), func(u Type) bool {
l := int64(-1) // valid if >= 0
var k, e Type // k is only set for maps
switch t := u.(type) {
// In pathological (invalid) cases (e.g.: type T1 [][[]T1{}[0][0]]T0)
// the element type may be accessed before it's set. Make sure we have
// a valid type.
- if x.typ_ == nil {
+ if x.typ() == nil {
x.typ_ = Typ[Invalid]
}
var ct, cu Type // type and respective common underlying type
var hasString bool
// TODO(adonovan): use go1.23 "range typeset()".
- typeset(x.typ_)(func(t, u Type) bool {
+ typeset(x.typ())(func(t, u Type) bool {
if u == nil {
- check.errorf(x, NonSliceableOperand, "cannot slice %s: no specific type in %s", x, x.typ_)
+ check.errorf(x, NonSliceableOperand, "cannot slice %s: no specific type in %s", x, x.typ())
cu = nil
return false
}
// If we saw a string, proceed with string type,
// but don't go from untyped string to string.
cu = Typ[String]
- if !isTypeParam(x.typ_) {
- cu = x.typ_.Underlying() // untyped string remains untyped
+ if !isTypeParam(x.typ()) {
+ cu = x.typ().Underlying() // untyped string remains untyped
}
}
// Note that we don't permit slice expressions where x is a type expression, so we don't check for that here.
// However, if x.typ is a pointer to an array type, slicing implicitly dereferences the value, meaning
// its base type must also be complete.
- if p, ok := x.typ_.Underlying().(*Pointer); ok && !check.isComplete(p.base) {
+ if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
x.mode_ = invalid
return
}
}
// spec: "For untyped string operands the result
// is a non-constant value of type string."
- if isUntyped(x.typ_) {
+ if isUntyped(x.typ()) {
x.typ_ = Typ[String]
}
}
}
if x.mode_ != constant_ {
- return x.typ_, -1
+ return x.typ(), -1
}
if x.val.Kind() == constant.Unknown {
}
// 0 <= v [ && v < max ]
- return x.typ_, v
+ return x.typ(), v
}
func (check *Checker) isValidIndex(x *operand, code Code, what string, allowNegative bool) bool {
}
// spec: "the index x must be of integer type or an untyped constant"
- if !allInteger(x.typ_) {
+ if !allInteger(x.typ()) {
check.errorf(x, code, invalidArg+"%s %s must be integer", what, x)
return false
}
continue
}
par := params.At(i)
- if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ_) {
+ if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ()) {
// Function parameters are always typed. Arguments may be untyped.
// Collect the indices of untyped arguments and handle them later.
- if isTyped(arg.typ_) {
- if !u.unify(par.typ, arg.typ_, assign) {
- errorf(par.typ, arg.typ_, arg)
+ if isTyped(arg.typ()) {
+ if !u.unify(par.typ, arg.typ(), assign) {
+ errorf(par.typ, arg.typ(), arg)
return nil
}
} else if _, ok := par.typ.(*TypeParam); ok && !arg.isNil() {
}
max := maxUntyped[tpar]
if max == nil {
- max = arg.typ_
+ max = arg.typ()
} else {
- m := maxType(max, arg.typ_)
+ m := maxType(max, arg.typ())
if m == nil {
- err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ_, tpar)
+ err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ(), tpar)
return nil
}
max = m
xkey := keyVal(x.val)
if keyIsInterface {
for _, vtyp := range visited[xkey] {
- if Identical(vtyp, x.typ_) {
+ if Identical(vtyp, x.typ()) {
duplicate = true
break
}
}
- visited[xkey] = append(visited[xkey], x.typ_)
+ visited[xkey] = append(visited[xkey], x.typ())
} else {
_, duplicate = visited[xkey]
visited[xkey] = nil
id builtinId
}
+func (x *operand) typ() Type {
+ return x.typ_
+}
+
+func (x *operand) isValid() bool {
+ return x.mode_ != invalid
+}
+
// Pos returns the position of the expression corresponding to x.
// If x is invalid the position is nopos.
func (x *operand) Pos() token.Pos {
// special-case nil
if isTypes2 {
if x.mode_ == nilvalue {
- switch x.typ_ {
+ switch x.typ() {
case nil, Typ[Invalid]:
return "nil (with invalid type)"
case Typ[UntypedNil]:
return "nil"
default:
- return fmt.Sprintf("nil (of type %s)", TypeString(x.typ_, qf))
+ return fmt.Sprintf("nil (of type %s)", TypeString(x.typ(), qf))
}
}
} else { // go/types
- if x.mode_ == value && x.typ_ == Typ[UntypedNil] {
+ if x.mode_ == value && x.typ() == Typ[UntypedNil] {
return "nil"
}
}
case builtin:
expr = predeclaredFuncs[x.id].name
case typexpr:
- expr = TypeString(x.typ_, qf)
+ expr = TypeString(x.typ(), qf)
case constant_:
expr = x.val.String()
}
// no type
default:
// should have a type, but be cautious (don't crash during printing)
- if x.typ_ != nil {
- if isUntyped(x.typ_) {
- buf.WriteString(x.typ_.(*Basic).name)
+ if x.typ() != nil {
+ if isUntyped(x.typ()) {
+ buf.WriteString(x.typ().(*Basic).name)
buf.WriteByte(' ')
break
}
// <typ>
if hasType {
- if isValid(x.typ_) {
+ if isValid(x.typ()) {
var desc string
- if isGeneric(x.typ_) {
+ if isGeneric(x.typ()) {
desc = "generic "
}
// If the type is a renamed basic type, describe the basic type,
// as in "int32 type MyInt" for a *Named type MyInt.
// If it is a type parameter, describe the constraint instead.
- tpar, _ := Unalias(x.typ_).(*TypeParam)
+ tpar, _ := Unalias(x.typ()).(*TypeParam)
if tpar == nil {
- switch x.typ_.(type) {
+ switch x.typ().(type) {
case *Alias, *Named:
- what := compositeKind(x.typ_)
+ what := compositeKind(x.typ())
if what == "" {
// x.typ must be basic type
- what = x.typ_.Underlying().(*Basic).name
+ what = x.typ().Underlying().(*Basic).name
}
desc += what + " "
}
// desc is "" or has a trailing space at the end
buf.WriteString(" of " + desc + "type ")
- WriteType(&buf, x.typ_, qf)
+ WriteType(&buf, x.typ(), qf)
if tpar != nil {
buf.WriteString(" constrained by ")
if isTypes2 {
return x.mode_ == nilvalue
} else { // go/types
- return x.mode_ == value && x.typ_ == Typ[UntypedNil]
+ return x.mode_ == value && x.typ() == Typ[UntypedNil]
}
}
}
origT := T
- V := Unalias(x.typ_)
+ V := Unalias(x.typ())
T = Unalias(T)
// x's type is identical to T
}
ok, code = x.assignableTo(check, T.typ, cause)
if !ok {
- errorf("cannot assign %s to %s (in %s)", x.typ_, T.typ, Tp)
+ errorf("cannot assign %s to %s (in %s)", x.typ(), T.typ, Tp)
return false
}
return true
check.expr(nil, &x, rangeVar)
if isTypes2 && x.mode_ != invalid && sValue == nil && !check.hasCallOrRecv {
- if t, ok := arrayPtrDeref(x.typ_.Underlying()).(*Array); ok {
+ if t, ok := arrayPtrDeref(x.typ().Underlying()).(*Array); ok {
for {
// Put constant info on the thing inside parentheses.
// That's where (*../noder/writer).expr expects it.
// determine key/value types
var key, val Type
if x.mode_ != invalid {
- k, v, cause, ok := rangeKeyVal(check, x.typ_, func(v goVersion) bool {
+ k, v, cause, ok := rangeKeyVal(check, x.typ(), func(v goVersion) bool {
return check.allowVersion(v)
})
switch {
lhs := [2]ast.Expr{sKey, sValue} // sKey, sValue may be nil
rhs := [2]Type{key, val} // key, val may be nil
- rangeOverInt := isInteger(x.typ_)
+ rangeOverInt := isInteger(x.typ())
if isDef {
// short variable declaration
// If the assignment succeeded, if x was untyped before, it now
// has a type inferred via the assignment. It must be an integer.
// (go.dev/issues/67027)
- if x.mode_ != invalid && !isInteger(x.typ_) {
- check.softErrorf(lhs, InvalidRangeExpr, "cannot use iteration variable of type %s", x.typ_)
+ if x.mode_ != invalid && !isInteger(x.typ()) {
+ check.softErrorf(lhs, InvalidRangeExpr, "cannot use iteration variable of type %s", x.typ())
}
} else {
var y operand
case novalue:
typ = (*Tuple)(nil)
case constant_:
- typ = x.typ_
+ typ = x.typ()
val = x.val
default:
- typ = x.typ_
+ typ = x.typ()
}
assert(x.expr != nil && typ != nil)
if a[0].mode_ == invalid {
return
}
- t0, t1 := a[0].typ_, a[1].typ_
+ t0, t1 := a[0].typ(), a[1].typ()
assert(isTyped(t0) && isTyped(t1) && (allBoolean(t1) || t1 == universeError))
if m := check.Types; m != nil {
for {
if x.mode_ == invalid || v.mode_ == invalid {
continue L
}
- check.convertUntyped(&v, x.typ_)
+ check.convertUntyped(&v, x.typ())
if v.mode_ == invalid {
continue L
}
// look for duplicate types for a given value
// (quadratic algorithm, but these lists tend to be very short)
for _, vt := range seen[val] {
- if Identical(v.typ_, vt.typ) {
+ if Identical(v.typ(), vt.typ) {
err := check.newError(DuplicateCase)
err.addf(&v, "duplicate case %s in expression switch", &v)
err.addf(atPos(vt.pos), "previous case")
continue L
}
}
- seen[val] = append(seen[val], valueType{v.Pos(), v.typ_})
+ seen[val] = append(seen[val], valueType{v.Pos(), v.typ()})
}
}
}
if len(types) != 1 || T == nil {
T = Typ[Invalid]
if x != nil {
- T = x.typ_
+ T = x.typ()
}
}
if len(types) != 1 || T == nil {
T = Typ[Invalid]
if x != nil {
- T = x.typ_
+ T = x.typ()
}
}
if x.mode_ == invalid {
return
}
- if !allNumeric(x.typ_) {
- check.errorf(s.X, NonNumericIncDec, invalidOp+"%s%s (non-numeric type %s)", s.X, s.Tok, x.typ_)
+ if !allNumeric(x.typ()) {
+ check.errorf(s.X, NonNumericIncDec, invalidOp+"%s%s (non-numeric type %s)", s.X, s.Tok, x.typ())
return
}
check.simpleStmt(s.Init)
var x operand
check.expr(nil, &x, s.Cond)
- if x.mode_ != invalid && !allBoolean(x.typ_) {
+ if x.mode_ != invalid && !allBoolean(x.typ()) {
check.error(s.Cond, InvalidCond, "non-boolean condition in if statement")
}
check.stmt(inner, s.Body)
// By checking assignment of x to an invisible temporary
// (as a compiler would), we get all the relevant checks.
check.assignment(&x, nil, "switch expression")
- if x.mode_ != invalid && !Comparable(x.typ_) && !hasNil(x.typ_) {
- check.errorf(&x, InvalidExprSwitch, "cannot switch on %s (%s is not comparable)", &x, x.typ_)
+ if x.mode_ != invalid && !Comparable(x.typ()) && !hasNil(x.typ()) {
+ check.errorf(&x, InvalidExprSwitch, "cannot switch on %s (%s is not comparable)", &x, x.typ())
x.mode_ = invalid
}
} else {
var x operand
check.expr(nil, &x, expr.X)
if x.mode_ != invalid {
- if isTypeParam(x.typ_) {
+ if isTypeParam(x.typ()) {
check.errorf(&x, InvalidTypeSwitch, "cannot use type switch on type parameter value %s", &x)
- } else if IsInterface(x.typ_) {
+ } else if IsInterface(x.typ()) {
sx = &x
} else {
check.errorf(&x, InvalidTypeSwitch, "%s is not an interface", &x)
if s.Cond != nil {
var x operand
check.expr(nil, &x, s.Cond)
- if x.mode_ != invalid && !allBoolean(x.typ_) {
+ if x.mode_ != invalid && !allBoolean(x.typ()) {
check.error(s.Cond, InvalidCond, "non-boolean condition in for statement")
}
}
switch x.mode_ {
case typexpr:
- return x.typ_
+ return x.typ()
case invalid:
// ignore - error reported before
case novalue:
switch x.mode_ {
case typexpr:
- return x.typ_
+ return x.typ()
case invalid:
// ignore - error reported before
case novalue:
return -1
}
- if isUntyped(x.typ_) || isInteger(x.typ_) {
+ 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 {
}
var msg string
- if isInteger(x.typ_) {
+ if isInteger(x.typ()) {
msg = "invalid array length %s"
} else {
msg = "array length %s must be integer"