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