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 // TODO(rFindley): ensure that existing error codes do not change in the
10 // dev.typeparams branch.
12 // This file defines the error codes that can be produced during type-checking.
13 // Collectively, these codes provide an identifier that may be used to
14 // implement special handling for certain types of errors.
16 // Error codes should be fine-grained enough that the exact nature of the error
17 // can be easily determined, but coarse enough that they are not an
18 // implementation detail of the type checking algorithm. As a rule-of-thumb,
19 // errors should be considered equivalent if there is a theoretical refactoring
20 // of the type checker in which they are emitted in exactly one place. For
21 // example, the type checker emits different error messages for "too many
22 // arguments" and "too few arguments", but one can imagine an alternative type
23 // checker where this check instead just emits a single "wrong number of
24 // arguments", so these errors should have the same code.
26 // Error code names should be as brief as possible while retaining accuracy and
27 // distinctiveness. In most cases names should start with an adjective
28 // describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
29 // and end with a noun identifying the relevant language object. For example,
30 // "_DuplicateDecl" or "_InvalidSliceExpr". For brevity, naming follows the
31 // convention that "bad" implies a problem with syntax, and "invalid" implies a
32 // problem with types.
37 // _Test is reserved for errors that only apply while in self-test mode.
42 // _BlankPkgName occurs when a package name is the blank identifier "_".
45 // "The PackageName must not be the blank identifier."
48 // _MismatchedPkgName occurs when a file's package name doesn't match the
49 // package name already established by other files.
52 // _InvalidPkgUse occurs when a package identifier is used outside of a
53 // selector expression.
63 // _BadImportPath occurs when an import path is not valid.
66 // _BrokenImport occurs when importing a package fails.
69 // import "amissingpackage"
72 // _ImportCRenamed occurs when the special import "C" is renamed. "C" is a
73 // pseudo-package, and must not be renamed.
79 // _UnusedImport occurs when an import is unused.
89 // _InvalidInitCycle occurs when an invalid cycle is detected within the
90 // initialization graph.
95 // func f() int { return x }
100 // _DuplicateDecl occurs when an identifier is declared multiple times.
107 // _InvalidDeclCycle occurs when a declaration cycle is not valid.
116 // var n = unsafe.Sizeof(T{})
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
130 // _InvalidConstInit occurs when a const declaration has a non-constant
138 // _InvalidConstVal occurs when a const value cannot be converted to its
141 // TODO(findleyr): this error code and example are not very clear. Consider
145 // const _ = 1 << "hello"
148 // _InvalidConstType occurs when the underlying type in a const declaration
149 // is not a valid constant type.
155 /* decls > var (+ other variable assignment codes) */
157 // _UntypedNil occurs when the predeclared (untyped) value nil is used to
158 // initialize a variable declared without an explicit type.
164 // _WrongAssignCount occurs when the number of values on the right-hand side
165 // of an assignment or or initialization expression does not match the number
166 // of variables on the left-hand side.
172 // _UnassignableOperand occurs when the left-hand side of an assignment is
182 // _NoNewVar occurs when a short variable declaration (':=') does not declare
192 // _MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
193 // not have single-valued left-hand or right-hand side.
196 // "In assignment operations, both the left- and right-hand expression lists
197 // must contain exactly one single-valued expression"
207 // _InvalidIfaceAssign occurs when a value of type T is used as an
208 // interface, but T does not implement a method of the expected interface.
211 // type I interface {
220 // _InvalidChanAssign occurs when a chan assignment is invalid.
222 // Per the spec, a value x is assignable to a channel type T if:
223 // "x is a bidirectional channel value, T is a channel type, x's type V and
224 // T have identical element types, and at least one of V or T is not a
232 // // Invalid assignment because both types are named
236 // _IncompatibleAssign occurs when the type of the right-hand side expression
237 // in an assignment cannot be assigned to the type of the variable being
245 // _UnaddressableFieldAssign occurs when trying to assign to a struct field
250 // m := make(map[string]struct{i int})
253 _UnaddressableFieldAssign
255 /* decls > type (+ other type expression codes) */
257 // _NotAType occurs when the identifier used as the underlying type in a type
258 // declaration or the right-hand side of a type alias does not denote a type.
266 // _InvalidArrayLen occurs when an array length is not a constant value.
273 // _BlankIfaceMethod occurs when a method name is '_'.
276 // "The name of each explicitly specified method must be unique and not
280 // type T interface {
285 // _IncomparableMapKey occurs when a map key type does not support the == and
289 // "The comparison operators == and != must be fully defined for operands of
290 // the key type; thus the key type must not be a function, map, or slice."
298 // _InvalidIfaceEmbed occurs when a non-interface type is embedded in an
306 // type I interface {
311 // _InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
312 // and T itself is itself a pointer, an unsafe.Pointer, or an interface.
315 // "An embedded field must be specified as a type name T or as a pointer to
316 // a non-interface type name *T, and T itself may not be a pointer type."
326 /* decls > func and method */
328 // _BadRecv occurs when a method declaration does not have exactly one
329 // receiver parameter.
335 // _InvalidRecv occurs when a receiver type expression is not of the form T
336 // or *T, or T is a pointer type.
344 // _DuplicateFieldAndMethod occurs when an identifier appears as both a field
353 _DuplicateFieldAndMethod
355 // _DuplicateMethod occurs when two methods on the same receiver type have
361 // func (T) m(i int) int { return i }
364 /* decls > special */
366 // _InvalidBlank occurs when a blank identifier is used as a value or type.
369 // "The blank identifier may appear as an operand only on the left-hand side
370 // of an assignment."
376 // _InvalidIota occurs when the predeclared identifier iota is used outside
377 // of a constant declaration.
383 // _MissingInitBody occurs when an init function is missing its body.
389 // _InvalidInitSig occurs when an init function declares parameters or
392 // Deprecated: no longer emitted by the type checker. _InvalidInitDecl is
396 // _InvalidInitDecl occurs when init is declared as anything other than a
403 // func init() int { return 1 }
406 // _InvalidMainDecl occurs when main is declared as anything other than a
407 // function, in a main package.
412 // _TooManyValues occurs when a function returns too many values for the
413 // expression context in which it is used.
416 // func ReturnTwo() (int, int) {
420 // var x = ReturnTwo()
423 // _NotAnExpr occurs when a type expression is used where a value expression
436 // _TruncatedFloat occurs when a float constant is truncated to an integer
443 // _NumericOverflow occurs when a numeric constant overflows its target type.
449 /* exprs > operation */
451 // _UndefinedOp occurs when an operator is not defined for the type(s) used
458 // _MismatchedTypes occurs when operand types are incompatible in a binary
467 // _DivByZero occurs when a division operation is provable at compile
468 // time to be a division by zero.
472 // var x int = 1/divisor
475 // _NonNumericIncDec occurs when an increment or decrement operator is
476 // applied to a non-numeric value.
487 // _UnaddressableOperand occurs when the & operator is applied to an
488 // unaddressable expression.
492 _UnaddressableOperand
494 // _InvalidIndirection occurs when a non-pointer value is indirected via the
504 // _NonIndexableOperand occurs when an index operation is applied to a value
505 // that cannot be indexed.
512 // _InvalidIndex occurs when an index argument is not of integer type,
513 // negative, or out-of-bounds.
516 // var s = [...]int{1,2,3}
520 // var s = []int{1,2,3}
524 // var s = []int{1,2,3}
529 // _SwappedSliceIndices occurs when constant indices in a slice expression
530 // are decreasing in value.
533 // var _ = []int{1,2,3}[2:1]
536 /* operators > slice */
538 // _NonSliceableOperand occurs when a slice operation is applied to a value
539 // whose type is not sliceable, or is unaddressable.
542 // var x = [...]int{1, 2, 3}[:1]
549 // _InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
550 // applied to a string.
559 // _InvalidShiftCount occurs when the right-hand side of a shift operation is
560 // either non-integer, negative, or too large.
569 // _InvalidShiftOperand occurs when the shifted operand is not an integer.
578 // _InvalidReceive occurs when there is a channel receive from a value that
579 // is either not a channel, or is a send-only channel.
588 // _InvalidSend occurs when there is a channel send to a value that is not a
589 // channel, or is a receive-only channel.
598 /* exprs > literal */
600 // _DuplicateLitKey occurs when an index is duplicated in a slice, array, or
604 // var _ = []int{0:1, 0:2}
607 // var _ = map[string]int{"a": 1, "a": 2}
610 // _MissingLitKey occurs when a map literal is missing a key expression.
613 // var _ = map[string]int{1}
616 // _InvalidLitIndex occurs when the key in a key-value element of a slice or
617 // array literal is not an integer constant.
621 // var x = []string{i: "world"}
624 // _OversizeArrayLit occurs when an array literal exceeds its length.
627 // var _ = [2]int{1,2,3}
630 // _MixedStructLit occurs when a struct literal contains a mix of positional
631 // and named elements.
634 // var _ = struct{i, j int}{i: 1, 2}
637 // _InvalidStructLit occurs when a positional struct literal has an incorrect
641 // var _ = struct{i, j int}{1,2,3}
644 // _MissingLitField occurs when a struct literal refers to a field that does
645 // not exist on the struct type.
648 // var _ = struct{i int}{j: 2}
651 // _DuplicateLitField occurs when a struct literal contains duplicated
655 // var _ = struct{i int}{i: 1, i: 2}
658 // _UnexportedLitField occurs when a positional struct literal implicitly
659 // assigns an unexported field of an imported type.
662 // _InvalidLitField occurs when a field name is not a valid identifier.
665 // var _ = struct{i int}{1: 1}
668 // _UntypedLit occurs when a composite literal omits a required type
672 // type outer struct{
673 // inner struct { i int }
676 // var _ = outer{inner: {1}}
679 // _InvalidLit occurs when a composite literal expression does not match its
689 /* exprs > selector */
691 // _AmbiguousSelector occurs when a selector is ambiguous.
694 // type E1 struct { i int }
695 // type E2 struct { i int }
696 // type T struct { E1; E2 }
702 // _UndeclaredImportedName occurs when a package-qualified identifier is
703 // undeclared by the imported package.
708 // var _ = types.NotAnActualIdentifier
709 _UndeclaredImportedName
711 // _UnexportedName occurs when a selector refers to an unexported identifier
712 // of an imported package.
717 // type _ reflect.flag
720 // _UndeclaredName occurs when an identifier is not declared in the current
727 // _MissingFieldOrMethod occurs when a selector references a field or method
728 // that does not exist.
734 _MissingFieldOrMethod
738 // _BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
742 // var _ = map[int][...]int{0: {}}
745 // _NonVariadicDotDotDot occurs when a "..." is used on the final argument to
746 // a non-variadic function.
749 // func printArgs(s []string) {
750 // for _, a := range s {
756 // s := []string{"a", "b", "c"}
759 _NonVariadicDotDotDot
761 // _MisplacedDotDotDot occurs when a "..." is used somewhere other than the
762 // final argument in a function declaration.
765 // func f(...int, int)
768 // _InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
772 // var s = []int{1, 2, 3}
776 /* exprs > built-in */
778 // _UncalledBuiltin occurs when a built-in function is used as a
779 // function-valued expression, instead of being called.
782 // "The built-in functions do not have standard Go types, so they can only
783 // appear in call expressions; they cannot be used as function values."
789 // _InvalidAppend occurs when append is called with a first argument that is
793 // var _ = append(1, 2)
796 // _InvalidCap occurs when an argument to the cap built-in function is not of
799 // See https://golang.org/ref/spec#Length_and_capacity for information on
800 // which underlying types are supported as arguments to cap and len.
807 // _InvalidClose occurs when close(...) is called with an argument that is
808 // not of channel type, or that is a receive-only channel.
817 // _InvalidCopy occurs when the arguments are not of slice type or do not
818 // have compatible type.
820 // See https://golang.org/ref/spec#Appending_and_copying_slices for more
821 // information on the type requirements for the copy built-in.
826 // y := []int64{1,2,3}
831 // _InvalidComplex occurs when the complex built-in function is called with
832 // arguments with incompatible types.
835 // var _ = complex(float32(1), float64(2))
838 // _InvalidDelete occurs when the delete built-in function is called with a
839 // first argument that is not a map.
848 // _InvalidImag occurs when the imag built-in function is called with an
849 // argument that does not have complex type.
852 // var _ = imag(int(1))
855 // _InvalidLen occurs when an argument to the len built-in function is not of
858 // See https://golang.org/ref/spec#Length_and_capacity for information on
859 // which underlying types are supported as arguments to cap and len.
866 // _SwappedMakeArgs occurs when make is called with three arguments, and its
867 // length argument is larger than its capacity argument.
870 // var x = make([]int, 3, 2)
873 // _InvalidMake occurs when make is called with an unsupported type argument.
875 // See https://golang.org/ref/spec#Making_slices_maps_and_channels for
876 // information on the types that may be created using make.
882 // _InvalidReal occurs when the real built-in function is called with an
883 // argument that does not have complex type.
886 // var _ = real(int(1))
889 /* exprs > assertion */
891 // _InvalidAssert occurs when a type assertion is applied to a
892 // value that is not of interface type.
896 // var _ = x.(float64)
899 // _ImpossibleAssert occurs for a type assertion x.(T) when the value x of
900 // interface cannot have dynamic type T, due to a missing or mismatching
906 // func (t *T) m() int { return int(*t) }
908 // type I interface { m() int }
914 /* exprs > conversion */
916 // _InvalidConversion occurs when the argument type cannot be converted to the
919 // See https://golang.org/ref/spec#Conversions for the rules of
927 // _InvalidUntypedConversion occurs when an there is no valid implicit
928 // conversion from an untyped value satisfying the type constraints of the
929 // context in which it is used.
933 _InvalidUntypedConversion
937 // _BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
938 // that is not a selector expression.
944 // var _ = unsafe.Offsetof(x)
947 // _InvalidOffsetof occurs when unsafe.Offsetof is called with a method
948 // selector, rather than a field selector, or when the field is embedded via
953 // "If f is an embedded field, it must be reachable without pointer
954 // indirections through fields of the struct. "
959 // type T struct { f int }
960 // type S struct { *T }
962 // var _ = unsafe.Offsetof(s.f)
972 // var _ = unsafe.Offsetof(s.m)
975 /* control flow > scope */
977 // _UnusedExpr occurs when a side-effect free expression is used as a
978 // statement. Such a statement has no effect.
986 // _UnusedVar occurs when a variable is declared but unused.
994 // _MissingReturn occurs when a function with results is missing a return
1001 // _WrongResultCount occurs when a return statement returns an incorrect
1002 // number of values.
1005 // func ReturnOne() int {
1010 // _OutOfScopeResult occurs when the name of a value implicitly returned by
1011 // an empty return statement is shadowed in a nested scope.
1014 // func factor(n int) (i int) {
1015 // for i := 2; i < n; i++ {
1024 /* control flow > if */
1026 // _InvalidCond occurs when an if condition is not a boolean expression.
1029 // func checkReturn(i int) {
1031 // panic("non-zero return")
1036 /* control flow > for */
1038 // _InvalidPostDecl occurs when there is a declaration in a for-loop post
1043 // for i := 0; i < 10; j := 0 {}
1047 // _InvalidIterVar occurs when two iteration variables are used while ranging
1051 // func f(c chan int) {
1052 // for k, v := range c {
1058 // _InvalidRangeExpr occurs when the type of a range expression is not array,
1059 // slice, string, map, or channel.
1063 // for j := range i {
1069 /* control flow > switch */
1071 // _MisplacedBreak occurs when a break statement is not within a for, switch,
1072 // or select statement of the innermost function definition.
1080 // _MisplacedContinue occurs when a continue statement is not within a for
1081 // loop of the innermost function definition.
1084 // func sumeven(n int) int {
1085 // proceed := func() {
1089 // for i := 1; i <= n; i++ {
1099 // _MisplacedFallthrough occurs when a fallthrough statement is not within an
1100 // expression switch.
1103 // func typename(i interface{}) string {
1104 // switch i.(type) {
1110 // return "unsupported"
1112 _MisplacedFallthrough
1114 // _DuplicateCase occurs when a type or expression switch has duplicate
1118 // func printInt(i int) {
1128 // _DuplicateDefault occurs when a type or expression switch has multiple
1132 // func printInt(i int) {
1144 // _BadTypeKeyword occurs when a .(type) expression is used anywhere other
1145 // than a type switch.
1148 // type I interface {
1155 // _InvalidTypeSwitch occurs when .(type) is used on an expression that is
1156 // not of interface type.
1160 // switch x := i.(type) {}
1164 // _InvalidExprSwitch occurs when a switch expression is not comparable.
1168 // var a struct{ _ func() }
1169 // switch a /* ERROR cannot switch on a */ {
1174 /* control flow > select */
1176 // _InvalidSelectCase occurs when a select case is not a channel send or
1180 // func checkChan(c <-chan int) bool {
1190 /* control flow > labels and jumps */
1192 // _UndeclaredLabel occurs when an undeclared label is jumped to.
1200 // _DuplicateLabel occurs when a label is declared more than once.
1210 // _MisplacedLabel occurs when a break or continue label is not on a for,
1211 // switch, or select statement.
1216 // a := []int{1,2,3}
1217 // for _, e := range a {
1226 // _UnusedLabel occurs when a label is declared but not used.
1234 // _JumpOverDecl occurs when a label jumps over a variable declaration.
1246 // _JumpIntoBlock occurs when a forward jump goes to a label inside a nested
1254 // print("inside block")
1259 /* control flow > calls */
1261 // _InvalidMethodExpr occurs when a pointer method is called but the argument
1262 // is not addressable.
1267 // func (*T) m() int { return 1 }
1272 // _WrongArgCount occurs when too few or too many arguments are passed by a
1280 // _InvalidCall occurs when an expression is called that is not of function
1288 /* control flow > suspended */
1290 // _UnusedResults occurs when a restricted expression-only built-in function
1291 // is suspended via go or defer. Such a suspension discards the results of
1292 // these side-effect free built-in functions, and therefore is ineffectual.
1295 // func f(a []int) int {
1301 // _InvalidDefer occurs when a deferred expression is not a function call,
1302 // for example if the expression is a type conversion.
1305 // func f(i int) int {
1311 // _InvalidGo occurs when a go expression is not a function call, for example
1312 // if the expression is a type conversion.
1315 // func f(i int) int {
1321 // _BadDecl occurs when a declaration has invalid syntax.
1324 // _Todo is a placeholder for error codes that have not been decided.
1325 // TODO(rFindley) remove this error code after deciding on errors for generics code.