]> git.lizzy.rs Git - rust.git/blob - src/librustc/error_codes.rs
Auto merge of #64025 - Wind-River:master_003, r=alexcrichton
[rust.git] / src / librustc / error_codes.rs
1 // Error messages for EXXXX errors.
2 // Each message should start and end with a new line, and be wrapped to 80 characters.
3 // In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
4 register_long_diagnostics! {
5 E0038: r##"
6 Trait objects like `Box<Trait>` can only be constructed when certain
7 requirements are satisfied by the trait in question.
8
9 Trait objects are a form of dynamic dispatch and use a dynamically sized type
10 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
11 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
12 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
13 (among other things) for dynamic dispatch. This design mandates some
14 restrictions on the types of traits that are allowed to be used in trait
15 objects, which are collectively termed as 'object safety' rules.
16
17 Attempting to create a trait object for a non object-safe trait will trigger
18 this error.
19
20 There are various rules:
21
22 ### The trait cannot require `Self: Sized`
23
24 When `Trait` is treated as a type, the type does not implement the special
25 `Sized` trait, because the type does not have a known size at compile time and
26 can only be accessed behind a pointer. Thus, if we have a trait like the
27 following:
28
29 ```
30 trait Foo where Self: Sized {
31
32 }
33 ```
34
35 We cannot create an object of type `Box<Foo>` or `&Foo` since in this case
36 `Self` would not be `Sized`.
37
38 Generally, `Self: Sized` is used to indicate that the trait should not be used
39 as a trait object. If the trait comes from your own crate, consider removing
40 this restriction.
41
42 ### Method references the `Self` type in its arguments or return type
43
44 This happens when a trait has a method like the following:
45
46 ```
47 trait Trait {
48     fn foo(&self) -> Self;
49 }
50
51 impl Trait for String {
52     fn foo(&self) -> Self {
53         "hi".to_owned()
54     }
55 }
56
57 impl Trait for u8 {
58     fn foo(&self) -> Self {
59         1
60     }
61 }
62 ```
63
64 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
65 cause this problem.)
66
67 In such a case, the compiler cannot predict the return type of `foo()` in a
68 situation like the following:
69
70 ```compile_fail
71 trait Trait {
72     fn foo(&self) -> Self;
73 }
74
75 fn call_foo(x: Box<Trait>) {
76     let y = x.foo(); // What type is y?
77     // ...
78 }
79 ```
80
81 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
82 on them to mark them as explicitly unavailable to trait objects. The
83 functionality will still be available to all other implementers, including
84 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
85
86 ```
87 trait Trait {
88     fn foo(&self) -> Self where Self: Sized;
89     // more functions
90 }
91 ```
92
93 Now, `foo()` can no longer be called on a trait object, but you will now be
94 allowed to make a trait object, and that will be able to call any object-safe
95 methods. With such a bound, one can still call `foo()` on types implementing
96 that trait that aren't behind trait objects.
97
98 ### Method has generic type parameters
99
100 As mentioned before, trait objects contain pointers to method tables. So, if we
101 have:
102
103 ```
104 trait Trait {
105     fn foo(&self);
106 }
107
108 impl Trait for String {
109     fn foo(&self) {
110         // implementation 1
111     }
112 }
113
114 impl Trait for u8 {
115     fn foo(&self) {
116         // implementation 2
117     }
118 }
119 // ...
120 ```
121
122 At compile time each implementation of `Trait` will produce a table containing
123 the various methods (and other items) related to the implementation.
124
125 This works fine, but when the method gains generic parameters, we can have a
126 problem.
127
128 Usually, generic parameters get _monomorphized_. For example, if I have
129
130 ```
131 fn foo<T>(x: T) {
132     // ...
133 }
134 ```
135
136 The machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
137 other type substitution is different. Hence the compiler generates the
138 implementation on-demand. If you call `foo()` with a `bool` parameter, the
139 compiler will only generate code for `foo::<bool>()`. When we have additional
140 type parameters, the number of monomorphized implementations the compiler
141 generates does not grow drastically, since the compiler will only generate an
142 implementation if the function is called with unparametrized substitutions
143 (i.e., substitutions where none of the substituted types are themselves
144 parametrized).
145
146 However, with trait objects we have to make a table containing _every_ object
147 that implements the trait. Now, if it has type parameters, we need to add
148 implementations for every type that implements the trait, and there could
149 theoretically be an infinite number of types.
150
151 For example, with:
152
153 ```
154 trait Trait {
155     fn foo<T>(&self, on: T);
156     // more methods
157 }
158
159 impl Trait for String {
160     fn foo<T>(&self, on: T) {
161         // implementation 1
162     }
163 }
164
165 impl Trait for u8 {
166     fn foo<T>(&self, on: T) {
167         // implementation 2
168     }
169 }
170
171 // 8 more implementations
172 ```
173
174 Now, if we have the following code:
175
176 ```compile_fail,E0038
177 # trait Trait { fn foo<T>(&self, on: T); }
178 # impl Trait for String { fn foo<T>(&self, on: T) {} }
179 # impl Trait for u8 { fn foo<T>(&self, on: T) {} }
180 # impl Trait for bool { fn foo<T>(&self, on: T) {} }
181 # // etc.
182 fn call_foo(thing: Box<Trait>) {
183     thing.foo(true); // this could be any one of the 8 types above
184     thing.foo(1);
185     thing.foo("hello");
186 }
187 ```
188
189 We don't just need to create a table of all implementations of all methods of
190 `Trait`, we need to create such a table, for each different type fed to
191 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
192 types being fed to `foo()`) = 30 implementations!
193
194 With real world traits these numbers can grow drastically.
195
196 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
197 fix for the sub-error above if you do not intend to call the method with type
198 parameters:
199
200 ```
201 trait Trait {
202     fn foo<T>(&self, on: T) where Self: Sized;
203     // more methods
204 }
205 ```
206
207 If this is not an option, consider replacing the type parameter with another
208 trait object (e.g., if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the
209 number of types you intend to feed to this method is limited, consider manually
210 listing out the methods of different types.
211
212 ### Method has no receiver
213
214 Methods that do not take a `self` parameter can't be called since there won't be
215 a way to get a pointer to the method table for them.
216
217 ```
218 trait Foo {
219     fn foo() -> u8;
220 }
221 ```
222
223 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
224 an implementation.
225
226 Adding a `Self: Sized` bound to these methods will generally make this compile.
227
228 ```
229 trait Foo {
230     fn foo() -> u8 where Self: Sized;
231 }
232 ```
233
234 ### The trait cannot contain associated constants
235
236 Just like static functions, associated constants aren't stored on the method
237 table. If the trait or any subtrait contain an associated constant, they cannot
238 be made into an object.
239
240 ```compile_fail,E0038
241 trait Foo {
242     const X: i32;
243 }
244
245 impl Foo {}
246 ```
247
248 A simple workaround is to use a helper method instead:
249
250 ```
251 trait Foo {
252     fn x(&self) -> i32;
253 }
254 ```
255
256 ### The trait cannot use `Self` as a type parameter in the supertrait listing
257
258 This is similar to the second sub-error, but subtler. It happens in situations
259 like the following:
260
261 ```compile_fail
262 trait Super<A> {}
263
264 trait Trait: Super<Self> {
265 }
266
267 struct Foo;
268
269 impl Super<Foo> for Foo{}
270
271 impl Trait for Foo {}
272 ```
273
274 Here, the supertrait might have methods as follows:
275
276 ```
277 trait Super<A> {
278     fn get_a(&self) -> A; // note that this is object safe!
279 }
280 ```
281
282 If the trait `Foo` was deriving from something like `Super<String>` or
283 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
284 `get_a()` will definitely return an object of that type.
285
286 However, if it derives from `Super<Self>`, even though `Super` is object safe,
287 the method `get_a()` would return an object of unknown type when called on the
288 function. `Self` type parameters let us make object safe traits no longer safe,
289 so they are forbidden when specifying supertraits.
290
291 There's no easy fix for this, generally code will need to be refactored so that
292 you no longer need to derive from `Super<Self>`.
293 "##,
294
295 E0072: r##"
296 When defining a recursive struct or enum, any use of the type being defined
297 from inside the definition must occur behind a pointer (like `Box` or `&`).
298 This is because structs and enums must have a well-defined size, and without
299 the pointer, the size of the type would need to be unbounded.
300
301 Consider the following erroneous definition of a type for a list of bytes:
302
303 ```compile_fail,E0072
304 // error, invalid recursive struct type
305 struct ListNode {
306     head: u8,
307     tail: Option<ListNode>,
308 }
309 ```
310
311 This type cannot have a well-defined size, because it needs to be arbitrarily
312 large (since we would be able to nest `ListNode`s to any depth). Specifically,
313
314 ```plain
315 size of `ListNode` = 1 byte for `head`
316                    + 1 byte for the discriminant of the `Option`
317                    + size of `ListNode`
318 ```
319
320 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
321
322 ```
323 struct ListNode {
324     head: u8,
325     tail: Option<Box<ListNode>>,
326 }
327 ```
328
329 This works because `Box` is a pointer, so its size is well-known.
330 "##,
331
332 E0080: r##"
333 This error indicates that the compiler was unable to sensibly evaluate an
334 constant expression that had to be evaluated. Attempting to divide by 0
335 or causing integer overflow are two ways to induce this error. For example:
336
337 ```compile_fail,E0080
338 enum Enum {
339     X = (1 << 500),
340     Y = (1 / 0)
341 }
342 ```
343
344 Ensure that the expressions given can be evaluated as the desired integer type.
345 See the FFI section of the Reference for more information about using a custom
346 integer type:
347
348 https://doc.rust-lang.org/reference.html#ffi-attributes
349 "##,
350
351 E0106: r##"
352 This error indicates that a lifetime is missing from a type. If it is an error
353 inside a function signature, the problem may be with failing to adhere to the
354 lifetime elision rules (see below).
355
356 Here are some simple examples of where you'll run into this error:
357
358 ```compile_fail,E0106
359 struct Foo1 { x: &bool }
360               // ^ expected lifetime parameter
361 struct Foo2<'a> { x: &'a bool } // correct
362
363 struct Bar1 { x: Foo2 }
364               // ^^^^ expected lifetime parameter
365 struct Bar2<'a> { x: Foo2<'a> } // correct
366
367 enum Baz1 { A(u8), B(&bool), }
368                   // ^ expected lifetime parameter
369 enum Baz2<'a> { A(u8), B(&'a bool), } // correct
370
371 type MyStr1 = &str;
372            // ^ expected lifetime parameter
373 type MyStr2<'a> = &'a str; // correct
374 ```
375
376 Lifetime elision is a special, limited kind of inference for lifetimes in
377 function signatures which allows you to leave out lifetimes in certain cases.
378 For more background on lifetime elision see [the book][book-le].
379
380 The lifetime elision rules require that any function signature with an elided
381 output lifetime must either have
382
383  - exactly one input lifetime
384  - or, multiple input lifetimes, but the function must also be a method with a
385    `&self` or `&mut self` receiver
386
387 In the first case, the output lifetime is inferred to be the same as the unique
388 input lifetime. In the second case, the lifetime is instead inferred to be the
389 same as the lifetime on `&self` or `&mut self`.
390
391 Here are some examples of elision errors:
392
393 ```compile_fail,E0106
394 // error, no input lifetimes
395 fn foo() -> &str { }
396
397 // error, `x` and `y` have distinct lifetimes inferred
398 fn bar(x: &str, y: &str) -> &str { }
399
400 // error, `y`'s lifetime is inferred to be distinct from `x`'s
401 fn baz<'a>(x: &'a str, y: &str) -> &str { }
402 ```
403
404 [book-le]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision
405 "##,
406
407 E0119: r##"
408 There are conflicting trait implementations for the same type.
409 Example of erroneous code:
410
411 ```compile_fail,E0119
412 trait MyTrait {
413     fn get(&self) -> usize;
414 }
415
416 impl<T> MyTrait for T {
417     fn get(&self) -> usize { 0 }
418 }
419
420 struct Foo {
421     value: usize
422 }
423
424 impl MyTrait for Foo { // error: conflicting implementations of trait
425                        //        `MyTrait` for type `Foo`
426     fn get(&self) -> usize { self.value }
427 }
428 ```
429
430 When looking for the implementation for the trait, the compiler finds
431 both the `impl<T> MyTrait for T` where T is all types and the `impl
432 MyTrait for Foo`. Since a trait cannot be implemented multiple times,
433 this is an error. So, when you write:
434
435 ```
436 trait MyTrait {
437     fn get(&self) -> usize;
438 }
439
440 impl<T> MyTrait for T {
441     fn get(&self) -> usize { 0 }
442 }
443 ```
444
445 This makes the trait implemented on all types in the scope. So if you
446 try to implement it on another one after that, the implementations will
447 conflict. Example:
448
449 ```
450 trait MyTrait {
451     fn get(&self) -> usize;
452 }
453
454 impl<T> MyTrait for T {
455     fn get(&self) -> usize { 0 }
456 }
457
458 struct Foo;
459
460 fn main() {
461     let f = Foo;
462
463     f.get(); // the trait is implemented so we can use it
464 }
465 ```
466 "##,
467
468 // This shouldn't really ever trigger since the repeated value error comes first
469 E0136: r##"
470 A binary can only have one entry point, and by default that entry point is the
471 function `main()`. If there are multiple such functions, please rename one.
472 "##,
473
474 E0137: r##"
475 More than one function was declared with the `#[main]` attribute.
476
477 Erroneous code example:
478
479 ```compile_fail,E0137
480 #![feature(main)]
481
482 #[main]
483 fn foo() {}
484
485 #[main]
486 fn f() {} // error: multiple functions with a `#[main]` attribute
487 ```
488
489 This error indicates that the compiler found multiple functions with the
490 `#[main]` attribute. This is an error because there must be a unique entry
491 point into a Rust program. Example:
492
493 ```
494 #![feature(main)]
495
496 #[main]
497 fn f() {} // ok!
498 ```
499 "##,
500
501 E0138: r##"
502 More than one function was declared with the `#[start]` attribute.
503
504 Erroneous code example:
505
506 ```compile_fail,E0138
507 #![feature(start)]
508
509 #[start]
510 fn foo(argc: isize, argv: *const *const u8) -> isize {}
511
512 #[start]
513 fn f(argc: isize, argv: *const *const u8) -> isize {}
514 // error: multiple 'start' functions
515 ```
516
517 This error indicates that the compiler found multiple functions with the
518 `#[start]` attribute. This is an error because there must be a unique entry
519 point into a Rust program. Example:
520
521 ```
522 #![feature(start)]
523
524 #[start]
525 fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
526 ```
527 "##,
528
529 E0139: r##"
530 #### Note: this error code is no longer emitted by the compiler.
531
532 There are various restrictions on transmuting between types in Rust; for example
533 types being transmuted must have the same size. To apply all these restrictions,
534 the compiler must know the exact types that may be transmuted. When type
535 parameters are involved, this cannot always be done.
536
537 So, for example, the following is not allowed:
538
539 ```
540 use std::mem::transmute;
541
542 struct Foo<T>(Vec<T>);
543
544 fn foo<T>(x: Vec<T>) {
545     // we are transmuting between Vec<T> and Foo<F> here
546     let y: Foo<T> = unsafe { transmute(x) };
547     // do something with y
548 }
549 ```
550
551 In this specific case there's a good chance that the transmute is harmless (but
552 this is not guaranteed by Rust). However, when alignment and enum optimizations
553 come into the picture, it's quite likely that the sizes may or may not match
554 with different type parameter substitutions. It's not possible to check this for
555 _all_ possible types, so `transmute()` simply only accepts types without any
556 unsubstituted type parameters.
557
558 If you need this, there's a good chance you're doing something wrong. Keep in
559 mind that Rust doesn't guarantee much about the layout of different structs
560 (even two structs with identical declarations may have different layouts). If
561 there is a solution that avoids the transmute entirely, try it instead.
562
563 If it's possible, hand-monomorphize the code by writing the function for each
564 possible type substitution. It's possible to use traits to do this cleanly,
565 for example:
566
567 ```
568 use std::mem::transmute;
569
570 struct Foo<T>(Vec<T>);
571
572 trait MyTransmutableType: Sized {
573     fn transmute(_: Vec<Self>) -> Foo<Self>;
574 }
575
576 impl MyTransmutableType for u8 {
577     fn transmute(x: Vec<u8>) -> Foo<u8> {
578         unsafe { transmute(x) }
579     }
580 }
581
582 impl MyTransmutableType for String {
583     fn transmute(x: Vec<String>) -> Foo<String> {
584         unsafe { transmute(x) }
585     }
586 }
587
588 // ... more impls for the types you intend to transmute
589
590 fn foo<T: MyTransmutableType>(x: Vec<T>) {
591     let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
592     // do something with y
593 }
594 ```
595
596 Each impl will be checked for a size match in the transmute as usual, and since
597 there are no unbound type parameters involved, this should compile unless there
598 is a size mismatch in one of the impls.
599
600 It is also possible to manually transmute:
601
602 ```
603 # use std::ptr;
604 # let v = Some("value");
605 # type SomeType = &'static [u8];
606 unsafe {
607     ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
608 }
609 # ;
610 ```
611
612 Note that this does not move `v` (unlike `transmute`), and may need a
613 call to `mem::forget(v)` in case you want to avoid destructors being called.
614 "##,
615
616 E0152: r##"
617 A lang item was redefined.
618
619 Erroneous code example:
620
621 ```compile_fail,E0152
622 #![feature(lang_items)]
623
624 #[lang = "arc"]
625 struct Foo; // error: duplicate lang item found: `arc`
626 ```
627
628 Lang items are already implemented in the standard library. Unless you are
629 writing a free-standing application (e.g., a kernel), you do not need to provide
630 them yourself.
631
632 You can build a free-standing crate by adding `#![no_std]` to the crate
633 attributes:
634
635 ```ignore (only-for-syntax-highlight)
636 #![no_std]
637 ```
638
639 See also the [unstable book][1].
640
641 [1]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib
642 "##,
643
644 E0214: r##"
645 A generic type was described using parentheses rather than angle brackets.
646 For example:
647
648 ```compile_fail,E0214
649 fn main() {
650     let v: Vec(&str) = vec!["foo"];
651 }
652 ```
653
654 This is not currently supported: `v` should be defined as `Vec<&str>`.
655 Parentheses are currently only used with generic types when defining parameters
656 for `Fn`-family traits.
657 "##,
658
659 E0230: r##"
660 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
661 message for when a particular trait isn't implemented on a type placed in a
662 position that needs that trait. For example, when the following code is
663 compiled:
664
665 ```compile_fail
666 #![feature(on_unimplemented)]
667
668 fn foo<T: Index<u8>>(x: T){}
669
670 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
671 trait Index<Idx> { /* ... */ }
672
673 foo(true); // `bool` does not implement `Index<u8>`
674 ```
675
676 There will be an error about `bool` not implementing `Index<u8>`, followed by a
677 note saying "the type `bool` cannot be indexed by `u8`".
678
679 As you can see, you can specify type parameters in curly braces for
680 substitution with the actual types (using the regular format string syntax) in
681 a given situation. Furthermore, `{Self}` will substitute to the type (in this
682 case, `bool`) that we tried to use.
683
684 This error appears when the curly braces contain an identifier which doesn't
685 match with any of the type parameters or the string `Self`. This might happen
686 if you misspelled a type parameter, or if you intended to use literal curly
687 braces. If it is the latter, escape the curly braces with a second curly brace
688 of the same type; e.g., a literal `{` is `{{`.
689 "##,
690
691 E0231: r##"
692 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
693 message for when a particular trait isn't implemented on a type placed in a
694 position that needs that trait. For example, when the following code is
695 compiled:
696
697 ```compile_fail
698 #![feature(on_unimplemented)]
699
700 fn foo<T: Index<u8>>(x: T){}
701
702 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
703 trait Index<Idx> { /* ... */ }
704
705 foo(true); // `bool` does not implement `Index<u8>`
706 ```
707
708 there will be an error about `bool` not implementing `Index<u8>`, followed by a
709 note saying "the type `bool` cannot be indexed by `u8`".
710
711 As you can see, you can specify type parameters in curly braces for
712 substitution with the actual types (using the regular format string syntax) in
713 a given situation. Furthermore, `{Self}` will substitute to the type (in this
714 case, `bool`) that we tried to use.
715
716 This error appears when the curly braces do not contain an identifier. Please
717 add one of the same name as a type parameter. If you intended to use literal
718 braces, use `{{` and `}}` to escape them.
719 "##,
720
721 E0232: r##"
722 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
723 message for when a particular trait isn't implemented on a type placed in a
724 position that needs that trait. For example, when the following code is
725 compiled:
726
727 ```compile_fail
728 #![feature(on_unimplemented)]
729
730 fn foo<T: Index<u8>>(x: T){}
731
732 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
733 trait Index<Idx> { /* ... */ }
734
735 foo(true); // `bool` does not implement `Index<u8>`
736 ```
737
738 there will be an error about `bool` not implementing `Index<u8>`, followed by a
739 note saying "the type `bool` cannot be indexed by `u8`".
740
741 For this to work, some note must be specified. An empty attribute will not do
742 anything, please remove the attribute or add some helpful note for users of the
743 trait.
744 "##,
745
746 E0261: r##"
747 When using a lifetime like `'a` in a type, it must be declared before being
748 used.
749
750 These two examples illustrate the problem:
751
752 ```compile_fail,E0261
753 // error, use of undeclared lifetime name `'a`
754 fn foo(x: &'a str) { }
755
756 struct Foo {
757     // error, use of undeclared lifetime name `'a`
758     x: &'a str,
759 }
760 ```
761
762 These can be fixed by declaring lifetime parameters:
763
764 ```
765 struct Foo<'a> {
766     x: &'a str,
767 }
768
769 fn foo<'a>(x: &'a str) {}
770 ```
771
772 Impl blocks declare lifetime parameters separately. You need to add lifetime
773 parameters to an impl block if you're implementing a type that has a lifetime
774 parameter of its own.
775 For example:
776
777 ```compile_fail,E0261
778 struct Foo<'a> {
779     x: &'a str,
780 }
781
782 // error,  use of undeclared lifetime name `'a`
783 impl Foo<'a> {
784     fn foo<'a>(x: &'a str) {}
785 }
786 ```
787
788 This is fixed by declaring the impl block like this:
789
790 ```
791 struct Foo<'a> {
792     x: &'a str,
793 }
794
795 // correct
796 impl<'a> Foo<'a> {
797     fn foo(x: &'a str) {}
798 }
799 ```
800 "##,
801
802 E0262: r##"
803 Declaring certain lifetime names in parameters is disallowed. For example,
804 because the `'static` lifetime is a special built-in lifetime name denoting
805 the lifetime of the entire program, this is an error:
806
807 ```compile_fail,E0262
808 // error, invalid lifetime parameter name `'static`
809 fn foo<'static>(x: &'static str) { }
810 ```
811 "##,
812
813 E0263: r##"
814 A lifetime name cannot be declared more than once in the same scope. For
815 example:
816
817 ```compile_fail,E0263
818 // error, lifetime name `'a` declared twice in the same scope
819 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
820 ```
821 "##,
822
823 E0264: r##"
824 An unknown external lang item was used. Erroneous code example:
825
826 ```compile_fail,E0264
827 #![feature(lang_items)]
828
829 extern "C" {
830     #[lang = "cake"] // error: unknown external lang item: `cake`
831     fn cake();
832 }
833 ```
834
835 A list of available external lang items is available in
836 `src/librustc/middle/weak_lang_items.rs`. Example:
837
838 ```
839 #![feature(lang_items)]
840
841 extern "C" {
842     #[lang = "panic_impl"] // ok!
843     fn cake();
844 }
845 ```
846 "##,
847
848 E0271: r##"
849 This is because of a type mismatch between the associated type of some
850 trait (e.g., `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
851 and another type `U` that is required to be equal to `T::Bar`, but is not.
852 Examples follow.
853
854 Here is a basic example:
855
856 ```compile_fail,E0271
857 trait Trait { type AssociatedType; }
858
859 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
860     println!("in foo");
861 }
862
863 impl Trait for i8 { type AssociatedType = &'static str; }
864
865 foo(3_i8);
866 ```
867
868 Here is that same example again, with some explanatory comments:
869
870 ```compile_fail,E0271
871 trait Trait { type AssociatedType; }
872
873 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
874 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
875 //                        |            |
876 //         This says `foo` can         |
877 //           only be used with         |
878 //              some type that         |
879 //         implements `Trait`.         |
880 //                                     |
881 //                             This says not only must
882 //                             `T` be an impl of `Trait`
883 //                             but also that the impl
884 //                             must assign the type `u32`
885 //                             to the associated type.
886     println!("in foo");
887 }
888
889 impl Trait for i8 { type AssociatedType = &'static str; }
890 //~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
891 //      |                             |
892 // `i8` does have                     |
893 // implementation                     |
894 // of `Trait`...                      |
895 //                     ... but it is an implementation
896 //                     that assigns `&'static str` to
897 //                     the associated type.
898
899 foo(3_i8);
900 // Here, we invoke `foo` with an `i8`, which does not satisfy
901 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
902 // therefore the type-checker complains with this error code.
903 ```
904
905 To avoid those issues, you have to make the types match correctly.
906 So we can fix the previous examples like this:
907
908 ```
909 // Basic Example:
910 trait Trait { type AssociatedType; }
911
912 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
913     println!("in foo");
914 }
915
916 impl Trait for i8 { type AssociatedType = &'static str; }
917
918 foo(3_i8);
919
920 // For-Loop Example:
921 let vs = vec![1, 2, 3, 4];
922 for v in &vs {
923     match v {
924         &1 => {}
925         _ => {}
926     }
927 }
928 ```
929 "##,
930
931
932 E0275: r##"
933 This error occurs when there was a recursive trait requirement that overflowed
934 before it could be evaluated. Often this means that there is unbounded
935 recursion in resolving some type bounds.
936
937 For example, in the following code:
938
939 ```compile_fail,E0275
940 trait Foo {}
941
942 struct Bar<T>(T);
943
944 impl<T> Foo for T where Bar<T>: Foo {}
945 ```
946
947 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
948 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
949 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
950 clearly a recursive requirement that can't be resolved directly.
951
952 Consider changing your trait bounds so that they're less self-referential.
953 "##,
954
955 E0276: r##"
956 This error occurs when a bound in an implementation of a trait does not match
957 the bounds specified in the original trait. For example:
958
959 ```compile_fail,E0276
960 trait Foo {
961     fn foo<T>(x: T);
962 }
963
964 impl Foo for bool {
965     fn foo<T>(x: T) where T: Copy {}
966 }
967 ```
968
969 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
970 take any type `T`. However, in the `impl` for `bool`, we have added an extra
971 bound that `T` is `Copy`, which isn't compatible with the original trait.
972
973 Consider removing the bound from the method or adding the bound to the original
974 method definition in the trait.
975 "##,
976
977 E0277: r##"
978 You tried to use a type which doesn't implement some trait in a place which
979 expected that trait. Erroneous code example:
980
981 ```compile_fail,E0277
982 // here we declare the Foo trait with a bar method
983 trait Foo {
984     fn bar(&self);
985 }
986
987 // we now declare a function which takes an object implementing the Foo trait
988 fn some_func<T: Foo>(foo: T) {
989     foo.bar();
990 }
991
992 fn main() {
993     // we now call the method with the i32 type, which doesn't implement
994     // the Foo trait
995     some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
996 }
997 ```
998
999 In order to fix this error, verify that the type you're using does implement
1000 the trait. Example:
1001
1002 ```
1003 trait Foo {
1004     fn bar(&self);
1005 }
1006
1007 fn some_func<T: Foo>(foo: T) {
1008     foo.bar(); // we can now use this method since i32 implements the
1009                // Foo trait
1010 }
1011
1012 // we implement the trait on the i32 type
1013 impl Foo for i32 {
1014     fn bar(&self) {}
1015 }
1016
1017 fn main() {
1018     some_func(5i32); // ok!
1019 }
1020 ```
1021
1022 Or in a generic context, an erroneous code example would look like:
1023
1024 ```compile_fail,E0277
1025 fn some_func<T>(foo: T) {
1026     println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1027                            //        implemented for the type `T`
1028 }
1029
1030 fn main() {
1031     // We now call the method with the i32 type,
1032     // which *does* implement the Debug trait.
1033     some_func(5i32);
1034 }
1035 ```
1036
1037 Note that the error here is in the definition of the generic function: Although
1038 we only call it with a parameter that does implement `Debug`, the compiler
1039 still rejects the function: It must work with all possible input types. In
1040 order to make this example compile, we need to restrict the generic type we're
1041 accepting:
1042
1043 ```
1044 use std::fmt;
1045
1046 // Restrict the input type to types that implement Debug.
1047 fn some_func<T: fmt::Debug>(foo: T) {
1048     println!("{:?}", foo);
1049 }
1050
1051 fn main() {
1052     // Calling the method is still fine, as i32 implements Debug.
1053     some_func(5i32);
1054
1055     // This would fail to compile now:
1056     // struct WithoutDebug;
1057     // some_func(WithoutDebug);
1058 }
1059 ```
1060
1061 Rust only looks at the signature of the called function, as such it must
1062 already specify all requirements that will be used for every type parameter.
1063 "##,
1064
1065 E0281: r##"
1066 #### Note: this error code is no longer emitted by the compiler.
1067
1068 You tried to supply a type which doesn't implement some trait in a location
1069 which expected that trait. This error typically occurs when working with
1070 `Fn`-based types. Erroneous code example:
1071
1072 ```compile-fail
1073 fn foo<F: Fn(usize)>(x: F) { }
1074
1075 fn main() {
1076     // type mismatch: ... implements the trait `core::ops::Fn<(String,)>`,
1077     // but the trait `core::ops::Fn<(usize,)>` is required
1078     // [E0281]
1079     foo(|y: String| { });
1080 }
1081 ```
1082
1083 The issue in this case is that `foo` is defined as accepting a `Fn` with one
1084 argument of type `String`, but the closure we attempted to pass to it requires
1085 one arguments of type `usize`.
1086 "##,
1087
1088 E0282: r##"
1089 This error indicates that type inference did not result in one unique possible
1090 type, and extra information is required. In most cases this can be provided
1091 by adding a type annotation. Sometimes you need to specify a generic type
1092 parameter manually.
1093
1094 A common example is the `collect` method on `Iterator`. It has a generic type
1095 parameter with a `FromIterator` bound, which for a `char` iterator is
1096 implemented by `Vec` and `String` among others. Consider the following snippet
1097 that reverses the characters of a string:
1098
1099 ```compile_fail,E0282
1100 let x = "hello".chars().rev().collect();
1101 ```
1102
1103 In this case, the compiler cannot infer what the type of `x` should be:
1104 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1105 use, you can use a type annotation on `x`:
1106
1107 ```
1108 let x: Vec<char> = "hello".chars().rev().collect();
1109 ```
1110
1111 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1112 the compiler can infer the rest:
1113
1114 ```
1115 let x: Vec<_> = "hello".chars().rev().collect();
1116 ```
1117
1118 Another way to provide the compiler with enough information, is to specify the
1119 generic type parameter:
1120
1121 ```
1122 let x = "hello".chars().rev().collect::<Vec<char>>();
1123 ```
1124
1125 Again, you need not specify the full type if the compiler can infer it:
1126
1127 ```
1128 let x = "hello".chars().rev().collect::<Vec<_>>();
1129 ```
1130
1131 Apart from a method or function with a generic type parameter, this error can
1132 occur when a type parameter of a struct or trait cannot be inferred. In that
1133 case it is not always possible to use a type annotation, because all candidates
1134 have the same return type. For instance:
1135
1136 ```compile_fail,E0282
1137 struct Foo<T> {
1138     num: T,
1139 }
1140
1141 impl<T> Foo<T> {
1142     fn bar() -> i32 {
1143         0
1144     }
1145
1146     fn baz() {
1147         let number = Foo::bar();
1148     }
1149 }
1150 ```
1151
1152 This will fail because the compiler does not know which instance of `Foo` to
1153 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1154 "##,
1155
1156 E0283: r##"
1157 This error occurs when the compiler doesn't have enough information
1158 to unambiguously choose an implementation.
1159
1160 For example:
1161
1162 ```compile_fail,E0283
1163 trait Generator {
1164     fn create() -> u32;
1165 }
1166
1167 struct Impl;
1168
1169 impl Generator for Impl {
1170     fn create() -> u32 { 1 }
1171 }
1172
1173 struct AnotherImpl;
1174
1175 impl Generator for AnotherImpl {
1176     fn create() -> u32 { 2 }
1177 }
1178
1179 fn main() {
1180     let cont: u32 = Generator::create();
1181     // error, impossible to choose one of Generator trait implementation
1182     // Should it be Impl or AnotherImpl, maybe something else?
1183 }
1184 ```
1185
1186 To resolve this error use the concrete type:
1187
1188 ```
1189 trait Generator {
1190     fn create() -> u32;
1191 }
1192
1193 struct AnotherImpl;
1194
1195 impl Generator for AnotherImpl {
1196     fn create() -> u32 { 2 }
1197 }
1198
1199 fn main() {
1200     let gen1 = AnotherImpl::create();
1201
1202     // if there are multiple methods with same name (different traits)
1203     let gen2 = <AnotherImpl as Generator>::create();
1204 }
1205 ```
1206 "##,
1207
1208 E0284: r##"
1209 This error occurs when the compiler is unable to unambiguously infer the
1210 return type of a function or method which is generic on return type, such
1211 as the `collect` method for `Iterator`s.
1212
1213 For example:
1214
1215 ```compile_fail,E0284
1216 fn foo() -> Result<bool, ()> {
1217     let results = [Ok(true), Ok(false), Err(())].iter().cloned();
1218     let v: Vec<bool> = results.collect()?;
1219     // Do things with v...
1220     Ok(true)
1221 }
1222 ```
1223
1224 Here we have an iterator `results` over `Result<bool, ()>`.
1225 Hence, `results.collect()` can return any type implementing
1226 `FromIterator<Result<bool, ()>>`. On the other hand, the
1227 `?` operator can accept any type implementing `Try`.
1228
1229 The author of this code probably wants `collect()` to return a
1230 `Result<Vec<bool>, ()>`, but the compiler can't be sure
1231 that there isn't another type `T` implementing both `Try` and
1232 `FromIterator<Result<bool, ()>>` in scope such that
1233 `T::Ok == Vec<bool>`. Hence, this code is ambiguous and an error
1234 is returned.
1235
1236 To resolve this error, use a concrete type for the intermediate expression:
1237
1238 ```
1239 fn foo() -> Result<bool, ()> {
1240     let results = [Ok(true), Ok(false), Err(())].iter().cloned();
1241     let v = {
1242         let temp: Result<Vec<bool>, ()> = results.collect();
1243         temp?
1244     };
1245     // Do things with v...
1246     Ok(true)
1247 }
1248 ```
1249
1250 Note that the type of `v` can now be inferred from the type of `temp`.
1251 "##,
1252
1253 E0308: r##"
1254 This error occurs when the compiler was unable to infer the concrete type of a
1255 variable. It can occur for several cases, the most common of which is a
1256 mismatch in the expected type that the compiler inferred for a variable's
1257 initializing expression, and the actual type explicitly assigned to the
1258 variable.
1259
1260 For example:
1261
1262 ```compile_fail,E0308
1263 let x: i32 = "I am not a number!";
1264 //     ~~~   ~~~~~~~~~~~~~~~~~~~~
1265 //      |             |
1266 //      |    initializing expression;
1267 //      |    compiler infers type `&str`
1268 //      |
1269 //    type `i32` assigned to variable `x`
1270 ```
1271 "##,
1272
1273 E0309: r##"
1274 The type definition contains some field whose type
1275 requires an outlives annotation. Outlives annotations
1276 (e.g., `T: 'a`) are used to guarantee that all the data in T is valid
1277 for at least the lifetime `'a`. This scenario most commonly
1278 arises when the type contains an associated type reference
1279 like `<T as SomeTrait<'a>>::Output`, as shown in this example:
1280
1281 ```compile_fail,E0309
1282 // This won't compile because the applicable impl of
1283 // `SomeTrait` (below) requires that `T: 'a`, but the struct does
1284 // not have a matching where-clause.
1285 struct Foo<'a, T> {
1286     foo: <T as SomeTrait<'a>>::Output,
1287 }
1288
1289 trait SomeTrait<'a> {
1290     type Output;
1291 }
1292
1293 impl<'a, T> SomeTrait<'a> for T
1294 where
1295     T: 'a,
1296 {
1297     type Output = u32;
1298 }
1299 ```
1300
1301 Here, the where clause `T: 'a` that appears on the impl is not known to be
1302 satisfied on the struct. To make this example compile, you have to add
1303 a where-clause like `T: 'a` to the struct definition:
1304
1305 ```
1306 struct Foo<'a, T>
1307 where
1308     T: 'a,
1309 {
1310     foo: <T as SomeTrait<'a>>::Output
1311 }
1312
1313 trait SomeTrait<'a> {
1314     type Output;
1315 }
1316
1317 impl<'a, T> SomeTrait<'a> for T
1318 where
1319     T: 'a,
1320 {
1321     type Output = u32;
1322 }
1323 ```
1324 "##,
1325
1326 E0310: r##"
1327 Types in type definitions have lifetimes associated with them that represent
1328 how long the data stored within them is guaranteed to be live. This lifetime
1329 must be as long as the data needs to be alive, and missing the constraint that
1330 denotes this will cause this error.
1331
1332 ```compile_fail,E0310
1333 // This won't compile because T is not constrained to the static lifetime
1334 // the reference needs
1335 struct Foo<T> {
1336     foo: &'static T
1337 }
1338 ```
1339
1340 This will compile, because it has the constraint on the type parameter:
1341
1342 ```
1343 struct Foo<T: 'static> {
1344     foo: &'static T
1345 }
1346 ```
1347 "##,
1348
1349 E0317: r##"
1350 This error occurs when an `if` expression without an `else` block is used in a
1351 context where a type other than `()` is expected, for example a `let`
1352 expression:
1353
1354 ```compile_fail,E0317
1355 fn main() {
1356     let x = 5;
1357     let a = if x == 5 { 1 };
1358 }
1359 ```
1360
1361 An `if` expression without an `else` block has the type `()`, so this is a type
1362 error. To resolve it, add an `else` block having the same type as the `if`
1363 block.
1364 "##,
1365
1366 E0391: r##"
1367 This error indicates that some types or traits depend on each other
1368 and therefore cannot be constructed.
1369
1370 The following example contains a circular dependency between two traits:
1371
1372 ```compile_fail,E0391
1373 trait FirstTrait : SecondTrait {
1374
1375 }
1376
1377 trait SecondTrait : FirstTrait {
1378
1379 }
1380 ```
1381 "##,
1382
1383 E0398: r##"
1384 #### Note: this error code is no longer emitted by the compiler.
1385
1386 In Rust 1.3, the default object lifetime bounds are expected to change, as
1387 described in [RFC 1156]. You are getting a warning because the compiler
1388 thinks it is possible that this change will cause a compilation error in your
1389 code. It is possible, though unlikely, that this is a false alarm.
1390
1391 The heart of the change is that where `&'a Box<SomeTrait>` used to default to
1392 `&'a Box<SomeTrait+'a>`, it now defaults to `&'a Box<SomeTrait+'static>` (here,
1393 `SomeTrait` is the name of some trait type). Note that the only types which are
1394 affected are references to boxes, like `&Box<SomeTrait>` or
1395 `&[Box<SomeTrait>]`. More common types like `&SomeTrait` or `Box<SomeTrait>`
1396 are unaffected.
1397
1398 To silence this warning, edit your code to use an explicit bound. Most of the
1399 time, this means that you will want to change the signature of a function that
1400 you are calling. For example, if the error is reported on a call like `foo(x)`,
1401 and `foo` is defined as follows:
1402
1403 ```
1404 # trait SomeTrait {}
1405 fn foo(arg: &Box<SomeTrait>) { /* ... */ }
1406 ```
1407
1408 You might change it to:
1409
1410 ```
1411 # trait SomeTrait {}
1412 fn foo<'a>(arg: &'a Box<SomeTrait+'a>) { /* ... */ }
1413 ```
1414
1415 This explicitly states that you expect the trait object `SomeTrait` to contain
1416 references (with a maximum lifetime of `'a`).
1417
1418 [RFC 1156]: https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md
1419 "##,
1420
1421 E0452: r##"
1422 An invalid lint attribute has been given. Erroneous code example:
1423
1424 ```compile_fail,E0452
1425 #![allow(foo = "")] // error: malformed lint attribute
1426 ```
1427
1428 Lint attributes only accept a list of identifiers (where each identifier is a
1429 lint name). Ensure the attribute is of this form:
1430
1431 ```
1432 #![allow(foo)] // ok!
1433 // or:
1434 #![allow(foo, foo2)] // ok!
1435 ```
1436 "##,
1437
1438 E0453: r##"
1439 A lint check attribute was overruled by a `forbid` directive set as an
1440 attribute on an enclosing scope, or on the command line with the `-F` option.
1441
1442 Example of erroneous code:
1443
1444 ```compile_fail,E0453
1445 #![forbid(non_snake_case)]
1446
1447 #[allow(non_snake_case)]
1448 fn main() {
1449     let MyNumber = 2; // error: allow(non_snake_case) overruled by outer
1450                       //        forbid(non_snake_case)
1451 }
1452 ```
1453
1454 The `forbid` lint setting, like `deny`, turns the corresponding compiler
1455 warning into a hard error. Unlike `deny`, `forbid` prevents itself from being
1456 overridden by inner attributes.
1457
1458 If you're sure you want to override the lint check, you can change `forbid` to
1459 `deny` (or use `-D` instead of `-F` if the `forbid` setting was given as a
1460 command-line option) to allow the inner lint check attribute:
1461
1462 ```
1463 #![deny(non_snake_case)]
1464
1465 #[allow(non_snake_case)]
1466 fn main() {
1467     let MyNumber = 2; // ok!
1468 }
1469 ```
1470
1471 Otherwise, edit the code to pass the lint check, and remove the overruled
1472 attribute:
1473
1474 ```
1475 #![forbid(non_snake_case)]
1476
1477 fn main() {
1478     let my_number = 2;
1479 }
1480 ```
1481 "##,
1482
1483 E0478: r##"
1484 A lifetime bound was not satisfied.
1485
1486 Erroneous code example:
1487
1488 ```compile_fail,E0478
1489 // Check that the explicit lifetime bound (`'SnowWhite`, in this example) must
1490 // outlive all the superbounds from the trait (`'kiss`, in this example).
1491
1492 trait Wedding<'t>: 't { }
1493
1494 struct Prince<'kiss, 'SnowWhite> {
1495     child: Box<Wedding<'kiss> + 'SnowWhite>,
1496     // error: lifetime bound not satisfied
1497 }
1498 ```
1499
1500 In this example, the `'SnowWhite` lifetime is supposed to outlive the `'kiss`
1501 lifetime but the declaration of the `Prince` struct doesn't enforce it. To fix
1502 this issue, you need to specify it:
1503
1504 ```
1505 trait Wedding<'t>: 't { }
1506
1507 struct Prince<'kiss, 'SnowWhite: 'kiss> { // You say here that 'kiss must live
1508                                           // longer than 'SnowWhite.
1509     child: Box<Wedding<'kiss> + 'SnowWhite>, // And now it's all good!
1510 }
1511 ```
1512 "##,
1513
1514 E0491: r##"
1515 A reference has a longer lifetime than the data it references.
1516
1517 Erroneous code example:
1518
1519 ```compile_fail,E0491
1520 trait SomeTrait<'a> {
1521     type Output;
1522 }
1523
1524 impl<'a, T> SomeTrait<'a> for T {
1525     type Output = &'a T; // compile error E0491
1526 }
1527 ```
1528
1529 Here, the problem is that a reference type like `&'a T` is only valid
1530 if all the data in T outlives the lifetime `'a`. But this impl as written
1531 is applicable to any lifetime `'a` and any type `T` -- we have no guarantee
1532 that `T` outlives `'a`. To fix this, you can add a where clause like
1533 `where T: 'a`.
1534
1535 ```
1536 trait SomeTrait<'a> {
1537     type Output;
1538 }
1539
1540 impl<'a, T> SomeTrait<'a> for T
1541 where
1542     T: 'a,
1543 {
1544     type Output = &'a T; // compile error E0491
1545 }
1546 ```
1547 "##,
1548
1549 E0496: r##"
1550 A lifetime name is shadowing another lifetime name. Erroneous code example:
1551
1552 ```compile_fail,E0496
1553 struct Foo<'a> {
1554     a: &'a i32,
1555 }
1556
1557 impl<'a> Foo<'a> {
1558     fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1559                            //        name that is already in scope
1560     }
1561 }
1562 ```
1563
1564 Please change the name of one of the lifetimes to remove this error. Example:
1565
1566 ```
1567 struct Foo<'a> {
1568     a: &'a i32,
1569 }
1570
1571 impl<'a> Foo<'a> {
1572     fn f<'b>(x: &'b i32) { // ok!
1573     }
1574 }
1575
1576 fn main() {
1577 }
1578 ```
1579 "##,
1580
1581 E0497: r##"
1582 A stability attribute was used outside of the standard library. Erroneous code
1583 example:
1584
1585 ```compile_fail
1586 #[stable] // error: stability attributes may not be used outside of the
1587           //        standard library
1588 fn foo() {}
1589 ```
1590
1591 It is not possible to use stability attributes outside of the standard library.
1592 Also, for now, it is not possible to write deprecation messages either.
1593 "##,
1594
1595 E0512: r##"
1596 Transmute with two differently sized types was attempted. Erroneous code
1597 example:
1598
1599 ```compile_fail,E0512
1600 fn takes_u8(_: u8) {}
1601
1602 fn main() {
1603     unsafe { takes_u8(::std::mem::transmute(0u16)); }
1604     // error: cannot transmute between types of different sizes,
1605     //        or dependently-sized types
1606 }
1607 ```
1608
1609 Please use types with same size or use the expected type directly. Example:
1610
1611 ```
1612 fn takes_u8(_: u8) {}
1613
1614 fn main() {
1615     unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
1616     // or:
1617     unsafe { takes_u8(0u8); } // ok!
1618 }
1619 ```
1620 "##,
1621
1622 E0517: r##"
1623 This error indicates that a `#[repr(..)]` attribute was placed on an
1624 unsupported item.
1625
1626 Examples of erroneous code:
1627
1628 ```compile_fail,E0517
1629 #[repr(C)]
1630 type Foo = u8;
1631
1632 #[repr(packed)]
1633 enum Foo {Bar, Baz}
1634
1635 #[repr(u8)]
1636 struct Foo {bar: bool, baz: bool}
1637
1638 #[repr(C)]
1639 impl Foo {
1640     // ...
1641 }
1642 ```
1643
1644 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1645 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1646 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1647
1648 These attributes do not work on typedefs, since typedefs are just aliases.
1649
1650 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1651 discriminant size for enums with no data fields on any of the variants, e.g.
1652 `enum Color {Red, Blue, Green}`, effectively setting the size of the enum to
1653 the size of the provided type. Such an enum can be cast to a value of the same
1654 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1655 with a constrained set of allowed values.
1656
1657 Only field-less enums can be cast to numerical primitives, so this attribute
1658 will not apply to structs.
1659
1660 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1661 representation of enums isn't strictly defined in Rust, and this attribute
1662 won't work on enums.
1663
1664 `#[repr(simd)]` will give a struct consisting of a homogeneous series of machine
1665 types (i.e., `u8`, `i32`, etc) a representation that permits vectorization via
1666 SIMD. This doesn't make much sense for enums since they don't consist of a
1667 single list of data.
1668 "##,
1669
1670 E0518: r##"
1671 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1672 on something other than a function or method.
1673
1674 Examples of erroneous code:
1675
1676 ```compile_fail,E0518
1677 #[inline(always)]
1678 struct Foo;
1679
1680 #[inline(never)]
1681 impl Foo {
1682     // ...
1683 }
1684 ```
1685
1686 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1687 function. By default, the compiler does a pretty good job of figuring this out
1688 itself, but if you feel the need for annotations, `#[inline(always)]` and
1689 `#[inline(never)]` can override or force the compiler's decision.
1690
1691 If you wish to apply this attribute to all methods in an impl, manually annotate
1692 each method; it is not possible to annotate the entire impl with an `#[inline]`
1693 attribute.
1694 "##,
1695
1696 E0522: r##"
1697 The lang attribute is intended for marking special items that are built-in to
1698 Rust itself. This includes special traits (like `Copy` and `Sized`) that affect
1699 how the compiler behaves, as well as special functions that may be automatically
1700 invoked (such as the handler for out-of-bounds accesses when indexing a slice).
1701 Erroneous code example:
1702
1703 ```compile_fail,E0522
1704 #![feature(lang_items)]
1705
1706 #[lang = "cookie"]
1707 fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
1708     loop {}
1709 }
1710 ```
1711 "##,
1712
1713 E0525: r##"
1714 A closure was used but didn't implement the expected trait.
1715
1716 Erroneous code example:
1717
1718 ```compile_fail,E0525
1719 struct X;
1720
1721 fn foo<T>(_: T) {}
1722 fn bar<T: Fn(u32)>(_: T) {}
1723
1724 fn main() {
1725     let x = X;
1726     let closure = |_| foo(x); // error: expected a closure that implements
1727                               //        the `Fn` trait, but this closure only
1728                               //        implements `FnOnce`
1729     bar(closure);
1730 }
1731 ```
1732
1733 In the example above, `closure` is an `FnOnce` closure whereas the `bar`
1734 function expected an `Fn` closure. In this case, it's simple to fix the issue,
1735 you just have to implement `Copy` and `Clone` traits on `struct X` and it'll
1736 be ok:
1737
1738 ```
1739 #[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
1740 struct X;
1741
1742 fn foo<T>(_: T) {}
1743 fn bar<T: Fn(u32)>(_: T) {}
1744
1745 fn main() {
1746     let x = X;
1747     let closure = |_| foo(x);
1748     bar(closure); // ok!
1749 }
1750 ```
1751
1752 To understand better how closures work in Rust, read:
1753 https://doc.rust-lang.org/book/ch13-01-closures.html
1754 "##,
1755
1756 E0580: r##"
1757 The `main` function was incorrectly declared.
1758
1759 Erroneous code example:
1760
1761 ```compile_fail,E0580
1762 fn main(x: i32) { // error: main function has wrong type
1763     println!("{}", x);
1764 }
1765 ```
1766
1767 The `main` function prototype should never take arguments.
1768 Example:
1769
1770 ```
1771 fn main() {
1772     // your code
1773 }
1774 ```
1775
1776 If you want to get command-line arguments, use `std::env::args`. To exit with a
1777 specified exit code, use `std::process::exit`.
1778 "##,
1779
1780 E0562: r##"
1781 Abstract return types (written `impl Trait` for some trait `Trait`) are only
1782 allowed as function and inherent impl return types.
1783
1784 Erroneous code example:
1785
1786 ```compile_fail,E0562
1787 fn main() {
1788     let count_to_ten: impl Iterator<Item=usize> = 0..10;
1789     // error: `impl Trait` not allowed outside of function and inherent method
1790     //        return types
1791     for i in count_to_ten {
1792         println!("{}", i);
1793     }
1794 }
1795 ```
1796
1797 Make sure `impl Trait` only appears in return-type position.
1798
1799 ```
1800 fn count_to_n(n: usize) -> impl Iterator<Item=usize> {
1801     0..n
1802 }
1803
1804 fn main() {
1805     for i in count_to_n(10) {  // ok!
1806         println!("{}", i);
1807     }
1808 }
1809 ```
1810
1811 See [RFC 1522] for more details.
1812
1813 [RFC 1522]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md
1814 "##,
1815
1816 E0591: r##"
1817 Per [RFC 401][rfc401], if you have a function declaration `foo`:
1818
1819 ```
1820 // For the purposes of this explanation, all of these
1821 // different kinds of `fn` declarations are equivalent:
1822 struct S;
1823 fn foo(x: S) { /* ... */ }
1824 # #[cfg(for_demonstration_only)]
1825 extern "C" { fn foo(x: S); }
1826 # #[cfg(for_demonstration_only)]
1827 impl S { fn foo(self) { /* ... */ } }
1828 ```
1829
1830 the type of `foo` is **not** `fn(S)`, as one might expect.
1831 Rather, it is a unique, zero-sized marker type written here as `typeof(foo)`.
1832 However, `typeof(foo)` can be _coerced_ to a function pointer `fn(S)`,
1833 so you rarely notice this:
1834
1835 ```
1836 # struct S;
1837 # fn foo(_: S) {}
1838 let x: fn(S) = foo; // OK, coerces
1839 ```
1840
1841 The reason that this matter is that the type `fn(S)` is not specific to
1842 any particular function: it's a function _pointer_. So calling `x()` results
1843 in a virtual call, whereas `foo()` is statically dispatched, because the type
1844 of `foo` tells us precisely what function is being called.
1845
1846 As noted above, coercions mean that most code doesn't have to be
1847 concerned with this distinction. However, you can tell the difference
1848 when using **transmute** to convert a fn item into a fn pointer.
1849
1850 This is sometimes done as part of an FFI:
1851
1852 ```compile_fail,E0591
1853 extern "C" fn foo(userdata: Box<i32>) {
1854     /* ... */
1855 }
1856
1857 # fn callback(_: extern "C" fn(*mut i32)) {}
1858 # use std::mem::transmute;
1859 # unsafe {
1860 let f: extern "C" fn(*mut i32) = transmute(foo);
1861 callback(f);
1862 # }
1863 ```
1864
1865 Here, transmute is being used to convert the types of the fn arguments.
1866 This pattern is incorrect because, because the type of `foo` is a function
1867 **item** (`typeof(foo)`), which is zero-sized, and the target type (`fn()`)
1868 is a function pointer, which is not zero-sized.
1869 This pattern should be rewritten. There are a few possible ways to do this:
1870
1871 - change the original fn declaration to match the expected signature,
1872   and do the cast in the fn body (the preferred option)
1873 - cast the fn item fo a fn pointer before calling transmute, as shown here:
1874
1875     ```
1876     # extern "C" fn foo(_: Box<i32>) {}
1877     # use std::mem::transmute;
1878     # unsafe {
1879     let f: extern "C" fn(*mut i32) = transmute(foo as extern "C" fn(_));
1880     let f: extern "C" fn(*mut i32) = transmute(foo as usize); // works too
1881     # }
1882     ```
1883
1884 The same applies to transmutes to `*mut fn()`, which were observed in practice.
1885 Note though that use of this type is generally incorrect.
1886 The intention is typically to describe a function pointer, but just `fn()`
1887 alone suffices for that. `*mut fn()` is a pointer to a fn pointer.
1888 (Since these values are typically just passed to C code, however, this rarely
1889 makes a difference in practice.)
1890
1891 [rfc401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
1892 "##,
1893
1894 E0593: r##"
1895 You tried to supply an `Fn`-based type with an incorrect number of arguments
1896 than what was expected.
1897
1898 Erroneous code example:
1899
1900 ```compile_fail,E0593
1901 fn foo<F: Fn()>(x: F) { }
1902
1903 fn main() {
1904     // [E0593] closure takes 1 argument but 0 arguments are required
1905     foo(|y| { });
1906 }
1907 ```
1908 "##,
1909
1910 E0601: r##"
1911 No `main` function was found in a binary crate. To fix this error, add a
1912 `main` function. For example:
1913
1914 ```
1915 fn main() {
1916     // Your program will start here.
1917     println!("Hello world!");
1918 }
1919 ```
1920
1921 If you don't know the basics of Rust, you can go look to the Rust Book to get
1922 started: https://doc.rust-lang.org/book/
1923 "##,
1924
1925 E0602: r##"
1926 An unknown lint was used on the command line.
1927
1928 Erroneous example:
1929
1930 ```sh
1931 rustc -D bogus omse_file.rs
1932 ```
1933
1934 Maybe you just misspelled the lint name or the lint doesn't exist anymore.
1935 Either way, try to update/remove it in order to fix the error.
1936 "##,
1937
1938 E0621: r##"
1939 This error code indicates a mismatch between the lifetimes appearing in the
1940 function signature (i.e., the parameter types and the return type) and the
1941 data-flow found in the function body.
1942
1943 Erroneous code example:
1944
1945 ```compile_fail,E0621
1946 fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 { // error: explicit lifetime
1947                                              //        required in the type of
1948                                              //        `y`
1949     if x > y { x } else { y }
1950 }
1951 ```
1952
1953 In the code above, the function is returning data borrowed from either `x` or
1954 `y`, but the `'a` annotation indicates that it is returning data only from `x`.
1955 To fix the error, the signature and the body must be made to match. Typically,
1956 this is done by updating the function signature. So, in this case, we change
1957 the type of `y` to `&'a i32`, like so:
1958
1959 ```
1960 fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
1961     if x > y { x } else { y }
1962 }
1963 ```
1964
1965 Now the signature indicates that the function data borrowed from either `x` or
1966 `y`. Alternatively, you could change the body to not return data from `y`:
1967
1968 ```
1969 fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
1970     x
1971 }
1972 ```
1973 "##,
1974
1975 E0635: r##"
1976 The `#![feature]` attribute specified an unknown feature.
1977
1978 Erroneous code example:
1979
1980 ```compile_fail,E0635
1981 #![feature(nonexistent_rust_feature)] // error: unknown feature
1982 ```
1983
1984 "##,
1985
1986 E0636: r##"
1987 A `#![feature]` attribute was declared multiple times.
1988
1989 Erroneous code example:
1990
1991 ```compile_fail,E0636
1992 #![allow(stable_features)]
1993 #![feature(rust1)]
1994 #![feature(rust1)] // error: the feature `rust1` has already been declared
1995 ```
1996
1997 "##,
1998
1999 E0644: r##"
2000 A closure or generator was constructed that references its own type.
2001
2002 Erroneous example:
2003
2004 ```compile-fail,E0644
2005 fn fix<F>(f: &F)
2006   where F: Fn(&F)
2007 {
2008   f(&f);
2009 }
2010
2011 fn main() {
2012   fix(&|y| {
2013     // Here, when `x` is called, the parameter `y` is equal to `x`.
2014   });
2015 }
2016 ```
2017
2018 Rust does not permit a closure to directly reference its own type,
2019 either through an argument (as in the example above) or by capturing
2020 itself through its environment. This restriction helps keep closure
2021 inference tractable.
2022
2023 The easiest fix is to rewrite your closure into a top-level function,
2024 or into a method. In some cases, you may also be able to have your
2025 closure call itself by capturing a `&Fn()` object or `fn()` pointer
2026 that refers to itself. That is permitting, since the closure would be
2027 invoking itself via a virtual call, and hence does not directly
2028 reference its own *type*.
2029
2030 "##,
2031
2032 E0692: r##"
2033 A `repr(transparent)` type was also annotated with other, incompatible
2034 representation hints.
2035
2036 Erroneous code example:
2037
2038 ```compile_fail,E0692
2039 #[repr(transparent, C)] // error: incompatible representation hints
2040 struct Grams(f32);
2041 ```
2042
2043 A type annotated as `repr(transparent)` delegates all representation concerns to
2044 another type, so adding more representation hints is contradictory. Remove
2045 either the `transparent` hint or the other hints, like this:
2046
2047 ```
2048 #[repr(transparent)]
2049 struct Grams(f32);
2050 ```
2051
2052 Alternatively, move the other attributes to the contained type:
2053
2054 ```
2055 #[repr(C)]
2056 struct Foo {
2057     x: i32,
2058     // ...
2059 }
2060
2061 #[repr(transparent)]
2062 struct FooWrapper(Foo);
2063 ```
2064
2065 Note that introducing another `struct` just to have a place for the other
2066 attributes may have unintended side effects on the representation:
2067
2068 ```
2069 #[repr(transparent)]
2070 struct Grams(f32);
2071
2072 #[repr(C)]
2073 struct Float(f32);
2074
2075 #[repr(transparent)]
2076 struct Grams2(Float); // this is not equivalent to `Grams` above
2077 ```
2078
2079 Here, `Grams2` is a not equivalent to `Grams` -- the former transparently wraps
2080 a (non-transparent) struct containing a single float, while `Grams` is a
2081 transparent wrapper around a float. This can make a difference for the ABI.
2082 "##,
2083
2084 E0698: r##"
2085 When using generators (or async) all type variables must be bound so a
2086 generator can be constructed.
2087
2088 Erroneous code example:
2089
2090 ```edition2018,compile-fail,E0698
2091 async fn bar<T>() -> () {}
2092
2093 async fn foo() {
2094     bar().await; // error: cannot infer type for `T`
2095 }
2096 ```
2097
2098 In the above example `T` is unknowable by the compiler.
2099 To fix this you must bind `T` to a concrete type such as `String`
2100 so that a generator can then be constructed:
2101
2102 ```edition2018
2103 async fn bar<T>() -> () {}
2104
2105 async fn foo() {
2106   bar::<String>().await;
2107   //   ^^^^^^^^ specify type explicitly
2108 }
2109 ```
2110 "##,
2111
2112 E0700: r##"
2113 The `impl Trait` return type captures lifetime parameters that do not
2114 appear within the `impl Trait` itself.
2115
2116 Erroneous code example:
2117
2118 ```compile-fail,E0700
2119 use std::cell::Cell;
2120
2121 trait Trait<'a> { }
2122
2123 impl<'a, 'b> Trait<'b> for Cell<&'a u32> { }
2124
2125 fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y>
2126 where 'x: 'y
2127 {
2128     x
2129 }
2130 ```
2131
2132 Here, the function `foo` returns a value of type `Cell<&'x u32>`,
2133 which references the lifetime `'x`. However, the return type is
2134 declared as `impl Trait<'y>` -- this indicates that `foo` returns
2135 "some type that implements `Trait<'y>`", but it also indicates that
2136 the return type **only captures data referencing the lifetime `'y`**.
2137 In this case, though, we are referencing data with lifetime `'x`, so
2138 this function is in error.
2139
2140 To fix this, you must reference the lifetime `'x` from the return
2141 type. For example, changing the return type to `impl Trait<'y> + 'x`
2142 would work:
2143
2144 ```
2145 use std::cell::Cell;
2146
2147 trait Trait<'a> { }
2148
2149 impl<'a,'b> Trait<'b> for Cell<&'a u32> { }
2150
2151 fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y> + 'x
2152 where 'x: 'y
2153 {
2154     x
2155 }
2156 ```
2157 "##,
2158
2159 E0701: r##"
2160 This error indicates that a `#[non_exhaustive]` attribute was incorrectly placed
2161 on something other than a struct or enum.
2162
2163 Examples of erroneous code:
2164
2165 ```compile_fail,E0701
2166 # #![feature(non_exhaustive)]
2167
2168 #[non_exhaustive]
2169 trait Foo { }
2170 ```
2171 "##,
2172
2173 E0718: r##"
2174 This error indicates that a `#[lang = ".."]` attribute was placed
2175 on the wrong type of item.
2176
2177 Examples of erroneous code:
2178
2179 ```compile_fail,E0718
2180 #![feature(lang_items)]
2181
2182 #[lang = "arc"]
2183 static X: u32 = 42;
2184 ```
2185 "##,
2186
2187 }
2188
2189
2190 register_diagnostics! {
2191 //  E0006, // merged with E0005
2192 //  E0101, // replaced with E0282
2193 //  E0102, // replaced with E0282
2194 //  E0134,
2195 //  E0135,
2196 //  E0272, // on_unimplemented #0
2197 //  E0273, // on_unimplemented #1
2198 //  E0274, // on_unimplemented #2
2199     E0278, // requirement is not satisfied
2200     E0279, // requirement is not satisfied
2201     E0280, // requirement is not satisfied
2202 //  E0285, // overflow evaluation builtin bounds
2203 //  E0296, // replaced with a generic attribute input check
2204 //  E0300, // unexpanded macro
2205 //  E0304, // expected signed integer constant
2206 //  E0305, // expected constant
2207     E0311, // thing may not live long enough
2208     E0312, // lifetime of reference outlives lifetime of borrowed content
2209     E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
2210     E0314, // closure outlives stack frame
2211     E0315, // cannot invoke closure outside of its lifetime
2212     E0316, // nested quantification of lifetimes
2213     E0320, // recursive overflow during dropck
2214     E0473, // dereference of reference outside its lifetime
2215     E0474, // captured variable `..` does not outlive the enclosing closure
2216     E0475, // index of slice outside its lifetime
2217     E0476, // lifetime of the source pointer does not outlive lifetime bound...
2218     E0477, // the type `..` does not fulfill the required lifetime...
2219     E0479, // the type `..` (provided as the value of a type parameter) is...
2220     E0480, // lifetime of method receiver does not outlive the method call
2221     E0481, // lifetime of function argument does not outlive the function call
2222     E0482, // lifetime of return value does not outlive the function call
2223     E0483, // lifetime of operand does not outlive the operation
2224     E0484, // reference is not valid at the time of borrow
2225     E0485, // automatically reference is not valid at the time of borrow
2226     E0486, // type of expression contains references that are not valid during...
2227     E0487, // unsafe use of destructor: destructor might be called while...
2228     E0488, // lifetime of variable does not enclose its declaration
2229     E0489, // type/lifetime parameter not in scope here
2230     E0490, // a value of type `..` is borrowed for too long
2231     E0495, // cannot infer an appropriate lifetime due to conflicting requirements
2232     E0566, // conflicting representation hints
2233     E0623, // lifetime mismatch where both parameters are anonymous regions
2234     E0628, // generators cannot have explicit parameters
2235     E0631, // type mismatch in closure arguments
2236     E0637, // "'_" is not a valid lifetime bound
2237     E0657, // `impl Trait` can only capture lifetimes bound at the fn level
2238     E0687, // in-band lifetimes cannot be used in `fn`/`Fn` syntax
2239     E0688, // in-band lifetimes cannot be mixed with explicit lifetime binders
2240     E0697, // closures cannot be static
2241     E0707, // multiple elided lifetimes used in arguments of `async fn`
2242     E0708, // `async` non-`move` closures with parameters are not currently supported
2243     E0709, // multiple different lifetimes used in arguments of `async fn`
2244     E0710, // an unknown tool name found in scoped lint
2245     E0711, // a feature has been declared with conflicting stability attributes
2246 //  E0702, // replaced with a generic attribute input check
2247     E0726, // non-explicit (not `'_`) elided lifetime in unsupported position
2248     E0727, // `async` generators are not yet supported
2249     E0728, // `await` must be in an `async` function or block
2250 }