// Copyright 2012 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// This file implements typechecking of expressions.package typesimport (.)/*Basic algorithm:Expressions are checked recursively, top down. Expression checker functionsare generally of the form: 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, andrelated error messages will have been issued by f.If a hint argument is present, it is the composite literal element typeof an outer composite literal; it is used to type-check composite literalelements that have no explicit type specification in the source(e.g.: []T{{...}, {...}}, the hint is the type T in this case).All expressions are checked via rawExpr, which dispatches accordingto expression kind. Upon returning, rawExpr is recording the types andconstant values for all expressions that have an untyped type (those typesmay change on the way up in the expression tree). Usually these are constants,but the results of comparisons or non-constant shifts of untyped constantsmay also be untyped, but not constant.Untyped expressions may eventually become fully typed (i.e., not untyped),typically when the value is assigned to a variable, or is used otherwise.The updateExprType method is used to record this final type and updatethe recorded types: the type-checked expression tree is again traversed down,and the new type is propagated as needed. Untyped constant expression valuesthat become fully typed must now be representable by the full type (constantsub-expression trees are left alone except for their roots). This mechanismensures that a client sees the actual (run-time) type an untyped value wouldhave. It also permits type-checking of lhs shift operands "as if the shiftwere not present": when updateExprType visits an untyped lhs shift operandand assigns it it's final type, that type must be an integer type, and aconstant lhs must be representable as an integer.When an expression gets its final type, either on the way out from rawExpr,on the way down in updateExprType, or at the end of the type checker run,the type (and constant value, if any) is recorded via Info.Types, if present.*/type opPredicates map[token.Token]func(Type) boolvar unaryOpPredicates opPredicatesfunc init() {// Setting unaryOpPredicates in init avoids declaration cycles.unaryOpPredicates = opPredicates{token.ADD: allNumeric,token.SUB: allNumeric,token.XOR: allInteger,token.NOT: allBoolean, }}func ( *Checker) ( opPredicates, *operand, token.Token) bool {if := []; != nil {if !(.typ) { .errorf(, UndefinedOp, invalidOp+"operator %s not defined on %s", , )returnfalse } } else { .errorf(, InvalidSyntaxTree, "unknown operator %s", )returnfalse }returntrue}// opName returns the name of the operation if x is an operation// that might overflow; otherwise it returns the empty string.func opName( ast.Expr) string {switch e := .(type) {case *ast.BinaryExpr:ifint(.Op) < len(op2str2) {returnop2str2[.Op] }case *ast.UnaryExpr:ifint(.Op) < len(op2str1) {returnop2str1[.Op] } }return""}var op2str1 = [...]string{token.XOR: "bitwise complement",}// This is only used for operations that may cause overflow.var op2str2 = [...]string{token.ADD: "addition",token.SUB: "subtraction",token.XOR: "bitwise XOR",token.MUL: "multiplication",token.SHL: "shift",}// If typ is a type parameter, underIs returns the result of typ.underIs(f).// Otherwise, underIs returns the result of f(under(typ)).func underIs( Type, func(Type) bool) bool { = Unalias()if , := .(*TypeParam); != nil {return .underIs() }return (under())}// The unary expression e may be nil. It's passed in for better error messages only.func ( *Checker) ( *operand, *ast.UnaryExpr) { .expr(nil, , .X)if .mode == invalid {return } := .Opswitch {casetoken.AND:// spec: "As an exception to the addressability // requirement x may also be a composite literal."if , := ast.Unparen(.X).(*ast.CompositeLit); ! && .mode != variable { .errorf(, UnaddressableOperand, invalidOp+"cannot take address of %s", ) .mode = invalidreturn } .mode = value .typ = &Pointer{base: .typ}returncasetoken.ARROW: := coreType(.typ)if == nil { .errorf(, InvalidReceive, invalidOp+"cannot receive from %s (no core type)", ) .mode = invalidreturn } , := .(*Chan)if == nil { .errorf(, InvalidReceive, invalidOp+"cannot receive from non-channel %s", ) .mode = invalidreturn }if .dir == SendOnly { .errorf(, InvalidReceive, invalidOp+"cannot receive from send-only channel %s", ) .mode = invalidreturn } .mode = commaok .typ = .elem .hasCallOrRecv = truereturncasetoken.TILDE:// Provide a better error position and message than what check.op below would do.if !allInteger(.typ) { .error(, UndefinedOp, "cannot use ~ outside of interface or type constraint") .mode = invalidreturn } .error(, UndefinedOp, "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)") = token.XOR }if !.op(unaryOpPredicates, , ) { .mode = invalidreturn }if .mode == constant_ {if .val.Kind() == constant.Unknown {// nothing to do (and don't cause an error below in the overflow check)return }varuintifisUnsigned(.typ) { = uint(.conf.sizeof(.typ) * 8) } .val = constant.UnaryOp(, .val, ) .expr = .overflow(, .Pos())return } .mode = value// x.typ remains unchanged}func isShift( token.Token) bool {return == token.SHL || == token.SHR}func isComparison( token.Token) bool {// Note: tokens are not ordered well to make this much easierswitch {casetoken.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:returntrue }returnfalse}// updateExprType updates the type of x to typ and invokes itself// recursively for the operands of x, depending on expression kind.// If typ is still an untyped and not the final type, updateExprType// only updates the recorded untyped type for x and possibly its// operands. Otherwise (i.e., typ is not an untyped type anymore,// or it is the final type for x), the type and value are recorded.// Also, if x is a constant, it must be representable as a value of typ,// and if x is the (formerly untyped) lhs operand of a non-constant// shift, it must be an integer value.func ( *Checker) ( ast.Expr, Type, bool) { .updateExprType0(nil, , , )}func ( *Checker) (, ast.Expr, Type, bool) { , := .untyped[]if ! {return// nothing to do }// update operands of x if necessaryswitch x := .(type) {case *ast.BadExpr, *ast.FuncLit, *ast.CompositeLit, *ast.IndexExpr, *ast.SliceExpr, *ast.TypeAssertExpr, *ast.StarExpr, *ast.KeyValueExpr, *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:// These expression are never untyped - nothing to do. // The respective sub-expressions got their final types // upon assignment or use.ifdebug { .dump("%v: found old type(%s): %s (new: %s)", .Pos(), , .typ, )panic("unreachable") }returncase *ast.CallExpr:// Resulting in an untyped constant (e.g., built-in complex). // The respective calls take care of calling updateExprType // for the arguments if necessary.case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:// An identifier denoting a constant, a constant literal, // or a qualified identifier (imported untyped constant). // No operands to take care of.case *ast.ParenExpr: .(, .X, , )case *ast.UnaryExpr:// If x is a constant, the operands were constants. // The operands don't need to be updated since they // never get "materialized" into a typed value. If // left in the untyped map, they will be processed // at the end of the type check.if .val != nil {break } .(, .X, , )case *ast.BinaryExpr:if .val != nil {break// see comment for unary expressions }ifisComparison(.Op) {// The result type is independent of operand types // and the operand types must have final types. } elseifisShift(.Op) {// The result type depends only on lhs operand. // The rhs type was updated when checking the shift. .(, .X, , ) } else {// The operand types match the result type. .(, .X, , ) .(, .Y, , ) }default:panic("unreachable") }// If the new type is not final and still untyped, just // update the recorded type.if ! && isUntyped() { .typ = under().(*Basic) .untyped[] = return }// Otherwise we have the final (typed or untyped type). // Remove it from the map of yet untyped expressions.delete(.untyped, )if .isLhs {// If x is the lhs of a shift, its final type must be integer. // We already know from the shift check that it is representable // as an integer if it is a constant.if !allInteger() { .errorf(, InvalidShiftOperand, invalidOp+"shifted operand %s (type %s) must be integer", , )return }// Even if we have an integer, if the value is a constant we // still must check that it is representable as the specific // int type requested (was go.dev/issue/22969). Fall through here. }if .val != nil {// If x is a constant, it must be representable as a value of typ. := operand{.mode, , .typ, .val, 0} .convertUntyped(&, )if .mode == invalid {return } }// Everything's fine, record final type and value for x. .recordTypeAndValue(, .mode, , .val)}// updateExprVal updates the value of x to val.func ( *Checker) ( ast.Expr, constant.Value) {if , := .untyped[]; { .val = .untyped[] = }}// implicitTypeAndValue returns the implicit type of x when used in a context// where the target type is expected. If no such implicit conversion is// possible, it returns a nil Type and non-zero error code.//// If x is a constant operand, the returned constant.Value will be the// representation of x in this context.func ( *Checker) ( *operand, Type) (Type, constant.Value, Code) {if .mode == invalid || isTyped(.typ) || !isValid() {return .typ, nil, 0 }// x is untypedifisUntyped() {// both x and target are untypedif := maxType(.typ, ); != nil {return , nil, 0 }returnnil, nil, InvalidUntypedConversion }switch u := under().(type) {case *Basic:if .mode == constant_ { , := .representation(, )if != 0 {returnnil, nil, }return , , }// Non-constant untyped values may appear as the // result of comparisons (untyped bool), intermediate // (delayed-checked) rhs operands of shifts, and as // the value nil.switch .typ.(*Basic).kind {caseUntypedBool:if !isBoolean() {returnnil, nil, InvalidUntypedConversion }caseUntypedInt, UntypedRune, UntypedFloat, UntypedComplex:if !isNumeric() {returnnil, nil, InvalidUntypedConversion }caseUntypedString:// Non-constant untyped string values are not permitted by the spec and // should not occur during normal typechecking passes, but this path is // reachable via the AssignableTo API.if !isString() {returnnil, nil, InvalidUntypedConversion }caseUntypedNil:// Unsafe.Pointer is a basic type that includes nil.if !hasNil() {returnnil, nil, InvalidUntypedConversion }// Preserve the type of nil as UntypedNil: see go.dev/issue/13061.returnTyp[UntypedNil], nil, 0default:returnnil, nil, InvalidUntypedConversion }case *Interface:ifisTypeParam() {if !.typeSet().underIs(func( Type) bool {if == nil {returnfalse } , , := .(, )return != nil }) {returnnil, nil, InvalidUntypedConversion }// keep nil untyped (was bug go.dev/issue/39755)if .isNil() {returnTyp[UntypedNil], nil, 0 }break }// Values must have concrete dynamic types. If the value is nil, // keep it untyped (this is important for tools such as go vet which // need the dynamic type for argument checking of say, print // functions)if .isNil() {returnTyp[UntypedNil], nil, 0 }// cannot assign untyped values to non-empty interfacesif !.Empty() {returnnil, nil, InvalidUntypedConversion }returnDefault(.typ), nil, 0case *Pointer, *Signature, *Slice, *Map, *Chan:if !.isNil() {returnnil, nil, InvalidUntypedConversion }// Keep nil untyped - see comment for interfaces, above.returnTyp[UntypedNil], nil, 0default:returnnil, nil, InvalidUntypedConversion }return , nil, 0}// If switchCase is true, the operator op is ignored.func ( *Checker) (, *operand, token.Token, bool) {// Avoid spurious errors if any of the operands has an invalid type (go.dev/issue/54405).if !isValid(.typ) || !isValid(.typ) { .mode = invalidreturn }if { = token.EQL } := // operand for which error is reported, if any := ""// specific error cause, if any// spec: "In any comparison, the first operand must be assignable // to the type of the second operand, or vice versa." := MismatchedTypes , := .assignableTo(, .typ, nil)if ! { , _ = .assignableTo(, .typ, nil) }if ! {// Report the error on the 2nd operand since we only // know after seeing the 2nd operand whether we have // a type mismatch. = = .sprintf("mismatched types %s and %s", .typ, .typ)goto }// check if comparison is defined for operands = UndefinedOpswitch {casetoken.EQL, token.NEQ:// spec: "The equality operators == and != apply to operands that are comparable."switch {case .isNil() || .isNil():// Comparison against nil requires that the other operand type has nil. := .typif .isNil() { = .typ }if !hasNil() {// This case should only be possible for "nil == nil". // Report the error on the 2nd operand since we only // know after seeing the 2nd operand whether we have // an invalid comparison. = goto }case !Comparable(.typ): = = .incomparableCause(.typ)gotocase !Comparable(.typ): = = .incomparableCause(.typ)goto }casetoken.LSS, token.LEQ, token.GTR, token.GEQ:// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."switch {case !allOrdered(.typ): = gotocase !allOrdered(.typ): = goto }default:panic("unreachable") }// comparison is okif .mode == constant_ && .mode == constant_ { .val = constant.MakeBool(constant.Compare(.val, , .val))// The operands are never materialized; no need to update // their types. } else { .mode = value// The operands have now their final types, which at run- // time will be materialized. Update the expression trees. // If the current types are untyped, the materialized type // is the respective default type. .updateExprType(.expr, Default(.typ), true) .updateExprType(.expr, Default(.typ), true) }// spec: "Comparison operators compare two operands and yield // an untyped boolean value." .typ = Typ[UntypedBool]return:// We have an offending operand errOp and possibly an error cause.if == "" {ifisTypeParam(.typ) || isTypeParam(.typ) {// TODO(gri) should report the specific type causing the problem, if anyif !isTypeParam(.typ) { = } = .sprintf("type parameter %s is not comparable with %s", .typ, ) } else { = .sprintf("operator %s not defined on %s", , .kindString(.typ)) // catch-all } }if { .errorf(, , "invalid case %s in switch on %s (%s)", .expr, .expr, ) // error position always at 1st operand } else { .errorf(, , invalidOp+"%s %s %s (%s)", .expr, , .expr, ) } .mode = invalid}// incomparableCause returns a more specific cause why typ is not comparable.// If there is no more specific cause, the result is "".func ( *Checker) ( Type) string {switchunder().(type) {case *Slice, *Signature, *Map:return .kindString() + " can only be compared to nil" }// see if we can extract a more specific errorvarstringcomparable(, true, nil, func( string, ...interface{}) { = .sprintf(, ...) })return}// kindString returns the type kind as a string.func ( *Checker) ( Type) string {switchunder().(type) {case *Array:return"array"case *Slice:return"slice"case *Struct:return"struct"case *Pointer:return"pointer"case *Signature:return"func"case *Interface:ifisTypeParam() {return .sprintf("type parameter %s", ) }return"interface"case *Map:return"map"case *Chan:return"chan"default:return .sprintf("%s", ) // catch-all }}// If e != nil, it must be the shift expression; it may be nil for non-constant shifts.func ( *Checker) (, *operand, ast.Expr, token.Token) {// TODO(gri) This function seems overly complex. Revisit.varconstant.Valueif .mode == constant_ { = constant.ToInt(.val) }ifallInteger(.typ) || isUntyped(.typ) && != nil && .Kind() == constant.Int {// The lhs is of integer type or an untyped constant representable // as an integer. Nothing to do. } else {// shift has no chance .errorf(, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", ) .mode = invalidreturn }// spec: "The right operand in a shift expression must have integer type // or be an untyped constant representable by a value of type uint."// Check that constants are representable by uint, but do not convert them // (see also go.dev/issue/47243).varconstant.Valueif .mode == constant_ {// Provide a good error message for negative shift counts. = constant.ToInt(.val) // consider -1, 1.0, but not -1.1if .Kind() == constant.Int && constant.Sign() < 0 { .errorf(, InvalidShiftCount, invalidOp+"negative shift count %s", ) .mode = invalidreturn }ifisUntyped(.typ) {// Caution: Check for representability here, rather than in the switch // below, because isInteger includes untyped integers (was bug go.dev/issue/43697). .representable(, Typ[Uint])if .mode == invalid { .mode = invalidreturn } } } else {// Check that RHS is otherwise at least of integer type.switch {caseallInteger(.typ):if !allUnsigned(.typ) && !.verifyVersionf(, go1_13, invalidOp+"signed shift count %s", ) { .mode = invalidreturn }caseisUntyped(.typ):// This is incorrect, but preserves pre-existing behavior. // See also go.dev/issue/47410. .convertUntyped(, Typ[Uint])if .mode == invalid { .mode = invalidreturn }default: .errorf(, InvalidShiftCount, invalidOp+"shift count %s must be integer", ) .mode = invalidreturn } }if .mode == constant_ {if .mode == constant_ {// if either x or y has an unknown value, the result is unknownif .val.Kind() == constant.Unknown || .val.Kind() == constant.Unknown { .val = constant.MakeUnknown()// ensure the correct type - see comment belowif !isInteger(.typ) { .typ = Typ[UntypedInt] }return }// rhs must be within reasonable bounds in constant shiftsconst = 1023 - 1 + 52// so we can express smallestFloat64 (see go.dev/issue/44057) , := constant.Uint64Val()if ! || > { .errorf(, InvalidShiftCount, invalidOp+"invalid shift count %s", ) .mode = invalidreturn }// The lhs is representable as an integer but may not be an integer // (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(.typ) { .typ = Typ[UntypedInt] }// x is a constant so xval != nil and it must be of Int kind. .val = constant.Shift(, , uint()) .expr = := .Pos()if , := .(*ast.BinaryExpr); != nil { = .OpPos } .overflow(, )return }// non-constant shift with constant lhsifisUntyped(.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 // were replaced by its left operand alone.". // // Delay operand checking until we know the final type // by marking the lhs expression as lhs shift operand. // // Usually (in correct programs), the lhs expression // is in the untyped map. However, it is possible to // create incorrect programs where the same expression // is evaluated twice (via a declaration cycle) such // that the lhs expression type is determined in the // first round and thus deleted from the map, and then // not found in the second round (double insertion of // the same expr node still just leads to one entry for // that node, and it can only be deleted once). // Be cautious and check for presence of entry. // Example: var e, f = int(1<<""[f]) // go.dev/issue/11347if , := .untyped[.expr]; { .isLhs = true .untyped[.expr] = }// keep x's type .mode = valuereturn } }// non-constant shift - lhs must be an integerif !allInteger(.typ) { .errorf(, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", ) .mode = invalidreturn } .mode = value}var binaryOpPredicates opPredicatesfunc init() {// Setting binaryOpPredicates in init avoids declaration cycles.binaryOpPredicates = opPredicates{token.ADD: allNumericOrString,token.SUB: allNumeric,token.MUL: allNumeric,token.QUO: allNumeric,token.REM: allInteger,token.AND: allInteger,token.OR: allInteger,token.XOR: allInteger,token.AND_NOT: allInteger,token.LAND: allBoolean,token.LOR: allBoolean, }}// If e != nil, it must be the binary expression; it may be nil for non-constant expressions// (when invoked for an assignment operation where the binary expression is implicit).func ( *Checker) ( *operand, ast.Expr, , ast.Expr, token.Token, token.Pos) {varoperand .expr(nil, , ) .expr(nil, &, )if .mode == invalid {return }if .mode == invalid { .mode = invalid .expr = .exprreturn }ifisShift() { .shift(, &, , )return } .matchTypes(, &)if .mode == invalid {return }ifisComparison() { .comparison(, &, , false)return }if !Identical(.typ, .typ) {// only report an error if we have valid types // (otherwise we had an error reported elsewhere already)ifisValid(.typ) && isValid(.typ) {varpositioner = if != nil { = }if != nil { .errorf(, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", , .typ, .typ) } else { .errorf(, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", , , , .typ, .typ) } } .mode = invalidreturn }if !.op(binaryOpPredicates, , ) { .mode = invalidreturn }if == token.QUO || == token.REM {// check for zero divisorif (.mode == constant_ || allInteger(.typ)) && .mode == constant_ && constant.Sign(.val) == 0 { .error(&, DivByZero, invalidOp+"division by zero") .mode = invalidreturn }// check for divisor underflow in complex division (see go.dev/issue/20227)if .mode == constant_ && .mode == constant_ && isComplex(.typ) { , := constant.Real(.val), constant.Imag(.val) , := constant.BinaryOp(, token.MUL, ), constant.BinaryOp(, token.MUL, )ifconstant.Sign() == 0 && constant.Sign() == 0 { .error(&, DivByZero, invalidOp+"division by zero") .mode = invalidreturn } } }if .mode == constant_ && .mode == constant_ {// if either x or y has an unknown value, the result is unknownif .val.Kind() == constant.Unknown || .val.Kind() == constant.Unknown { .val = constant.MakeUnknown()// x.typ is unchangedreturn }// force integer division of integer operandsif == token.QUO && isInteger(.typ) { = token.QUO_ASSIGN } .val = constant.BinaryOp(.val, , .val) .expr = .overflow(, )return } .mode = value// x.typ is unchanged}// matchTypes attempts to convert any untyped types x and y such that they match.// If an error occurs, x.mode is set to invalid.func ( *Checker) (, *operand) {// mayConvert reports whether the operands x and y may // possibly have matching types after converting one // untyped operand to the type of the other. // If mayConvert returns true, we try to convert the // operands to each other's types, and if that fails // we report a conversion failure. // If mayConvert returns false, we continue without an // attempt at conversion, and if the operand types are // not compatible, we report a type mismatch error. := func(, *operand) bool {// If both operands are typed, there's no need for an implicit conversion.ifisTyped(.typ) && isTyped(.typ) {returnfalse }// 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.ifisNonTypeParamInterface(.typ) || isNonTypeParamInterface(.typ) {returntrue }// A boolean type can only convert to another boolean type.ifallBoolean(.typ) != allBoolean(.typ) {returnfalse }// A string type can only convert to another string type.ifallString(.typ) != allString(.typ) {returnfalse }// Untyped nil can only convert to a type that has a nil.if .isNil() {returnhasNil(.typ) }if .isNil() {returnhasNil(.typ) }// An untyped operand cannot convert to a pointer. // TODO(gri) generalize to type parametersifisPointer(.typ) || isPointer(.typ) {returnfalse }returntrue }if (, ) { .convertUntyped(, .typ)if .mode == invalid {return } .convertUntyped(, .typ)if .mode == invalid { .mode = invalidreturn } }}// exprKind describes the kind of an expression; the kind// determines if an expression is valid in 'statement context'.type exprKind intconst ( conversion exprKind = iota expression statement)// target represent the (signature) type and description of the LHS// variable of an assignment, or of a function result variable.type target struct { sig *Signature desc string}// newTarget creates a new target for the given type and description.// The result is nil if typ is not a signature.func newTarget( Type, string) *target {if != nil {if , := under().(*Signature); != nil {return &target{, } } }returnnil}// rawExpr typechecks expression e and initializes x with the expression// value or type. If an error occurred, x.mode is set to invalid.// If a non-nil target T is given and e is a generic function,// T is used to infer the type arguments for e.// If hint != nil, it is the type of a composite literal element.// If allowGeneric is set, the operand type may be an uninstantiated// parameterized type or function value.func ( *Checker) ( *target, *operand, ast.Expr, Type, bool) exprKind {if .conf._Trace { .trace(.Pos(), "-- expr %s", ) .indent++deferfunc() { .indent-- .trace(.Pos(), "=> %s", ) }() } := .exprInternal(, , , )if ! { .nonGeneric(, ) } .record()return}// If x is a generic type, or a generic function whose type arguments cannot be inferred// from a non-nil target T, nonGeneric reports an error and invalidates x.mode and x.typ.// Otherwise it leaves x alone.func ( *Checker) ( *target, *operand) {if .mode == invalid || .mode == novalue {return }varstringswitch t := .typ.(type) {case *Alias, *Named:ifisGeneric() { = "type" }case *Signature:if .tparams != nil {ifenableReverseTypeInference && != nil { .funcInst(, .Pos(), , nil, true)return } = "function" } }if != "" { .errorf(.expr, WrongTypeArgCount, "cannot use generic %s %s without instantiation", , .expr) .mode = invalid .typ = Typ[Invalid] }}// langCompat reports an error if the representation of a numeric// literal is not compatible with the current language version.func ( *Checker) ( *ast.BasicLit) { := .Valueiflen() <= 2 || .allowVersion(, go1_13) {return }// len(s) > 2ifstrings.Contains(, "_") { .versionErrorf(, go1_13, "underscore in numeric literal")return }if [0] != '0' {return } := [1]if == 'b' || == 'B' { .versionErrorf(, go1_13, "binary literal")return }if == 'o' || == 'O' { .versionErrorf(, go1_13, "0o/0O-style octal literal")return }if .Kind != token.INT && ( == 'x' || == 'X') { .versionErrorf(, go1_13, "hexadecimal floating-point literal") }}// exprInternal contains the core of type checking of expressions.// Must only be called by rawExpr.// (See rawExpr for an explanation of the parameters.)func ( *Checker) ( *target, *operand, ast.Expr, Type) exprKind {// make sure x has a valid state in case of bailout // (was go.dev/issue/5770) .mode = invalid .typ = Typ[Invalid]switch e := .(type) {case *ast.BadExpr:goto// error was reported beforecase *ast.Ident: .ident(, , nil, false)case *ast.Ellipsis:// ellipses are handled explicitly where they are legal // (array composite literals and parameter lists) .error(, BadDotDotDotSyntax, "invalid use of '...'")gotocase *ast.BasicLit:switch .Kind {casetoken.INT, token.FLOAT, token.IMAG: .langCompat()// The max. mantissa precision for untyped numeric values // is 512 bits, or 4048 bits for each of the two integer // parts of a fraction for floating-point numbers that are // represented accurately in the go/constant package. // Constant literals that are longer than this many bits // are not meaningful; and excessively long constants may // consume a lot of space and time for a useless conversion. // Cap constant length with a generous upper limit that also // allows for separators between all digits.const = 10000iflen(.Value) > { .errorf(, InvalidConstVal, "excessively long constant: %s... (%d chars)", .Value[:10], len(.Value))goto } } .setConst(.Kind, .Value)if .mode == invalid {// The parser already establishes syntactic correctness. // If we reach here it's because of number under-/overflow. // TODO(gri) setConst (and in turn the go/constant package) // should return an error describing the issue. .errorf(, InvalidConstVal, "malformed constant: %s", .Value)goto }// Ensure that integer values don't overflow (go.dev/issue/54280). .overflow(, .Pos())case *ast.FuncLit:if , := .typ(.Type).(*Signature); {// Set the Scope's extent to the complete "func (...) {...}" // so that Scope.Innermost works correctly. .scope.pos = .Pos() .scope.end = .End()if !.conf.IgnoreFuncBodies && .Body != nil {// Anonymous functions are considered part of the // init expression/func declaration which contains // them: use existing package-level declaration info. := .decl// capture for use in closure below := .iota// capture for use in closure below (go.dev/issue/22345)// Don't type-check right away because the function may // be part of a type definition to which the function // body refers. Instead, type-check as soon as possible, // but before the enclosing scope contents changes (go.dev/issue/22992). .later(func() { .funcBody(, "<function literal>", , .Body, ) }).describef(, "func literal") } .mode = value .typ = } else { .errorf(, InvalidSyntaxTree, "invalid function literal %v", )goto }case *ast.CompositeLit:var , Typeswitch {case .Type != nil:// composite literal type present - use it // [...]T array types may only appear with composite literals. // Check for them here so we don't have to handle ... in general.if , := .Type.(*ast.ArrayType); != nil && .Len != nil {if , := .Len.(*ast.Ellipsis); != nil && .Elt == nil {// We have an "open" [...]T array type. // Create a new ArrayType with unknown length (-1) // and finish setting it up after analyzing the literal. = &Array{len: -1, elem: .varType(.Elt)} = break } } = .typ(.Type) = case != nil:// no composite literal type present - use hint (element type of enclosing type) = , _ = deref(coreType()) // *T implies &T{}if == nil { .errorf(, InvalidLit, "invalid composite literal element type %s (no core type)", )goto }default:// TODO(gri) provide better error messages depending on context .error(, UntypedLit, "missing type in composite literal")goto }switch utyp := coreType().(type) {case *Struct:// Prevent crash if the struct referred to is not yet set up. // See analogous comment for *Array.if .fields == nil { .error(, InvalidTypeCycle, "invalid recursive type")goto }iflen(.Elts) == 0 {break }// Convention for error messages on invalid struct literals: // we mention the struct type only if it clarifies the error // (e.g., a duplicate field error doesn't need the struct type). := .fieldsif , := .Elts[0].(*ast.KeyValueExpr); {// all elements must have keys := make([]bool, len())for , := range .Elts { , := .(*ast.KeyValueExpr)if == nil { .error(, MixedStructLit, "mixture of field:value and value elements in struct literal")continue } , := .Key.(*ast.Ident)// do all possible checks early (before exiting due to errors) // so we don't drop information on the floor .expr(nil, , .Value)if == nil { .errorf(, InvalidLitField, "invalid field name %s in struct literal", .Key)continue } := fieldIndex(.fields, .pkg, .Name, false)if < 0 {varObjectif := fieldIndex(, .pkg, .Name, true); >= 0 { = [] } := .lookupError(, .Name, , true) .error(.Key, MissingLitField, )continue } := [] .recordUse(, ) := .typ .assignment(, , "struct literal")// 0 <= i < len(fields)if [] { .errorf(, DuplicateLitField, "duplicate field name %s in struct literal", .Name)continue } [] = true } } else {// no element must have a keyfor , := range .Elts {if , := .(*ast.KeyValueExpr); != nil { .error(, MixedStructLit, "mixture of field:value and value elements in struct literal")continue } .expr(nil, , )if >= len() { .errorf(, InvalidStructLit, "too many values in struct literal of type %s", )break// cannot continue }// i < len(fields) := []if !.Exported() && .pkg != .pkg { .errorf(,UnexportedLitField,"implicit assignment to unexported field %s in struct literal of type %s", .name, )continue } := .typ .assignment(, , "struct literal") }iflen(.Elts) < len() { .errorf(inNode(, .Rbrace), InvalidStructLit, "too few values in struct literal of type %s", )// ok to continue } }case *Array:// Prevent crash if the array referred to is not yet set up. Was go.dev/issue/18643. // This is a stop-gap solution. Should use Checker.objPath to report entire // path starting with earliest declaration in the source. TODO(gri) fix this.if .elem == nil { .error(, InvalidTypeCycle, "invalid recursive type")goto } := .indexedElts(.Elts, .elem, .len)// If we have an array of unknown length (usually [...]T arrays, but also // arrays [n]T where n is invalid) set the length now that we know it and // record the type for the array (usually done by check.typ which is not // called for [...]T). We handle [...]T arrays and arrays with invalid // length the same here because it makes sense to "guess" the length for // the latter if we have a composite literal; e.g. for [n]int{1, 2, 3} // where n is invalid for some reason, it seems fair to assume it should // be 3 (see also Checked.arrayLength and go.dev/issue/27346).if .len < 0 { .len = // e.Type is missing if we have a composite literal element // that is itself a composite literal with omitted type. In // that case there is nothing to record (there is no type in // the source at that point).if .Type != nil { .recordTypeAndValue(.Type, typexpr, , nil) } }case *Slice:// Prevent crash if the slice referred to is not yet set up. // See analogous comment for *Array.if .elem == nil { .error(, InvalidTypeCycle, "invalid recursive type")goto } .indexedElts(.Elts, .elem, -1)case *Map:// Prevent crash if the map referred to is not yet set up. // See analogous comment for *Array.if .key == nil || .elem == nil { .error(, InvalidTypeCycle, "invalid recursive type")goto }// If the map key type is an interface (but not a type parameter), // the type of a constant key must be considered when checking for // duplicates. := isNonTypeParamInterface(.key) := make(map[any][]Type, len(.Elts))for , := range .Elts { , := .(*ast.KeyValueExpr)if == nil { .error(, MissingLitKey, "missing key in map literal")continue } .exprWithHint(, .Key, .key) .assignment(, .key, "map literal")if .mode == invalid {continue }if .mode == constant_ { := false := keyVal(.val)if {for , := range [] {ifIdentical(, .typ) { = truebreak } } [] = append([], .typ) } else { _, = [] [] = nil }if { .errorf(, DuplicateLitKey, "duplicate key %s in map literal", .val)continue } } .exprWithHint(, .Value, .elem) .assignment(, .elem, "map literal") }default:// when "using" all elements unpack KeyValueExpr // explicitly because check.use doesn't accept themfor , := range .Elts {if , := .(*ast.KeyValueExpr); != nil {// Ideally, we should also "use" kv.Key but we can't know // if it's an externally defined struct key or not. Going // forward anyway can lead to other errors. Give up instead. = .Value } .use() }// if utyp is invalid, an error was reported beforeifisValid() { .errorf(, InvalidLit, "invalid composite literal type %s", )goto } } .mode = value .typ = case *ast.ParenExpr:// type inference doesn't go past parentheses (targe type T = nil) := .rawExpr(nil, , .X, nil, false) .expr = returncase *ast.SelectorExpr: .selector(, , nil, false)case *ast.IndexExpr, *ast.IndexListExpr: := typeparams.UnpackIndexExpr()if .indexExpr(, ) {if !enableReverseTypeInference { = nil } .funcInst(, .Pos(), , , true) }if .mode == invalid {goto }case *ast.SliceExpr: .sliceExpr(, )if .mode == invalid {goto }case *ast.TypeAssertExpr: .expr(nil, , .X)if .mode == invalid {goto }// x.(type) expressions are handled explicitly in type switchesif .Type == nil {// Don't use InvalidSyntaxTree because this can occur in the AST produced by // go/parser. .error(, BadTypeKeyword, "use of .(type) outside type switch")goto }ifisTypeParam(.typ) { .errorf(, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", )goto }if , := under(.typ).(*Interface); ! { .errorf(, InvalidAssert, invalidOp+"%s is not an interface", )goto } := .varType(.Type)if !isValid() {goto } .typeAssertion(, , , false) .mode = commaok .typ = case *ast.CallExpr:return .callExpr(, )case *ast.StarExpr: .exprOrType(, .X, false)switch .mode {caseinvalid:gotocasetypexpr: .validVarType(.X, .typ) .typ = &Pointer{base: .typ}default:varTypeif !underIs(.typ, func( Type) bool { , := .(*Pointer)if == nil { .errorf(, InvalidIndirection, invalidOp+"cannot indirect %s", )returnfalse }if != nil && !Identical(.base, ) { .errorf(, InvalidIndirection, invalidOp+"pointers of %s must have identical base types", )returnfalse } = .basereturntrue }) {goto } .mode = variable .typ = }case *ast.UnaryExpr: .unary(, )if .mode == invalid {goto }if .Op == token.ARROW { .expr = returnstatement// receive operations may appear in statement context }case *ast.BinaryExpr: .binary(, , .X, .Y, .Op, .OpPos)if .mode == invalid {goto }case *ast.KeyValueExpr:// key:value expressions are handled in composite literals .error(, InvalidSyntaxTree, "no key:value expected")gotocase *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType: .mode = typexpr .typ = .typ()// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue // even though check.typ has already called it. This is fine as both // times the same expression and type are recorded. It is also not a // performance issue because we only reach here for composite literal // types, which are comparatively rare.default:panic(fmt.Sprintf("%s: unknown expression type %T", .fset.Position(.Pos()), )) }// everything went well .expr = returnexpression: .mode = invalid .expr = returnstatement// avoid follow-up errors}// keyVal maps a complex, float, integer, string or boolean constant value// to the corresponding complex128, float64, int64, uint64, string, or bool// Go value if possible; otherwise it returns x.// A complex constant that can be represented as a float (such as 1.2 + 0i)// is returned as a floating point value; if a floating point value can be// represented as an integer (such as 1.0) it is returned as an integer value.// This ensures that constants of different kind but equal value (such as// 1.0 + 0i, 1.0, 1) result in the same value.func keyVal( constant.Value) interface{} {switch .Kind() {caseconstant.Complex: := constant.ToFloat()if .Kind() != constant.Float { , := constant.Float64Val(constant.Real()) , := constant.Float64Val(constant.Imag())returncomplex(, ) } = fallthroughcaseconstant.Float: := constant.ToInt()if .Kind() != constant.Int { , := constant.Float64Val()return } = fallthroughcaseconstant.Int:if , := constant.Int64Val(); {return }if , := constant.Uint64Val(); {return }caseconstant.String:returnconstant.StringVal()caseconstant.Bool:returnconstant.BoolVal() }return}// typeAssertion checks x.(T). The type of x must be an interface.func ( *Checker) ( ast.Expr, *operand, Type, bool) {varstringif .assertableTo(.typ, , &) {return// success }if { .errorf(, ImpossibleAssert, "impossible type switch case: %s\n\t%s cannot have dynamic type %s %s", , , , )return } .errorf(, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", , , .typ, )}// expr typechecks expression e and initializes x with the expression value.// If a non-nil target T is given and e is a generic function or// a function call, T is used to infer the type arguments for e.// The result must be a single value.// If an error occurred, x.mode is set to invalid.func ( *Checker) ( *target, *operand, ast.Expr) { .rawExpr(, , , nil, false) .exclude(, 1<<novalue|1<<builtin|1<<typexpr) .singleValue()}// genericExpr is like expr but the result may also be generic.func ( *Checker) ( *operand, ast.Expr) { .rawExpr(nil, , , nil, true) .exclude(, 1<<novalue|1<<builtin|1<<typexpr) .singleValue()}// multiExpr typechecks e and returns its value (or values) in list.// If allowCommaOk is set and e is a map index, comma-ok, or comma-err// expression, the result is a two-element list containing the value// of e, and an untyped bool value or an error value, respectively.// If an error occurred, list[0] is not valid.func ( *Checker) ( ast.Expr, bool) ( []*operand, bool) {varoperand .rawExpr(nil, &, , nil, false) .exclude(&, 1<<novalue|1<<builtin|1<<typexpr)if , := .typ.(*Tuple); && .mode != invalid {// multiple values = make([]*operand, .Len())for , := range .vars { [] = &operand{mode: value, expr: , typ: .typ} }return }// exactly one (possibly invalid or comma-ok) value = []*operand{&}if && (.mode == mapindex || .mode == commaok || .mode == commaerr) { := &operand{mode: value, expr: , typ: Typ[UntypedBool]}if .mode == commaerr { .typ = universeError } = append(, ) = true }return}// exprWithHint typechecks expression e and initializes x with the expression value;// hint is the type of a composite literal element.// If an error occurred, x.mode is set to invalid.func ( *Checker) ( *operand, ast.Expr, Type) {assert( != nil) .rawExpr(nil, , , , false) .exclude(, 1<<novalue|1<<builtin|1<<typexpr) .singleValue()}// exprOrType typechecks expression or type e and initializes x with the expression value or type.// If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function// value.// If an error occurred, x.mode is set to invalid.func ( *Checker) ( *operand, ast.Expr, bool) { .rawExpr(nil, , , nil, ) .exclude(, 1<<novalue) .singleValue()}// exclude reports an error if x.mode is in modeset and sets x.mode to invalid.// The modeset may contain any of 1<<novalue, 1<<builtin, 1<<typexpr.func ( *Checker) ( *operand, uint) {if &(1<<.mode) != 0 {varstringvarCodeswitch .mode {casenovalue:if &(1<<typexpr) != 0 { = "%s used as value" } else { = "%s used as value or type" } = TooManyValuescasebuiltin: = "%s must be called" = UncalledBuiltincasetypexpr: = "%s is not an expression" = NotAnExprdefault:panic("unreachable") } .errorf(, , , ) .mode = invalid }}// singleValue reports an error if x describes a tuple and sets x.mode to invalid.func ( *Checker) ( *operand) {if .mode == value {// tuple types are never named - no need for underlying type belowif , := .typ.(*Tuple); {assert(.Len() != 1) .errorf(, TooManyValues, "multiple-value %s in single-value context", ) .mode = invalid } }}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.