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.
9 // This file defines the error codes that can be produced during type-checking.
10 // Collectively, these codes provide an identifier that may be used to
11 // implement special handling for certain types of errors.
13 // Error codes should be fine-grained enough that the exact nature of the error
14 // can be easily determined, but coarse enough that they are not an
15 // implementation detail of the type checking algorithm. As a rule-of-thumb,
16 // errors should be considered equivalent if there is a theoretical refactoring
17 // of the type checker in which they are emitted in exactly one place. For
18 // example, the type checker emits different error messages for "too many
19 // arguments" and "too few arguments", but one can imagine an alternative type
20 // checker where this check instead just emits a single "wrong number of
21 // arguments", so these errors should have the same code.
23 // Error code names should be as brief as possible while retaining accuracy and
24 // distinctiveness. In most cases names should start with an adjective
25 // describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
26 // and end with a noun identifying the relevant language object. For example,
27 // "_DuplicateDecl" or "_InvalidSliceExpr". For brevity, naming follows the
28 // convention that "bad" implies a problem with syntax, and "invalid" implies a
29 // problem with types.
34 // _Test is reserved for errors that only apply while in self-test mode.
39 // _BlankPkgName occurs when a package name is the blank identifier "_".
42 // "The PackageName must not be the blank identifier."
45 // _MismatchedPkgName occurs when a file's package name doesn't match the
46 // package name already established by other files.
49 // _InvalidPkgUse occurs when a package identifier is used outside of a
50 // selector expression.
60 // _BadImportPath occurs when an import path is not valid.
63 // _BrokenImport occurs when importing a package fails.
66 // import "amissingpackage"
69 // _ImportCRenamed occurs when the special import "C" is renamed. "C" is a
70 // pseudo-package, and must not be renamed.
76 // _UnusedImport occurs when an import is unused.
86 // _InvalidInitCycle occurs when an invalid cycle is detected within the
87 // initialization graph.
92 // func f() int { return x }
97 // _DuplicateDecl occurs when an identifier is declared multiple times.
104 // _InvalidDeclCycle occurs when a declaration cycle is not valid.
113 // var n = unsafe.Sizeof(T{})
116 // _InvalidTypeCycle occurs when a cycle in type definitions results in a
117 // type that is not well-defined.
122 // type T [unsafe.Sizeof(T{})]int
127 // _InvalidConstInit occurs when a const declaration has a non-constant
135 // _InvalidConstVal occurs when a const value cannot be converted to its
138 // TODO(findleyr): this error code and example are not very clear. Consider
142 // const _ = 1 << "hello"
145 // _InvalidConstType occurs when the underlying type in a const declaration
146 // is not a valid constant type.
152 /* decls > var (+ other variable assignment codes) */
154 // _UntypedNil occurs when the predeclared (untyped) value nil is used to
155 // initialize a variable declared without an explicit type.
161 // _WrongAssignCount occurs when the number of values on the right-hand side
162 // of an assignment or or initialization expression does not match the number
163 // of variables on the left-hand side.
169 // _UnassignableOperand occurs when the left-hand side of an assignment is
179 // _NoNewVar occurs when a short variable declaration (':=') does not declare
189 // _MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
190 // not have single-valued left-hand or right-hand side.
193 // "In assignment operations, both the left- and right-hand expression lists
194 // must contain exactly one single-valued expression"
204 // _InvalidIfaceAssign occurs when a value of type T is used as an
205 // interface, but T does not implement a method of the expected interface.
208 // type I interface {
217 // _InvalidChanAssign occurs when a chan assignment is invalid.
219 // Per the spec, a value x is assignable to a channel type T if:
220 // "x is a bidirectional channel value, T is a channel type, x's type V and
221 // T have identical element types, and at least one of V or T is not a
229 // // Invalid assignment because both types are named
233 // _IncompatibleAssign occurs when the type of the right-hand side expression
234 // in an assignment cannot be assigned to the type of the variable being
242 // _UnaddressableFieldAssign occurs when trying to assign to a struct field
247 // m := make(map[string]struct{i int})
250 _UnaddressableFieldAssign
252 /* decls > type (+ other type expression codes) */
254 // _NotAType occurs when the identifier used as the underlying type in a type
255 // declaration or the right-hand side of a type alias does not denote a type.
263 // _InvalidArrayLen occurs when an array length is not a constant value.
270 // _BlankIfaceMethod occurs when a method name is '_'.
273 // "The name of each explicitly specified method must be unique and not
277 // type T interface {
282 // _IncomparableMapKey occurs when a map key type does not support the == and
286 // "The comparison operators == and != must be fully defined for operands of
287 // the key type; thus the key type must not be a function, map, or slice."
295 // _InvalidIfaceEmbed occurs when a non-interface type is embedded in an
303 // type I interface {
308 // _InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
309 // and T itself is itself a pointer, an unsafe.Pointer, or an interface.
312 // "An embedded field must be specified as a type name T or as a pointer to
313 // a non-interface type name *T, and T itself may not be a pointer type."
323 /* decls > func and method */
325 // _BadRecv occurs when a method declaration does not have exactly one
326 // receiver parameter.
332 // _InvalidRecv occurs when a receiver type expression is not of the form T
333 // or *T, or T is a pointer type.
341 // _DuplicateFieldAndMethod occurs when an identifier appears as both a field
350 _DuplicateFieldAndMethod
352 // _DuplicateMethod occurs when two methods on the same receiver type have
358 // func (T) m(i int) int { return i }
361 /* decls > special */
363 // _InvalidBlank occurs when a blank identifier is used as a value or type.
366 // "The blank identifier may appear as an operand only on the left-hand side
367 // of an assignment."
373 // _InvalidIota occurs when the predeclared identifier iota is used outside
374 // of a constant declaration.
380 // _MissingInitBody occurs when an init function is missing its body.
386 // _InvalidInitSig occurs when an init function declares parameters or
389 // Deprecated: no longer emitted by the type checker. _InvalidInitDecl is
393 // _InvalidInitDecl occurs when init is declared as anything other than a
400 // func init() int { return 1 }
403 // _InvalidMainDecl occurs when main is declared as anything other than a
404 // function, in a main package.
409 // _TooManyValues occurs when a function returns too many values for the
410 // expression context in which it is used.
413 // func ReturnTwo() (int, int) {
417 // var x = ReturnTwo()
420 // _NotAnExpr occurs when a type expression is used where a value expression
433 // _TruncatedFloat occurs when a float constant is truncated to an integer
440 // _NumericOverflow occurs when a numeric constant overflows its target type.
446 /* exprs > operation */
448 // _UndefinedOp occurs when an operator is not defined for the type(s) used
455 // _MismatchedTypes occurs when operand types are incompatible in a binary
464 // _DivByZero occurs when a division operation is provable at compile
465 // time to be a division by zero.
469 // var x int = 1/divisor
472 // _NonNumericIncDec occurs when an increment or decrement operator is
473 // applied to a non-numeric value.
484 // _UnaddressableOperand occurs when the & operator is applied to an
485 // unaddressable expression.
489 _UnaddressableOperand
491 // _InvalidIndirection occurs when a non-pointer value is indirected via the
501 // _NonIndexableOperand occurs when an index operation is applied to a value
502 // that cannot be indexed.
509 // _InvalidIndex occurs when an index argument is not of integer type,
510 // negative, or out-of-bounds.
513 // var s = [...]int{1,2,3}
517 // var s = []int{1,2,3}
521 // var s = []int{1,2,3}
526 // _SwappedSliceIndices occurs when constant indices in a slice expression
527 // are decreasing in value.
530 // var _ = []int{1,2,3}[2:1]
533 /* operators > slice */
535 // _NonSliceableOperand occurs when a slice operation is applied to a value
536 // whose type is not sliceable, or is unaddressable.
539 // var x = [...]int{1, 2, 3}[:1]
546 // _InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
547 // applied to a string.
556 // _InvalidShiftCount occurs when the right-hand side of a shift operation is
557 // either non-integer, negative, or too large.
566 // _InvalidShiftOperand occurs when the shifted operand is not an integer.
575 // _InvalidReceive occurs when there is a channel receive from a value that
576 // is either not a channel, or is a send-only channel.
585 // _InvalidSend occurs when there is a channel send to a value that is not a
586 // channel, or is a receive-only channel.
595 /* exprs > literal */
597 // _DuplicateLitKey occurs when an index is duplicated in a slice, array, or
601 // var _ = []int{0:1, 0:2}
604 // var _ = map[string]int{"a": 1, "a": 2}
607 // _MissingLitKey occurs when a map literal is missing a key expression.
610 // var _ = map[string]int{1}
613 // _InvalidLitIndex occurs when the key in a key-value element of a slice or
614 // array literal is not an integer constant.
618 // var x = []string{i: "world"}
621 // _OversizeArrayLit occurs when an array literal exceeds its length.
624 // var _ = [2]int{1,2,3}
627 // _MixedStructLit occurs when a struct literal contains a mix of positional
628 // and named elements.
631 // var _ = struct{i, j int}{i: 1, 2}
634 // _InvalidStructLit occurs when a positional struct literal has an incorrect
638 // var _ = struct{i, j int}{1,2,3}
641 // _MissingLitField occurs when a struct literal refers to a field that does
642 // not exist on the struct type.
645 // var _ = struct{i int}{j: 2}
648 // _DuplicateLitField occurs when a struct literal contains duplicated
652 // var _ = struct{i int}{i: 1, i: 2}
655 // _UnexportedLitField occurs when a positional struct literal implicitly
656 // assigns an unexported field of an imported type.
659 // _InvalidLitField occurs when a field name is not a valid identifier.
662 // var _ = struct{i int}{1: 1}
665 // _UntypedLit occurs when a composite literal omits a required type
669 // type outer struct{
670 // inner struct { i int }
673 // var _ = outer{inner: {1}}
676 // _InvalidLit occurs when a composite literal expression does not match its
686 /* exprs > selector */
688 // _AmbiguousSelector occurs when a selector is ambiguous.
691 // type E1 struct { i int }
692 // type E2 struct { i int }
693 // type T struct { E1; E2 }
699 // _UndeclaredImportedName occurs when a package-qualified identifier is
700 // undeclared by the imported package.
705 // var _ = types.NotAnActualIdentifier
706 _UndeclaredImportedName
708 // _UnexportedName occurs when a selector refers to an unexported identifier
709 // of an imported package.
714 // type _ reflect.flag
717 // _UndeclaredName occurs when an identifier is not declared in the current
724 // _MissingFieldOrMethod occurs when a selector references a field or method
725 // that does not exist.
731 _MissingFieldOrMethod
735 // _BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
739 // var _ = map[int][...]int{0: {}}
742 // _NonVariadicDotDotDot occurs when a "..." is used on the final argument to
743 // a non-variadic function.
746 // func printArgs(s []string) {
747 // for _, a := range s {
753 // s := []string{"a", "b", "c"}
756 _NonVariadicDotDotDot
758 // _MisplacedDotDotDot occurs when a "..." is used somewhere other than the
759 // final argument in a function declaration.
762 // func f(...int, int)
765 // _InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
769 // var s = []int{1, 2, 3}
773 /* exprs > built-in */
775 // _UncalledBuiltin occurs when a built-in function is used as a
776 // function-valued expression, instead of being called.
779 // "The built-in functions do not have standard Go types, so they can only
780 // appear in call expressions; they cannot be used as function values."
786 // _InvalidAppend occurs when append is called with a first argument that is
790 // var _ = append(1, 2)
793 // _InvalidCap occurs when an argument to the cap built-in function is not of
796 // See https://golang.org/ref/spec#Length_and_capacity for information on
797 // which underlying types are supported as arguments to cap and len.
804 // _InvalidClose occurs when close(...) is called with an argument that is
805 // not of channel type, or that is a receive-only channel.
814 // _InvalidCopy occurs when the arguments are not of slice type or do not
815 // have compatible type.
817 // See https://golang.org/ref/spec#Appending_and_copying_slices for more
818 // information on the type requirements for the copy built-in.
823 // y := []int64{1,2,3}
828 // _InvalidComplex occurs when the complex built-in function is called with
829 // arguments with incompatible types.
832 // var _ = complex(float32(1), float64(2))
835 // _InvalidDelete occurs when the delete built-in function is called with a
836 // first argument that is not a map.
845 // _InvalidImag occurs when the imag built-in function is called with an
846 // argument that does not have complex type.
849 // var _ = imag(int(1))
852 // _InvalidLen occurs when an argument to the len built-in function is not of
855 // See https://golang.org/ref/spec#Length_and_capacity for information on
856 // which underlying types are supported as arguments to cap and len.
863 // _SwappedMakeArgs occurs when make is called with three arguments, and its
864 // length argument is larger than its capacity argument.
867 // var x = make([]int, 3, 2)
870 // _InvalidMake occurs when make is called with an unsupported type argument.
872 // See https://golang.org/ref/spec#Making_slices_maps_and_channels for
873 // information on the types that may be created using make.
879 // _InvalidReal occurs when the real built-in function is called with an
880 // argument that does not have complex type.
883 // var _ = real(int(1))
886 /* exprs > assertion */
888 // _InvalidAssert occurs when a type assertion is applied to a
889 // value that is not of interface type.
893 // var _ = x.(float64)
896 // _ImpossibleAssert occurs for a type assertion x.(T) when the value x of
897 // interface cannot have dynamic type T, due to a missing or mismatching
903 // func (t *T) m() int { return int(*t) }
905 // type I interface { m() int }
911 /* exprs > conversion */
913 // _InvalidConversion occurs when the argument type cannot be converted to the
916 // See https://golang.org/ref/spec#Conversions for the rules of
924 // _InvalidUntypedConversion occurs when an there is no valid implicit
925 // conversion from an untyped value satisfying the type constraints of the
926 // context in which it is used.
930 _InvalidUntypedConversion
934 // _BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
935 // that is not a selector expression.
941 // var _ = unsafe.Offsetof(x)
944 // _InvalidOffsetof occurs when unsafe.Offsetof is called with a method
945 // selector, rather than a field selector, or when the field is embedded via
950 // "If f is an embedded field, it must be reachable without pointer
951 // indirections through fields of the struct. "
956 // type T struct { f int }
957 // type S struct { *T }
959 // var _ = unsafe.Offsetof(s.f)
969 // var _ = unsafe.Offsetof(s.m)
972 /* control flow > scope */
974 // _UnusedExpr occurs when a side-effect free expression is used as a
975 // statement. Such a statement has no effect.
983 // _UnusedVar occurs when a variable is declared but unused.
991 // _MissingReturn occurs when a function with results is missing a return
998 // _WrongResultCount occurs when a return statement returns an incorrect
1002 // func ReturnOne() int {
1007 // _OutOfScopeResult occurs when the name of a value implicitly returned by
1008 // an empty return statement is shadowed in a nested scope.
1011 // func factor(n int) (i int) {
1012 // for i := 2; i < n; i++ {
1021 /* control flow > if */
1023 // _InvalidCond occurs when an if condition is not a boolean expression.
1026 // func checkReturn(i int) {
1028 // panic("non-zero return")
1033 /* control flow > for */
1035 // _InvalidPostDecl occurs when there is a declaration in a for-loop post
1040 // for i := 0; i < 10; j := 0 {}
1044 // _InvalidIterVar occurs when two iteration variables are used while ranging
1048 // func f(c chan int) {
1049 // for k, v := range c {
1055 // _InvalidRangeExpr occurs when the type of a range expression is not array,
1056 // slice, string, map, or channel.
1060 // for j := range i {
1066 /* control flow > switch */
1068 // _MisplacedBreak occurs when a break statement is not within a for, switch,
1069 // or select statement of the innermost function definition.
1077 // _MisplacedContinue occurs when a continue statement is not within a for
1078 // loop of the innermost function definition.
1081 // func sumeven(n int) int {
1082 // proceed := func() {
1086 // for i := 1; i <= n; i++ {
1096 // _MisplacedFallthrough occurs when a fallthrough statement is not within an
1097 // expression switch.
1100 // func typename(i interface{}) string {
1101 // switch i.(type) {
1107 // return "unsupported"
1109 _MisplacedFallthrough
1111 // _DuplicateCase occurs when a type or expression switch has duplicate
1115 // func printInt(i int) {
1125 // _DuplicateDefault occurs when a type or expression switch has multiple
1129 // func printInt(i int) {
1141 // _BadTypeKeyword occurs when a .(type) expression is used anywhere other
1142 // than a type switch.
1145 // type I interface {
1152 // _InvalidTypeSwitch occurs when .(type) is used on an expression that is
1153 // not of interface type.
1157 // switch x := i.(type) {}
1161 // _InvalidExprSwitch occurs when a switch expression is not comparable.
1165 // var a struct{ _ func() }
1166 // switch a /* ERROR cannot switch on a */ {
1171 /* control flow > select */
1173 // _InvalidSelectCase occurs when a select case is not a channel send or
1177 // func checkChan(c <-chan int) bool {
1187 /* control flow > labels and jumps */
1189 // _UndeclaredLabel occurs when an undeclared label is jumped to.
1197 // _DuplicateLabel occurs when a label is declared more than once.
1207 // _MisplacedLabel occurs when a break or continue label is not on a for,
1208 // switch, or select statement.
1213 // a := []int{1,2,3}
1214 // for _, e := range a {
1223 // _UnusedLabel occurs when a label is declared but not used.
1231 // _JumpOverDecl occurs when a label jumps over a variable declaration.
1243 // _JumpIntoBlock occurs when a forward jump goes to a label inside a nested
1251 // print("inside block")
1256 /* control flow > calls */
1258 // _InvalidMethodExpr occurs when a pointer method is called but the argument
1259 // is not addressable.
1264 // func (*T) m() int { return 1 }
1269 // _WrongArgCount occurs when too few or too many arguments are passed by a
1277 // _InvalidCall occurs when an expression is called that is not of function
1285 /* control flow > suspended */
1287 // _UnusedResults occurs when a restricted expression-only built-in function
1288 // is suspended via go or defer. Such a suspension discards the results of
1289 // these side-effect free built-in functions, and therefore is ineffectual.
1292 // func f(a []int) int {
1298 // _InvalidDefer occurs when a deferred expression is not a function call,
1299 // for example if the expression is a type conversion.
1302 // func f(i int) int {
1308 // _InvalidGo occurs when a go expression is not a function call, for example
1309 // if the expression is a type conversion.
1312 // func f(i int) int {
1318 // _Todo is a placeholder for error codes that have not been decided.
1319 // TODO(rFindley) remove this error code after deciding on errors for generics code.