1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 //go:generate stringer -type Code codes.go
11 // This file defines the error codes that can be produced during type-checking.
12 // Collectively, these codes provide an identifier that may be used to
13 // implement special handling for certain types of errors.
15 // Error code values should not be changed: add new codes at the end.
17 // Error codes should be fine-grained enough that the exact nature of the error
18 // can be easily determined, but coarse enough that they are not an
19 // implementation detail of the type checking algorithm. As a rule-of-thumb,
20 // errors should be considered equivalent if there is a theoretical refactoring
21 // of the type checker in which they are emitted in exactly one place. For
22 // example, the type checker emits different error messages for "too many
23 // arguments" and "too few arguments", but one can imagine an alternative type
24 // checker where this check instead just emits a single "wrong number of
25 // arguments", so these errors should have the same code.
27 // Error code names should be as brief as possible while retaining accuracy and
28 // distinctiveness. In most cases names should start with an adjective
29 // describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
30 // and end with a noun identifying the relevant language object. For example,
31 // "_DuplicateDecl" or "_InvalidSliceExpr". For brevity, naming follows the
32 // convention that "bad" implies a problem with syntax, and "invalid" implies a
33 // problem with types.
36 // InvalidSyntaxTree occurs if an invalid syntax tree is provided
37 // to the type checker. It should never happen.
38 InvalidSyntaxTree Code = -1
42 // The zero Code value indicates an unset (invalid) error code.
45 // Test is reserved for errors that only apply while in self-test mode.
48 // BlankPkgName occurs when a package name is the blank identifier "_".
51 // "The PackageName must not be the blank identifier."
57 // MismatchedPkgName occurs when a file's package name doesn't match the
58 // package name already established by other files.
61 // InvalidPkgUse occurs when a package identifier is used outside of a
62 // selector expression.
70 // BadImportPath occurs when an import path is not valid.
73 // BrokenImport occurs when importing a package fails.
76 // import "amissingpackage"
79 // ImportCRenamed occurs when the special import "C" is renamed. "C" is a
80 // pseudo-package, and must not be renamed.
86 // UnusedImport occurs when an import is unused.
94 // InvalidInitCycle occurs when an invalid cycle is detected within the
95 // initialization graph.
100 // func f() int { return x }
103 // DuplicateDecl occurs when an identifier is declared multiple times.
110 // InvalidDeclCycle occurs when a declaration cycle is not valid.
119 // InvalidTypeCycle occurs when a cycle in type definitions results in a
120 // type that is not well-defined.
125 // type T [unsafe.Sizeof(T{})]int
128 // InvalidConstInit occurs when a const declaration has a non-constant
136 // InvalidConstVal occurs when a const value cannot be converted to its
139 // TODO(findleyr): this error code and example are not very clear. Consider
143 // const _ = 1 << "hello"
146 // InvalidConstType occurs when the underlying type in a const declaration
147 // is not a valid constant type.
153 // UntypedNilUse occurs when the predeclared (untyped) value nil is used to
154 // initialize a variable declared without an explicit type.
160 // WrongAssignCount occurs when the number of values on the right-hand side
161 // of an assignment or initialization expression does not match the number
162 // of variables on the left-hand side.
168 // UnassignableOperand occurs when the left-hand side of an assignment is
178 // NoNewVar occurs when a short variable declaration (':=') does not declare
188 // MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
189 // not have single-valued left-hand or right-hand side.
192 // "In assignment operations, both the left- and right-hand expression lists
193 // must contain exactly one single-valued expression"
203 // InvalidIfaceAssign occurs when a value of type T is used as an
204 // interface, but T does not implement a method of the expected interface.
207 // type I interface {
216 // InvalidChanAssign occurs when a chan assignment is invalid.
218 // Per the spec, a value x is assignable to a channel type T if:
219 // "x is a bidirectional channel value, T is a channel type, x's type V and
220 // T have identical element types, and at least one of V or T is not a
228 // // Invalid assignment because both types are named
232 // IncompatibleAssign occurs when the type of the right-hand side expression
233 // in an assignment cannot be assigned to the type of the variable being
241 // UnaddressableFieldAssign occurs when trying to assign to a struct field
246 // m := make(map[string]struct{i int})
249 UnaddressableFieldAssign
251 // NotAType occurs when the identifier used as the underlying type in a type
252 // declaration or the right-hand side of a type alias does not denote a type.
260 // InvalidArrayLen occurs when an array length is not a constant value.
267 // BlankIfaceMethod occurs when a method name is '_'.
270 // "The name of each explicitly specified method must be unique and not
274 // type T interface {
279 // IncomparableMapKey occurs when a map key type does not support the == and
283 // "The comparison operators == and != must be fully defined for operands of
284 // the key type; thus the key type must not be a function, map, or slice."
292 // InvalidIfaceEmbed occurs when a non-interface type is embedded in an
293 // interface (for go 1.17 or earlier).
294 _ // not used anymore
296 // InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
297 // and T itself is itself a pointer, an unsafe.Pointer, or an interface.
300 // "An embedded field must be specified as a type name T or as a pointer to
301 // a non-interface type name *T, and T itself may not be a pointer type."
311 // BadRecv occurs when a method declaration does not have exactly one
312 // receiver parameter.
318 // InvalidRecv occurs when a receiver type expression is not of the form T
319 // or *T, or T is a pointer type.
327 // DuplicateFieldAndMethod occurs when an identifier appears as both a field
336 DuplicateFieldAndMethod
338 // DuplicateMethod occurs when two methods on the same receiver type have
344 // func (T) m(i int) int { return i }
347 // InvalidBlank occurs when a blank identifier is used as a value or type.
350 // "The blank identifier may appear as an operand only on the left-hand side
351 // of an assignment."
357 // InvalidIota occurs when the predeclared identifier iota is used outside
358 // of a constant declaration.
364 // MissingInitBody occurs when an init function is missing its body.
370 // InvalidInitSig occurs when an init function declares parameters or
373 // Deprecated: no longer emitted by the type checker. _InvalidInitDecl is
377 // InvalidInitDecl occurs when init is declared as anything other than a
384 // func init() int { return 1 }
387 // InvalidMainDecl occurs when main is declared as anything other than a
388 // function, in a main package.
391 // TooManyValues occurs when a function returns too many values for the
392 // expression context in which it is used.
395 // func ReturnTwo() (int, int) {
399 // var x = ReturnTwo()
402 // NotAnExpr occurs when a type expression is used where a value expression
413 // TruncatedFloat occurs when a float constant is truncated to an integer
420 // NumericOverflow occurs when a numeric constant overflows its target type.
426 // UndefinedOp occurs when an operator is not defined for the type(s) used
433 // MismatchedTypes occurs when operand types are incompatible in a binary
442 // DivByZero occurs when a division operation is provable at compile
443 // time to be a division by zero.
447 // var x int = 1/divisor
450 // NonNumericIncDec occurs when an increment or decrement operator is
451 // applied to a non-numeric value.
460 // UnaddressableOperand occurs when the & operator is applied to an
461 // unaddressable expression.
467 // InvalidIndirection occurs when a non-pointer value is indirected via the
475 // NonIndexableOperand occurs when an index operation is applied to a value
476 // that cannot be indexed.
483 // InvalidIndex occurs when an index argument is not of integer type,
484 // negative, or out-of-bounds.
487 // var s = [...]int{1,2,3}
491 // var s = []int{1,2,3}
495 // var s = []int{1,2,3}
500 // SwappedSliceIndices occurs when constant indices in a slice expression
501 // are decreasing in value.
504 // var _ = []int{1,2,3}[2:1]
507 // NonSliceableOperand occurs when a slice operation is applied to a value
508 // whose type is not sliceable, or is unaddressable.
511 // var x = [...]int{1, 2, 3}[:1]
518 // InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
519 // applied to a string.
526 // InvalidShiftCount occurs when the right-hand side of a shift operation is
527 // either non-integer, negative, or too large.
536 // InvalidShiftOperand occurs when the shifted operand is not an integer.
543 // InvalidReceive occurs when there is a channel receive from a value that
544 // is either not a channel, or is a send-only channel.
553 // InvalidSend occurs when there is a channel send to a value that is not a
554 // channel, or is a receive-only channel.
563 // DuplicateLitKey occurs when an index is duplicated in a slice, array, or
567 // var _ = []int{0:1, 0:2}
570 // var _ = map[string]int{"a": 1, "a": 2}
573 // MissingLitKey occurs when a map literal is missing a key expression.
576 // var _ = map[string]int{1}
579 // InvalidLitIndex occurs when the key in a key-value element of a slice or
580 // array literal is not an integer constant.
584 // var x = []string{i: "world"}
587 // OversizeArrayLit occurs when an array literal exceeds its length.
590 // var _ = [2]int{1,2,3}
593 // MixedStructLit occurs when a struct literal contains a mix of positional
594 // and named elements.
597 // var _ = struct{i, j int}{i: 1, 2}
600 // InvalidStructLit occurs when a positional struct literal has an incorrect
604 // var _ = struct{i, j int}{1,2,3}
607 // MissingLitField occurs when a struct literal refers to a field that does
608 // not exist on the struct type.
611 // var _ = struct{i int}{j: 2}
614 // DuplicateLitField occurs when a struct literal contains duplicated
618 // var _ = struct{i int}{i: 1, i: 2}
621 // UnexportedLitField occurs when a positional struct literal implicitly
622 // assigns an unexported field of an imported type.
625 // InvalidLitField occurs when a field name is not a valid identifier.
628 // var _ = struct{i int}{1: 1}
631 // UntypedLit occurs when a composite literal omits a required type
635 // type outer struct{
636 // inner struct { i int }
639 // var _ = outer{inner: {1}}
642 // InvalidLit occurs when a composite literal expression does not match its
652 // AmbiguousSelector occurs when a selector is ambiguous.
655 // type E1 struct { i int }
656 // type E2 struct { i int }
657 // type T struct { E1; E2 }
663 // UndeclaredImportedName occurs when a package-qualified identifier is
664 // undeclared by the imported package.
669 // var _ = types.NotAnActualIdentifier
670 UndeclaredImportedName
672 // UnexportedName occurs when a selector refers to an unexported identifier
673 // of an imported package.
678 // type _ reflect.flag
681 // UndeclaredName occurs when an identifier is not declared in the current
688 // MissingFieldOrMethod occurs when a selector references a field or method
689 // that does not exist.
697 // BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
701 // var _ = map[int][...]int{0: {}}
704 // NonVariadicDotDotDot occurs when a "..." is used on the final argument to
705 // a non-variadic function.
708 // func printArgs(s []string) {
709 // for _, a := range s {
715 // s := []string{"a", "b", "c"}
720 // MisplacedDotDotDot occurs when a "..." is used somewhere other than the
721 // final argument in a function declaration.
724 // func f(...int, int)
727 _ // InvalidDotDotDotOperand was removed.
729 // InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
733 // var s = []int{1, 2, 3}
737 // UncalledBuiltin occurs when a built-in function is used as a
738 // function-valued expression, instead of being called.
741 // "The built-in functions do not have standard Go types, so they can only
742 // appear in call expressions; they cannot be used as function values."
748 // InvalidAppend occurs when append is called with a first argument that is
752 // var _ = append(1, 2)
755 // InvalidCap occurs when an argument to the cap built-in function is not of
758 // See https://golang.org/ref/spec#Length_and_capacity for information on
759 // which underlying types are supported as arguments to cap and len.
766 // InvalidClose occurs when close(...) is called with an argument that is
767 // not of channel type, or that is a receive-only channel.
776 // InvalidCopy occurs when the arguments are not of slice type or do not
777 // have compatible type.
779 // See https://golang.org/ref/spec#Appending_and_copying_slices for more
780 // information on the type requirements for the copy built-in.
785 // y := []int64{1,2,3}
790 // InvalidComplex occurs when the complex built-in function is called with
791 // arguments with incompatible types.
794 // var _ = complex(float32(1), float64(2))
797 // InvalidDelete occurs when the delete built-in function is called with a
798 // first argument that is not a map.
807 // InvalidImag occurs when the imag built-in function is called with an
808 // argument that does not have complex type.
811 // var _ = imag(int(1))
814 // InvalidLen occurs when an argument to the len built-in function is not of
817 // See https://golang.org/ref/spec#Length_and_capacity for information on
818 // which underlying types are supported as arguments to cap and len.
825 // SwappedMakeArgs occurs when make is called with three arguments, and its
826 // length argument is larger than its capacity argument.
829 // var x = make([]int, 3, 2)
832 // InvalidMake occurs when make is called with an unsupported type argument.
834 // See https://golang.org/ref/spec#Making_slices_maps_and_channels for
835 // information on the types that may be created using make.
841 // InvalidReal occurs when the real built-in function is called with an
842 // argument that does not have complex type.
845 // var _ = real(int(1))
848 // InvalidAssert occurs when a type assertion is applied to a
849 // value that is not of interface type.
853 // var _ = x.(float64)
856 // ImpossibleAssert occurs for a type assertion x.(T) when the value x of
857 // interface cannot have dynamic type T, due to a missing or mismatching
863 // func (t *T) m() int { return int(*t) }
865 // type I interface { m() int }
871 // InvalidConversion occurs when the argument type cannot be converted to the
874 // See https://golang.org/ref/spec#Conversions for the rules of
882 // InvalidUntypedConversion occurs when there is no valid implicit
883 // conversion from an untyped value satisfying the type constraints of the
884 // context in which it is used.
887 // var _ = 1 + []int{}
888 InvalidUntypedConversion
890 // BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
891 // that is not a selector expression.
897 // var _ = unsafe.Offsetof(x)
900 // InvalidOffsetof occurs when unsafe.Offsetof is called with a method
901 // selector, rather than a field selector, or when the field is embedded via
906 // "If f is an embedded field, it must be reachable without pointer
907 // indirections through fields of the struct. "
912 // type T struct { f int }
913 // type S struct { *T }
915 // var _ = unsafe.Offsetof(s.f)
925 // var _ = unsafe.Offsetof(s.m)
928 // UnusedExpr occurs when a side-effect free expression is used as a
929 // statement. Such a statement has no effect.
937 // UnusedVar occurs when a variable is declared but unused.
945 // MissingReturn occurs when a function with results is missing a return
952 // WrongResultCount occurs when a return statement returns an incorrect
956 // func ReturnOne() int {
961 // OutOfScopeResult occurs when the name of a value implicitly returned by
962 // an empty return statement is shadowed in a nested scope.
965 // func factor(n int) (i int) {
966 // for i := 2; i < n; i++ {
975 // InvalidCond occurs when an if condition is not a boolean expression.
978 // func checkReturn(i int) {
980 // panic("non-zero return")
985 // InvalidPostDecl occurs when there is a declaration in a for-loop post
990 // for i := 0; i < 10; j := 0 {}
994 _ // InvalidChanRange was removed.
996 // InvalidIterVar occurs when two iteration variables are used while ranging
1000 // func f(c chan int) {
1001 // for k, v := range c {
1007 // InvalidRangeExpr occurs when the type of a range expression is not
1008 // a valid type for use with a range loop.
1011 // func f(f float64) {
1012 // for j := range f {
1018 // MisplacedBreak occurs when a break statement is not within a for, switch,
1019 // or select statement of the innermost function definition.
1027 // MisplacedContinue occurs when a continue statement is not within a for
1028 // loop of the innermost function definition.
1031 // func sumeven(n int) int {
1032 // proceed := func() {
1036 // for i := 1; i <= n; i++ {
1046 // MisplacedFallthrough occurs when a fallthrough statement is not within an
1047 // expression switch.
1050 // func typename(i interface{}) string {
1051 // switch i.(type) {
1057 // return "unsupported"
1059 MisplacedFallthrough
1061 // DuplicateCase occurs when a type or expression switch has duplicate
1065 // func printInt(i int) {
1075 // DuplicateDefault occurs when a type or expression switch has multiple
1079 // func printInt(i int) {
1091 // BadTypeKeyword occurs when a .(type) expression is used anywhere other
1092 // than a type switch.
1095 // type I interface {
1102 // InvalidTypeSwitch occurs when .(type) is used on an expression that is
1103 // not of interface type.
1107 // switch x := i.(type) {}
1111 // InvalidExprSwitch occurs when a switch expression is not comparable.
1115 // var a struct{ _ func() }
1116 // switch a /* ERROR cannot switch on a */ {
1121 // InvalidSelectCase occurs when a select case is not a channel send or
1125 // func checkChan(c <-chan int) bool {
1135 // UndeclaredLabel occurs when an undeclared label is jumped to.
1143 // DuplicateLabel occurs when a label is declared more than once.
1153 // MisplacedLabel occurs when a break or continue label is not on a for,
1154 // switch, or select statement.
1159 // a := []int{1,2,3}
1160 // for _, e := range a {
1169 // UnusedLabel occurs when a label is declared and not used.
1177 // JumpOverDecl occurs when a label jumps over a variable declaration.
1189 // JumpIntoBlock occurs when a forward jump goes to a label inside a nested
1197 // print("inside block")
1202 // InvalidMethodExpr occurs when a pointer method is called but the argument
1203 // is not addressable.
1208 // func (*T) m() int { return 1 }
1213 // WrongArgCount occurs when too few or too many arguments are passed by a
1221 // InvalidCall occurs when an expression is called that is not of function
1229 // UnusedResults occurs when a restricted expression-only built-in function
1230 // is suspended via go or defer. Such a suspension discards the results of
1231 // these side-effect free built-in functions, and therefore is ineffectual.
1234 // func f(a []int) int {
1240 // InvalidDefer occurs when a deferred expression is not a function call,
1241 // for example if the expression is a type conversion.
1244 // func f(i int) int {
1250 // InvalidGo occurs when a go expression is not a function call, for example
1251 // if the expression is a type conversion.
1254 // func f(i int) int {
1260 // All codes below were added in Go 1.17.
1262 // BadDecl occurs when a declaration has invalid syntax.
1265 // RepeatedDecl occurs when an identifier occurs more than once on the left
1266 // hand side of a short variable declaration.
1270 // x, y, y := 1, 2, 3
1274 // InvalidUnsafeAdd occurs when unsafe.Add is called with a
1275 // length argument that is not of integer type.
1276 // It also occurs if it is used in a package compiled for a
1277 // language version before go1.17.
1282 // var p unsafe.Pointer
1283 // var _ = unsafe.Add(p, float64(1))
1286 // InvalidUnsafeSlice occurs when unsafe.Slice is called with a
1287 // pointer argument that is not of pointer type or a length argument
1288 // that is not of integer type, negative, or out of bounds.
1289 // It also occurs if it is used in a package compiled for a language
1290 // version before go1.17.
1296 // var _ = unsafe.Slice(x, 1)
1302 // var _ = unsafe.Slice(&x, float64(1))
1308 // var _ = unsafe.Slice(&x, -1)
1314 // var _ = unsafe.Slice(&x, uint64(1) << 63)
1317 // All codes below were added in Go 1.18.
1319 // UnsupportedFeature occurs when a language feature is used that is not
1320 // supported at this Go version.
1323 // NotAGenericType occurs when a non-generic type is used where a generic
1324 // type is expected: in type or function instantiation.
1332 // WrongTypeArgCount occurs when a type or function is instantiated with an
1333 // incorrect number of type arguments, including when a generic type or
1334 // function is used without instantiation.
1336 // Errors involving failed type inference are assigned other error codes.
1339 // type T[p any] int
1341 // var _ T[int, string]
1344 // func f[T any]() {}
1349 // CannotInferTypeArgs occurs when type or function type argument inference
1350 // fails to infer all type arguments.
1353 // func f[T any]() {}
1360 // InvalidTypeArg occurs when a type argument does not satisfy its
1361 // corresponding type parameter constraints.
1364 // type T[P ~int] struct{}
1367 InvalidTypeArg // arguments? InferenceFailed
1369 // InvalidInstanceCycle occurs when an invalid cycle is detected
1370 // within the instantiation graph.
1373 // func f[T any]() { f[*T]() }
1374 InvalidInstanceCycle
1376 // InvalidUnion occurs when an embedded union or approximation element is
1380 // type _ interface {
1381 // ~int | interface{ m() }
1385 // MisplacedConstraintIface occurs when a constraint-type interface is used
1386 // outside of constraint position.
1389 // type I interface { ~int }
1392 MisplacedConstraintIface
1394 // InvalidMethodTypeParams occurs when methods have type parameters.
1396 // It cannot be encountered with an AST parsed using go/parser.
1397 InvalidMethodTypeParams
1399 // MisplacedTypeParam occurs when a type parameter is used in a place where
1400 // it is not permitted.
1406 // type T[P any] struct{ *P }
1409 // InvalidUnsafeSliceData occurs when unsafe.SliceData is called with
1410 // an argument that is not of slice type. It also occurs if it is used
1411 // in a package compiled for a language version before go1.20.
1417 // var _ = unsafe.SliceData(x)
1418 InvalidUnsafeSliceData
1420 // InvalidUnsafeString occurs when unsafe.String is called with
1421 // a length argument that is not of integer type, negative, or
1422 // out of bounds. It also occurs if it is used in a package
1423 // compiled for a language version before go1.20.
1429 // var _ = unsafe.String(&b[0], -1)
1432 // InvalidUnsafeStringData occurs if it is used in a package
1433 // compiled for a language version before go1.20.
1434 _ // not used anymore
1436 // InvalidClear occurs when clear is called with an argument
1437 // that is not of map or slice type.
1445 // TypeTooLarge occurs if unsafe.Sizeof or unsafe.Offsetof is
1446 // called with an expression whose type is too large.
1451 // type E [1 << 31 - 1]int
1453 // var _ = unsafe.Sizeof(a)
1458 // type E [1 << 31 - 1]int
1463 // var _ = unsafe.Offsetof(s.x)
1466 // InvalidMinMaxOperand occurs if min or max is called
1467 // with an operand that cannot be ordered because it
1468 // does not support the < operator.
1471 // const _ = min(true)
1475 // var _ = max(s, t)
1476 InvalidMinMaxOperand