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