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=ErrorCode
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 codes should be fine-grained enough that the exact nature of the error
16 // can be easily determined, but coarse enough that they are not an
17 // implementation detail of the type checking algorithm. As a rule-of-thumb,
18 // errors should be considered equivalent if there is a theoretical refactoring
19 // of the type checker in which they are emitted in exactly one place. For
20 // example, the type checker emits different error messages for "too many
21 // arguments" and "too few arguments", but one can imagine an alternative type
22 // checker where this check instead just emits a single "wrong number of
23 // arguments", so these errors should have the same code.
25 // Error code names should be as brief as possible while retaining accuracy and
26 // distinctiveness. In most cases names should start with an adjective
27 // describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
28 // and end with a noun identifying the relevant language object. For example,
29 // "DuplicateDecl" or "InvalidSliceExpr". For brevity, naming follows the
30 // convention that "bad" implies a problem with syntax, and "invalid" implies a
31 // problem with types.
36 // Test is reserved for errors that only apply while in self-test mode.
41 // BlankPkgName occurs when a package name is the blank identifier "_".
44 // "The PackageName must not be the blank identifier."
47 // MismatchedPkgName occurs when a file's package name doesn't match the
48 // package name already established by other files.
51 // InvalidPkgUse occurs when a package identifier is used outside of a
52 // selector expression.
62 // BadImportPath occurs when an import path is not valid.
65 // BrokenImport occurs when importing a package fails.
68 // import "amissingpackage"
71 // ImportCRenamed occurs when the special import "C" is renamed. "C" is a
72 // pseudo-package, and must not be renamed.
78 // UnusedImport occurs when an import is unused.
88 // InvalidInitCycle occurs when an invalid cycle is detected within the
89 // initialization graph.
94 // func f() int { return x }
99 // DuplicateDecl occurs when an identifier is declared multiple times.
106 // InvalidDeclCycle occurs when a declaration cycle is not valid.
115 // var n = unsafe.Sizeof(T{})
118 // InvalidTypeCycle occurs when a cycle in type definitions results in a
119 // type that is not well-defined.
124 // type T [unsafe.Sizeof(T{})]int
129 // InvalidConstInit occurs when a const declaration has a non-constant
137 // InvalidConstVal occurs when a const value cannot be converted to its
140 // TODO(findleyr): this error code and example are not very clear. Consider
144 // const _ = 1 << "hello"
147 // InvalidConstType occurs when the underlying type in a const declaration
148 // is not a valid constant type.
154 /* decls > var (+ other variable assignment codes) */
156 // UntypedNil occurs when the predeclared (untyped) value nil is used to
157 // initialize a variable declared without an explicit type.
163 // WrongAssignCount occurs when the number of values on the right-hand side
164 // of an assignment or or initialization expression does not match the number
165 // of variables on the left-hand side.
171 // UnassignableOperand occurs when the left-hand side of an assignment is
181 // NoNewVar occurs when a short variable declaration (':=') does not declare
191 // MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
192 // not have single-valued left-hand or right-hand side.
195 // "In assignment operations, both the left- and right-hand expression lists
196 // must contain exactly one single-valued expression"
206 // InvalidIfaceAssign occurs when a value of type T is used as an
207 // interface, but T does not implement a method of the expected interface.
210 // type I interface {
219 // InvalidChanAssign occurs when a chan assignment is invalid.
221 // Per the spec, a value x is assignable to a channel type T if:
222 // "x is a bidirectional channel value, T is a channel type, x's type V and
223 // T have identical element types, and at least one of V or T is not a
231 // // Invalid assignment because both types are named
235 // IncompatibleAssign occurs when the type of the right-hand side expression
236 // in an assignment cannot be assigned to the type of the variable being
244 // UnaddressableFieldAssign occurs when trying to assign to a struct field
249 // m := make(map[string]struct{i int})
252 UnaddressableFieldAssign
254 /* decls > type (+ other type expression codes) */
256 // NotAType occurs when the identifier used as the underlying type in a type
257 // declaration or the right-hand side of a type alias does not denote a type.
265 // InvalidArrayLen occurs when an array length is not a constant value.
272 // BlankIfaceMethod occurs when a method name is '_'.
275 // "The name of each explicitly specified method must be unique and not
279 // type T interface {
284 // IncomparableMapKey occurs when a map key type does not support the == and
288 // "The comparison operators == and != must be fully defined for operands of
289 // the key type; thus the key type must not be a function, map, or slice."
297 // InvalidIfaceEmbed occurs when a non-interface type is embedded in an
305 // type I interface {
310 // InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
311 // and T itself is itself a pointer, an unsafe.Pointer, or an interface.
314 // "An embedded field must be specified as a type name T or as a pointer to
315 // a non-interface type name *T, and T itself may not be a pointer type."
325 /* decls > func and method */
327 // BadRecv occurs when a method declaration does not have exactly one
328 // receiver parameter.
334 // InvalidRecv occurs when a receiver type expression is not of the form T
335 // or *T, or T is a pointer type.
343 // DuplicateFieldAndMethod occurs when an identifier appears as both a field
352 DuplicateFieldAndMethod
354 // DuplicateMethod occurs when two methods on the same receiver type have
360 // func (T) m(i int) int { return i }
363 /* decls > special */
365 // InvalidBlank occurs when a blank identifier is used as a value or type.
368 // "The blank identifier may appear as an operand only on the left-hand side
369 // of an assignment."
375 // InvalidIota occurs when the predeclared identifier iota is used outside
376 // of a constant declaration.
382 // MissingInitBody occurs when an init function is missing its body.
388 // InvalidInitSig occurs when an init function declares parameters or
392 // func init() int { return 1 }
395 // InvalidInitDecl occurs when init is declared as anything other than a
402 // InvalidMainDecl occurs when main is declared as anything other than a
403 // function, in a main package.
408 // TooManyValues occurs when a function returns too many values for the
409 // expression context in which it is used.
412 // func ReturnTwo() (int, int) {
416 // var x = ReturnTwo()
419 // NotAnExpr occurs when a type expression is used where a value expression
432 // TruncatedFloat occurs when a float constant is truncated to an integer
439 // NumericOverflow occurs when a numeric constant overflows its target type.
445 /* exprs > operation */
447 // UndefinedOp occurs when an operator is not defined for the type(s) used
454 // MismatchedTypes occurs when operand types are incompatible in a binary
463 // DivByZero occurs when a division operation is provable at compile
464 // time to be a division by zero.
468 // var x int = 1/divisor
471 // NonNumericIncDec occurs when an increment or decrement operator is
472 // applied to a non-numeric value.
483 // UnaddressableOperand occurs when the & operator is applied to an
484 // unaddressable expression.
490 // InvalidIndirection occurs when a non-pointer value is indirected via the
500 // NonIndexableOperand occurs when an index operation is applied to a value
501 // that cannot be indexed.
508 // InvalidIndex occurs when an index argument is not of integer type,
509 // negative, or out-of-bounds.
512 // var s = [...]int{1,2,3}
516 // var s = []int{1,2,3}
520 // var s = []int{1,2,3}
525 // SwappedSliceIndices occurs when constant indices in a slice expression
526 // are decreasing in value.
529 // var _ = []int{1,2,3}[2:1]
532 /* operators > slice */
534 // NonSliceableOperand occurs when a slice operation is applied to a value
535 // whose type is not sliceable, or is unaddressable.
538 // var x = [...]int{1, 2, 3}[:1]
545 // InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
546 // applied to a string.
555 // InvalidShiftCount occurs when the right-hand side of a shift operation is
556 // either non-integer, negative, or too large.
565 // InvalidShiftOperand occurs when the shifted operand is not an integer.
574 // InvalidReceive occurs when there is a channel receive from a value that
575 // is either not a channel, or is a send-only channel.
584 // InvalidSend occurs when there is a channel send to a value that is not a
585 // channel, or is a receive-only channel.
594 /* exprs > literal */
596 // DuplicateLitKey occurs when an index is duplicated in a slice, array, or
600 // var _ = []int{0:1, 0:2}
603 // var _ = map[string]int{"a": 1, "a": 2}
606 // MissingLitKey occurs when a map literal is missing a key expression.
609 // var _ = map[string]int{1}
612 // InvalidLitIndex occurs when the key in a key-value element of a slice or
613 // array literal is not an integer constant.
617 // var x = []string{i: "world"}
620 // OversizeArrayLit occurs when an array literal exceeds its length.
623 // var _ = [2]int{1,2,3}
626 // MixedStructLit occurs when a struct literal contains a mix of positional
627 // and named elements.
630 // var _ = struct{i, j int}{i: 1, 2}
633 // InvalidStructLit occurs when a positional struct literal has an incorrect
637 // var _ = struct{i, j int}{1,2,3}
640 // MissingLitField occurs when a struct literal refers to a field that does
641 // not exist on the struct type.
644 // var _ = struct{i int}{j: 2}
647 // DuplicateLitField occurs when a struct literal contains duplicated
651 // var _ = struct{i int}{i: 1, i: 2}
654 // UnexportedLitField occurs when a positional struct literal implicitly
655 // assigns an unexported field of an imported type.
658 // InvalidLitField occurs when a field name is not a valid identifier.
661 // var _ = struct{i int}{1: 1}
664 // UntypedLit occurs when a composite literal omits a required type
668 // type outer struct{
669 // inner struct { i int }
672 // var _ = outer{inner: {1}}
675 // InvalidLit occurs when a composite literal expression does not match its
685 /* exprs > selector */
687 // AmbiguousSelector occurs when a selector is ambiguous.
690 // type E1 struct { i int }
691 // type E2 struct { i int }
692 // type T struct { E1; E2 }
698 // UndeclaredImportedName occurs when a package-qualified identifier is
699 // undeclared by the imported package.
704 // var _ = types.NotAnActualIdentifier
705 UndeclaredImportedName
707 // UnexportedName occurs when a selector refers to an unexported identifier
708 // of an imported package.
713 // type _ reflect.flag
716 // UndeclaredName occurs when an identifier is not declared in the current
723 // MissingFieldOrMethod occurs when a selector references a field or method
724 // that does not exist.
734 // BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
738 // var _ = map[int][...]int{0: {}}
741 // NonVariadicDotDotDot occurs when a "..." is used on the final argument to
742 // a non-variadic function.
745 // func printArgs(s []string) {
746 // for _, a := range s {
752 // s := []string{"a", "b", "c"}
757 // MisplacedDotDotDot occurs when a "..." is used somewhere other than the
758 // final argument to a function call.
761 // func printArgs(args ...int) {
762 // for _, a := range args {
769 // printArgs(0, a...)
773 // InvalidDotDotDotOperand occurs when a "..." operator is applied to a
774 // single-valued operand.
777 // func printArgs(args ...int) {
778 // for _, a := range args {
789 // func args() (int, int) {
793 // func printArgs(args ...int) {
794 // for _, a := range args {
800 // printArgs(args()...)
802 InvalidDotDotDotOperand
804 // InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
808 // var s = []int{1, 2, 3}
812 /* exprs > built-in */
814 // UncalledBuiltin occurs when a built-in function is used as a
815 // function-valued expression, instead of being called.
818 // "The built-in functions do not have standard Go types, so they can only
819 // appear in call expressions; they cannot be used as function values."
825 // InvalidAppend occurs when append is called with a first argument that is
829 // var _ = append(1, 2)
832 // InvalidCap occurs when an argument to the cap built-in function is not of
835 // See https://golang.org/ref/spec#Lengthand_capacity for information on
836 // which underlying types are supported as arguments to cap and len.
843 // InvalidClose occurs when close(...) is called with an argument that is
844 // not of channel type, or that is a receive-only channel.
853 // InvalidCopy occurs when the arguments are not of slice type or do not
854 // have compatible type.
856 // See https://golang.org/ref/spec#Appendingand_copying_slices for more
857 // information on the type requirements for the copy built-in.
862 // y := []int64{1,2,3}
867 // InvalidComplex occurs when the complex built-in function is called with
868 // arguments with incompatible types.
871 // var _ = complex(float32(1), float64(2))
874 // InvalidDelete occurs when the delete built-in function is called with a
875 // first argument that is not a map.
884 // InvalidImag occurs when the imag built-in function is called with an
885 // argument that does not have complex type.
888 // var _ = imag(int(1))
891 // InvalidLen occurs when an argument to the len built-in function is not of
894 // See https://golang.org/ref/spec#Lengthand_capacity for information on
895 // which underlying types are supported as arguments to cap and len.
902 // SwappedMakeArgs occurs when make is called with three arguments, and its
903 // length argument is larger than its capacity argument.
906 // var x = make([]int, 3, 2)
909 // InvalidMake occurs when make is called with an unsupported type argument.
911 // See https://golang.org/ref/spec#Makingslices_maps_and_channels for
912 // information on the types that may be created using make.
918 // InvalidReal occurs when the real built-in function is called with an
919 // argument that does not have complex type.
922 // var _ = real(int(1))
925 /* exprs > assertion */
927 // InvalidAssert occurs when a type assertion is applied to a
928 // value that is not of interface type.
932 // var _ = x.(float64)
935 // ImpossibleAssert occurs for a type assertion x.(T) when the value x of
936 // interface cannot have dynamic type T, due to a missing or mismatching
942 // func (t *T) m() int { return int(*t) }
944 // type I interface { m() int }
950 /* exprs > conversion */
952 // InvalidConversion occurs when the argument type cannot be converted to the
955 // See https://golang.org/ref/spec#Conversions for the rules of
963 // InvalidUntypedConversion occurs when an there is no valid implicit
964 // conversion from an untyped value satisfying the type constraints of the
965 // context in which it is used.
969 InvalidUntypedConversion
973 // BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
974 // that is not a selector expression.
980 // var _ = unsafe.Offsetof(x)
983 // InvalidOffsetof occurs when unsafe.Offsetof is called with a method
984 // selector, rather than a field selector, or when the field is embedded via
989 // "If f is an embedded field, it must be reachable without pointer
990 // indirections through fields of the struct. "
995 // type T struct { f int }
996 // type S struct { *T }
998 // var _ = unsafe.Offsetof(s.f)
1008 // var _ = unsafe.Offsetof(s.m)
1011 /* control flow > scope */
1013 // UnusedExpr occurs when a side-effect free expression is used as a
1014 // statement. Such a statement has no effect.
1022 // UnusedVar occurs when a variable is declared but unused.
1030 // MissingReturn occurs when a function with results is missing a return
1037 // WrongResultCount occurs when a return statement returns an incorrect
1038 // number of values.
1041 // func ReturnOne() int {
1046 // OutOfScopeResult occurs when the name of a value implicitly returned by
1047 // an empty return statement is shadowed in a nested scope.
1050 // func factor(n int) (i int) {
1051 // for i := 2; i < n; i++ {
1060 /* control flow > if */
1062 // InvalidCond occurs when an if condition is not a boolean expression.
1065 // func checkReturn(i int) {
1067 // panic("non-zero return")
1072 /* control flow > for */
1074 // InvalidPostDecl occurs when there is a declaration in a for-loop post
1079 // for i := 0; i < 10; j := 0 {}
1083 // InvalidChanRange occurs when a send-only channel used in a range
1087 // func sum(c chan<- int) {
1089 // for i := range c {
1095 // InvalidIterVar occurs when two iteration variables are used while ranging
1099 // func f(c chan int) {
1100 // for k, v := range c {
1106 // InvalidRangeExpr occurs when the type of a range expression is not array,
1107 // slice, string, map, or channel.
1111 // for j := range i {
1117 /* control flow > switch */
1119 // MisplacedBreak occurs when a break statement is not within a for, switch,
1120 // or select statement of the innermost function definition.
1128 // MisplacedContinue occurs when a continue statement is not within a for
1129 // loop of the innermost function definition.
1132 // func sumeven(n int) int {
1133 // proceed := func() {
1137 // for i := 1; i <= n; i++ {
1147 // MisplacedFallthrough occurs when a fallthrough statement is not within an
1148 // expression switch.
1151 // func typename(i interface{}) string {
1152 // switch i.(type) {
1158 // return "unsupported"
1160 MisplacedFallthrough
1162 // DuplicateCase occurs when a type or expression switch has duplicate
1166 // func printInt(i int) {
1176 // DuplicateDefault occurs when a type or expression switch has multiple
1180 // func printInt(i int) {
1192 // BadTypeKeyword occurs when a .(type) expression is used anywhere other
1193 // than a type switch.
1196 // type I interface {
1203 // InvalidTypeSwitch occurs when .(type) is used on an expression that is
1204 // not of interface type.
1208 // switch x := i.(type) {}
1212 /* control flow > select */
1214 // InvalidSelectCase occurs when a select case is not a channel send or
1218 // func checkChan(c <-chan int) bool {
1228 /* control flow > labels and jumps */
1230 // UndeclaredLabel occurs when an undeclared label is jumped to.
1238 // DuplicateLabel occurs when a label is declared more than once.
1248 // MisplacedLabel occurs when a break or continue label is not on a for,
1249 // switch, or select statement.
1254 // a := []int{1,2,3}
1255 // for _, e := range a {
1264 // UnusedLabel occurs when a label is declared but not used.
1272 // JumpOverDecl occurs when a label jumps over a variable declaration.
1284 // JumpIntoBlock occurs when a forward jump goes to a label inside a nested
1292 // print("inside block")
1297 /* control flow > calls */
1299 // InvalidMethodExpr occurs when a pointer method is called but the argument
1300 // is not addressable.
1305 // func (*T) m() int { return 1 }
1310 // WrongArgCount occurs when too few or too many arguments are passed by a
1318 // InvalidCall occurs when an expression is called that is not of function
1326 /* control flow > suspended */
1328 // UnusedResults occurs when a restricted expression-only built-in function
1329 // is suspended via go or defer. Such a suspension discards the results of
1330 // these side-effect free built-in functions, and therefore is ineffectual.
1333 // func f(a []int) int {
1339 // InvalidDefer occurs when a deferred expression is not a function call,
1340 // for example if the expression is a type conversion.
1343 // func f(i int) int {
1349 // InvalidGo occurs when a go expression is not a function call, for example
1350 // if the expression is a type conversion.
1353 // func f(i int) int {