]> git.lizzy.rs Git - rust.git/blob - src/librustc/diagnostics.rs
Rollup merge of #36148 - birryree:E0194_bonus_format, r=jonathandturner
[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 ```ignore
202 fn call_foo(thing: Box<Trait>) {
203     thing.foo(true); // this could be any one of the 8 types above
204     thing.foo(1);
205     thing.foo("hello");
206 }
207 ```
208
209 We don't just need to create a table of all implementations of all methods of
210 `Trait`, we need to create such a table, for each different type fed to
211 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
212 types being fed to `foo()`) = 30 implementations!
213
214 With real world traits these numbers can grow drastically.
215
216 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
217 fix for the sub-error above if you do not intend to call the method with type
218 parameters:
219
220 ```
221 trait Trait {
222     fn foo<T>(&self, on: T) where Self: Sized;
223     // more methods
224 }
225 ```
226
227 If this is not an option, consider replacing the type parameter with another
228 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
229 of types you intend to feed to this method is limited, consider manually listing
230 out the methods of different types.
231
232 ### Method has no receiver
233
234 Methods that do not take a `self` parameter can't be called since there won't be
235 a way to get a pointer to the method table for them.
236
237 ```
238 trait Foo {
239     fn foo() -> u8;
240 }
241 ```
242
243 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
244 an implementation.
245
246 Adding a `Self: Sized` bound to these methods will generally make this compile.
247
248 ```
249 trait Foo {
250     fn foo() -> u8 where Self: Sized;
251 }
252 ```
253
254 ### The trait cannot use `Self` as a type parameter in the supertrait listing
255
256 This is similar to the second sub-error, but subtler. It happens in situations
257 like the following:
258
259 ```compile_fail
260 trait Super<A> {}
261
262 trait Trait: Super<Self> {
263 }
264
265 struct Foo;
266
267 impl Super<Foo> for Foo{}
268
269 impl Trait for Foo {}
270 ```
271
272 Here, the supertrait might have methods as follows:
273
274 ```
275 trait Super<A> {
276     fn get_a(&self) -> A; // note that this is object safe!
277 }
278 ```
279
280 If the trait `Foo` was deriving from something like `Super<String>` or
281 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
282 `get_a()` will definitely return an object of that type.
283
284 However, if it derives from `Super<Self>`, even though `Super` is object safe,
285 the method `get_a()` would return an object of unknown type when called on the
286 function. `Self` type parameters let us make object safe traits no longer safe,
287 so they are forbidden when specifying supertraits.
288
289 There's no easy fix for this, generally code will need to be refactored so that
290 you no longer need to derive from `Super<Self>`.
291 "##,
292
293 E0072: r##"
294 When defining a recursive struct or enum, any use of the type being defined
295 from inside the definition must occur behind a pointer (like `Box` or `&`).
296 This is because structs and enums must have a well-defined size, and without
297 the pointer, the size of the type would need to be unbounded.
298
299 Consider the following erroneous definition of a type for a list of bytes:
300
301 ```compile_fail,E0072
302 // error, invalid recursive struct type
303 struct ListNode {
304     head: u8,
305     tail: Option<ListNode>,
306 }
307 ```
308
309 This type cannot have a well-defined size, because it needs to be arbitrarily
310 large (since we would be able to nest `ListNode`s to any depth). Specifically,
311
312 ```plain
313 size of `ListNode` = 1 byte for `head`
314                    + 1 byte for the discriminant of the `Option`
315                    + size of `ListNode`
316 ```
317
318 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
319
320 ```
321 struct ListNode {
322     head: u8,
323     tail: Option<Box<ListNode>>,
324 }
325 ```
326
327 This works because `Box` is a pointer, so its size is well-known.
328 "##,
329
330 E0109: r##"
331 You tried to give a type parameter to a type which doesn't need it. Erroneous
332 code example:
333
334 ```compile_fail,E0109
335 type X = u32<i32>; // error: type parameters are not allowed on this type
336 ```
337
338 Please check that you used the correct type and recheck its definition. Perhaps
339 it doesn't need the type parameter.
340
341 Example:
342
343 ```
344 type X = u32; // this compiles
345 ```
346
347 Note that type parameters for enum-variant constructors go after the variant,
348 not after the enum (Option::None::<u32>, not Option::<u32>::None).
349 "##,
350
351 E0110: r##"
352 You tried to give a lifetime parameter to a type which doesn't need it.
353 Erroneous code example:
354
355 ```compile_fail,E0110
356 type X = u32<'static>; // error: lifetime parameters are not allowed on
357                        //        this type
358 ```
359
360 Please check that the correct type was used and recheck its definition; perhaps
361 it doesn't need the lifetime parameter. Example:
362
363 ```
364 type X = u32; // ok!
365 ```
366 "##,
367
368 E0133: r##"
369 Unsafe code was used outside of an unsafe function or block.
370
371 Erroneous code example:
372
373 ```compile_fail,E0133
374 unsafe fn f() { return; } // This is the unsafe code
375
376 fn main() {
377     f(); // error: call to unsafe function requires unsafe function or block
378 }
379 ```
380
381 Using unsafe functionality is potentially dangerous and disallowed by safety
382 checks. Examples:
383
384 * Dereferencing raw pointers
385 * Calling functions via FFI
386 * Calling functions marked unsafe
387
388 These safety checks can be relaxed for a section of the code by wrapping the
389 unsafe instructions with an `unsafe` block. For instance:
390
391 ```
392 unsafe fn f() { return; }
393
394 fn main() {
395     unsafe { f(); } // ok!
396 }
397 ```
398
399 See also https://doc.rust-lang.org/book/unsafe.html
400 "##,
401
402 // This shouldn't really ever trigger since the repeated value error comes first
403 E0136: r##"
404 A binary can only have one entry point, and by default that entry point is the
405 function `main()`. If there are multiple such functions, please rename one.
406 "##,
407
408 E0137: r##"
409 More than one function was declared with the `#[main]` attribute.
410
411 Erroneous code example:
412
413 ```compile_fail,E0137
414 #![feature(main)]
415
416 #[main]
417 fn foo() {}
418
419 #[main]
420 fn f() {} // error: multiple functions with a #[main] attribute
421 ```
422
423 This error indicates that the compiler found multiple functions with the
424 `#[main]` attribute. This is an error because there must be a unique entry
425 point into a Rust program. Example:
426
427 ```
428 #![feature(main)]
429
430 #[main]
431 fn f() {} // ok!
432 ```
433 "##,
434
435 E0138: r##"
436 More than one function was declared with the `#[start]` attribute.
437
438 Erroneous code example:
439
440 ```compile_fail,E0138
441 #![feature(start)]
442
443 #[start]
444 fn foo(argc: isize, argv: *const *const u8) -> isize {}
445
446 #[start]
447 fn f(argc: isize, argv: *const *const u8) -> isize {}
448 // error: multiple 'start' functions
449 ```
450
451 This error indicates that the compiler found multiple functions with the
452 `#[start]` attribute. This is an error because there must be a unique entry
453 point into a Rust program. Example:
454
455 ```
456 #![feature(start)]
457
458 #[start]
459 fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
460 ```
461 "##,
462
463 // isn't thrown anymore
464 E0139: r##"
465 There are various restrictions on transmuting between types in Rust; for example
466 types being transmuted must have the same size. To apply all these restrictions,
467 the compiler must know the exact types that may be transmuted. When type
468 parameters are involved, this cannot always be done.
469
470 So, for example, the following is not allowed:
471
472 ```
473 use std::mem::transmute;
474
475 struct Foo<T>(Vec<T>);
476
477 fn foo<T>(x: Vec<T>) {
478     // we are transmuting between Vec<T> and Foo<F> here
479     let y: Foo<T> = unsafe { transmute(x) };
480     // do something with y
481 }
482 ```
483
484 In this specific case there's a good chance that the transmute is harmless (but
485 this is not guaranteed by Rust). However, when alignment and enum optimizations
486 come into the picture, it's quite likely that the sizes may or may not match
487 with different type parameter substitutions. It's not possible to check this for
488 _all_ possible types, so `transmute()` simply only accepts types without any
489 unsubstituted type parameters.
490
491 If you need this, there's a good chance you're doing something wrong. Keep in
492 mind that Rust doesn't guarantee much about the layout of different structs
493 (even two structs with identical declarations may have different layouts). If
494 there is a solution that avoids the transmute entirely, try it instead.
495
496 If it's possible, hand-monomorphize the code by writing the function for each
497 possible type substitution. It's possible to use traits to do this cleanly,
498 for example:
499
500 ```ignore
501 struct Foo<T>(Vec<T>);
502
503 trait MyTransmutableType {
504     fn transmute(Vec<Self>) -> Foo<Self>;
505 }
506
507 impl MyTransmutableType for u8 {
508     fn transmute(x: Foo<u8>) -> Vec<u8> {
509         transmute(x)
510     }
511 }
512
513 impl MyTransmutableType for String {
514     fn transmute(x: Foo<String>) -> Vec<String> {
515         transmute(x)
516     }
517 }
518
519 // ... more impls for the types you intend to transmute
520
521 fn foo<T: MyTransmutableType>(x: Vec<T>) {
522     let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
523     // do something with y
524 }
525 ```
526
527 Each impl will be checked for a size match in the transmute as usual, and since
528 there are no unbound type parameters involved, this should compile unless there
529 is a size mismatch in one of the impls.
530
531 It is also possible to manually transmute:
532
533 ```ignore
534 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
535 ```
536
537 Note that this does not move `v` (unlike `transmute`), and may need a
538 call to `mem::forget(v)` in case you want to avoid destructors being called.
539 "##,
540
541 E0152: r##"
542 A lang item was redefined.
543
544 Erroneous code example:
545
546 ```compile_fail,E0152
547 #![feature(lang_items)]
548
549 #[lang = "panic_fmt"]
550 struct Foo; // error: duplicate lang item found: `panic_fmt`
551 ```
552
553 Lang items are already implemented in the standard library. Unless you are
554 writing a free-standing application (e.g. a kernel), you do not need to provide
555 them yourself.
556
557 You can build a free-standing crate by adding `#![no_std]` to the crate
558 attributes:
559
560 ```
561 #![no_std]
562 ```
563
564 See also https://doc.rust-lang.org/book/no-stdlib.html
565 "##,
566
567 E0229: r##"
568 An associated type binding was done outside of the type parameter declaration
569 and `where` clause. Erroneous code example:
570
571 ```compile_fail,E0229
572 pub trait Foo {
573     type A;
574     fn boo(&self) -> <Self as Foo>::A;
575 }
576
577 struct Bar;
578
579 impl Foo for isize {
580     type A = usize;
581     fn boo(&self) -> usize { 42 }
582 }
583
584 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
585 // error: associated type bindings are not allowed here
586 ```
587
588 To solve this error, please move the type bindings in the type parameter
589 declaration:
590
591 ```ignore
592 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
593 ```
594
595 Or in the `where` clause:
596
597 ```ignore
598 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
599 ```
600 "##,
601
602 E0261: r##"
603 When using a lifetime like `'a` in a type, it must be declared before being
604 used.
605
606 These two examples illustrate the problem:
607
608 ```compile_fail,E0261
609 // error, use of undeclared lifetime name `'a`
610 fn foo(x: &'a str) { }
611
612 struct Foo {
613     // error, use of undeclared lifetime name `'a`
614     x: &'a str,
615 }
616 ```
617
618 These can be fixed by declaring lifetime parameters:
619
620 ```
621 fn foo<'a>(x: &'a str) {}
622
623 struct Foo<'a> {
624     x: &'a str,
625 }
626 ```
627 "##,
628
629 E0262: r##"
630 Declaring certain lifetime names in parameters is disallowed. For example,
631 because the `'static` lifetime is a special built-in lifetime name denoting
632 the lifetime of the entire program, this is an error:
633
634 ```compile_fail,E0262
635 // error, invalid lifetime parameter name `'static`
636 fn foo<'static>(x: &'static str) { }
637 ```
638 "##,
639
640 E0263: r##"
641 A lifetime name cannot be declared more than once in the same scope. For
642 example:
643
644 ```compile_fail,E0263
645 // error, lifetime name `'a` declared twice in the same scope
646 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
647 ```
648 "##,
649
650 E0264: r##"
651 An unknown external lang item was used. Erroneous code example:
652
653 ```compile_fail,E0264
654 #![feature(lang_items)]
655
656 extern "C" {
657     #[lang = "cake"] // error: unknown external lang item: `cake`
658     fn cake();
659 }
660 ```
661
662 A list of available external lang items is available in
663 `src/librustc/middle/weak_lang_items.rs`. Example:
664
665 ```
666 #![feature(lang_items)]
667
668 extern "C" {
669     #[lang = "panic_fmt"] // ok!
670     fn cake();
671 }
672 ```
673 "##,
674
675 E0269: r##"
676 A returned value was expected but not all control paths return one.
677
678 Erroneous code example:
679
680 ```compile_fail,E0269
681 fn abracada_FAIL() -> String {
682     "this won't work".to_string();
683     // error: not all control paths return a value
684 }
685 ```
686
687 In the previous code, the function is supposed to return a `String`, however,
688 the code returns nothing (because of the ';'). Another erroneous code would be:
689
690 ```compile_fail
691 fn abracada_FAIL(b: bool) -> u32 {
692     if b {
693         0
694     } else {
695         "a" // It fails because an `u32` was expected and something else is
696             // returned.
697     }
698 }
699 ```
700
701 It is advisable to find out what the unhandled cases are and check for them,
702 returning an appropriate value or panicking if necessary. Check if you need
703 to remove a semicolon from the last expression, like in the first erroneous
704 code example.
705 "##,
706
707 E0270: r##"
708 Rust lets you define functions which are known to never return, i.e. are
709 'diverging', by marking its return type as `!`.
710
711 For example, the following functions never return:
712
713 ```no_run
714 fn foo() -> ! {
715     loop {}
716 }
717
718 fn bar() -> ! {
719     foo() // foo() is diverging, so this will diverge too
720 }
721
722 fn baz() -> ! {
723     panic!(); // this macro internally expands to a call to a diverging function
724 }
725 ```
726
727 Such functions can be used in a place where a value is expected without
728 returning a value of that type, for instance:
729
730 ```no_run
731 fn foo() -> ! {
732     loop {}
733 }
734
735 let x = 3;
736
737 let y = match x {
738     1 => 1,
739     2 => 4,
740     _ => foo() // diverging function called here
741 };
742
743 println!("{}", y)
744 ```
745
746 If the third arm of the match block is reached, since `foo()` doesn't ever
747 return control to the match block, it is fine to use it in a place where an
748 integer was expected. The `match` block will never finish executing, and any
749 point where `y` (like the print statement) is needed will not be reached.
750
751 However, if we had a diverging function that actually does finish execution:
752
753 ```ignore
754 fn foo() -> ! {
755     loop {break;}
756 }
757 ```
758
759 Then we would have an unknown value for `y` in the following code:
760
761 ```no_run
762 fn foo() -> ! {
763     loop {}
764 }
765
766 let x = 3;
767
768 let y = match x {
769     1 => 1,
770     2 => 4,
771     _ => foo()
772 };
773
774 println!("{}", y);
775 ```
776
777 In the previous example, the print statement was never reached when the
778 wildcard match arm was hit, so we were okay with `foo()` not returning an
779 integer that we could set to `y`. But in this example, `foo()` actually does
780 return control, so the print statement will be executed with an uninitialized
781 value.
782
783 Obviously we cannot have functions which are allowed to be used in such
784 positions and yet can return control. So, if you are defining a function that
785 returns `!`, make sure that there is no way for it to actually finish
786 executing.
787 "##,
788
789 E0271: r##"
790 This is because of a type mismatch between the associated type of some
791 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
792 and another type `U` that is required to be equal to `T::Bar`, but is not.
793 Examples follow.
794
795 Here is a basic example:
796
797 ```compile_fail,E0271
798 trait Trait { type AssociatedType; }
799
800 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
801     println!("in foo");
802 }
803
804 impl Trait for i8 { type AssociatedType = &'static str; }
805
806 foo(3_i8);
807 ```
808
809 Here is that same example again, with some explanatory comments:
810
811 ```ignore
812 trait Trait { type AssociatedType; }
813
814 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
815 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
816 //                        |            |
817 //         This says `foo` can         |
818 //           only be used with         |
819 //              some type that         |
820 //         implements `Trait`.         |
821 //                                     |
822 //                             This says not only must
823 //                             `T` be an impl of `Trait`
824 //                             but also that the impl
825 //                             must assign the type `u32`
826 //                             to the associated type.
827     println!("in foo");
828 }
829
830 impl Trait for i8 { type AssociatedType = &'static str; }
831 ~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
832 //      |                             |
833 // `i8` does have                     |
834 // implementation                     |
835 // of `Trait`...                      |
836 //                     ... but it is an implementation
837 //                     that assigns `&'static str` to
838 //                     the associated type.
839
840 foo(3_i8);
841 // Here, we invoke `foo` with an `i8`, which does not satisfy
842 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
843 // therefore the type-checker complains with this error code.
844 ```
845
846 Here is a more subtle instance of the same problem, that can
847 arise with for-loops in Rust:
848
849 ```compile_fail
850 let vs: Vec<i32> = vec![1, 2, 3, 4];
851 for v in &vs {
852     match v {
853         1 => {},
854         _ => {},
855     }
856 }
857 ```
858
859 The above fails because of an analogous type mismatch,
860 though may be harder to see. Again, here are some
861 explanatory comments for the same example:
862
863 ```ignore
864 {
865     let vs = vec![1, 2, 3, 4];
866
867     // `for`-loops use a protocol based on the `Iterator`
868     // trait. Each item yielded in a `for` loop has the
869     // type `Iterator::Item` -- that is, `Item` is the
870     // associated type of the concrete iterator impl.
871     for v in &vs {
872 //      ~    ~~~
873 //      |     |
874 //      |    We borrow `vs`, iterating over a sequence of
875 //      |    *references* of type `&Elem` (where `Elem` is
876 //      |    vector's element type). Thus, the associated
877 //      |    type `Item` must be a reference `&`-type ...
878 //      |
879 //  ... and `v` has the type `Iterator::Item`, as dictated by
880 //  the `for`-loop protocol ...
881
882         match v {
883             1 => {}
884 //          ~
885 //          |
886 // ... but *here*, `v` is forced to have some integral type;
887 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
888 // match the pattern `1` ...
889
890             _ => {}
891         }
892
893 // ... therefore, the compiler complains, because it sees
894 // an attempt to solve the equations
895 // `some integral-type` = type-of-`v`
896 //                      = `Iterator::Item`
897 //                      = `&Elem` (i.e. `some reference type`)
898 //
899 // which cannot possibly all be true.
900
901     }
902 }
903 ```
904
905 To avoid those issues, you have to make the types match correctly.
906 So we can fix the previous examples like this:
907
908 ```
909 // Basic Example:
910 trait Trait { type AssociatedType; }
911
912 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
913     println!("in foo");
914 }
915
916 impl Trait for i8 { type AssociatedType = &'static str; }
917
918 foo(3_i8);
919
920 // For-Loop Example:
921 let vs = vec![1, 2, 3, 4];
922 for v in &vs {
923     match v {
924         &1 => {}
925         _ => {}
926     }
927 }
928 ```
929 "##,
930
931 E0272: r##"
932 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
933 message for when a particular trait isn't implemented on a type placed in a
934 position that needs that trait. For example, when the following code is
935 compiled:
936
937 ```compile_fail
938 #![feature(on_unimplemented)]
939
940 fn foo<T: Index<u8>>(x: T){}
941
942 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
943 trait Index<Idx> { /* ... */ }
944
945 foo(true); // `bool` does not implement `Index<u8>`
946 ```
947
948 There will be an error about `bool` not implementing `Index<u8>`, followed by a
949 note saying "the type `bool` cannot be indexed by `u8`".
950
951 As you can see, you can specify type parameters in curly braces for
952 substitution with the actual types (using the regular format string syntax) in
953 a given situation. Furthermore, `{Self}` will substitute to the type (in this
954 case, `bool`) that we tried to use.
955
956 This error appears when the curly braces contain an identifier which doesn't
957 match with any of the type parameters or the string `Self`. This might happen
958 if you misspelled a type parameter, or if you intended to use literal curly
959 braces. If it is the latter, escape the curly braces with a second curly brace
960 of the same type; e.g. a literal `{` is `{{`.
961 "##,
962
963 E0273: 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 As you can see, you can specify type parameters in curly braces for
984 substitution with the actual types (using the regular format string syntax) in
985 a given situation. Furthermore, `{Self}` will substitute to the type (in this
986 case, `bool`) that we tried to use.
987
988 This error appears when the curly braces do not contain an identifier. Please
989 add one of the same name as a type parameter. If you intended to use literal
990 braces, use `{{` and `}}` to escape them.
991 "##,
992
993 E0274: r##"
994 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
995 message for when a particular trait isn't implemented on a type placed in a
996 position that needs that trait. For example, when the following code is
997 compiled:
998
999 ```compile_fail
1000 #![feature(on_unimplemented)]
1001
1002 fn foo<T: Index<u8>>(x: T){}
1003
1004 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1005 trait Index<Idx> { /* ... */ }
1006
1007 foo(true); // `bool` does not implement `Index<u8>`
1008 ```
1009
1010 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1011 note saying "the type `bool` cannot be indexed by `u8`".
1012
1013 For this to work, some note must be specified. An empty attribute will not do
1014 anything, please remove the attribute or add some helpful note for users of the
1015 trait.
1016 "##,
1017
1018 E0275: r##"
1019 This error occurs when there was a recursive trait requirement that overflowed
1020 before it could be evaluated. Often this means that there is unbounded
1021 recursion in resolving some type bounds.
1022
1023 For example, in the following code:
1024
1025 ```compile_fail,E0275
1026 trait Foo {}
1027
1028 struct Bar<T>(T);
1029
1030 impl<T> Foo for T where Bar<T>: Foo {}
1031 ```
1032
1033 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1034 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
1035 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
1036 clearly a recursive requirement that can't be resolved directly.
1037
1038 Consider changing your trait bounds so that they're less self-referential.
1039 "##,
1040
1041 E0276: r##"
1042 This error occurs when a bound in an implementation of a trait does not match
1043 the bounds specified in the original trait. For example:
1044
1045 ```compile_fail,E0276
1046 trait Foo {
1047     fn foo<T>(x: T);
1048 }
1049
1050 impl Foo for bool {
1051     fn foo<T>(x: T) where T: Copy {}
1052 }
1053 ```
1054
1055 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1056 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1057 bound that `T` is `Copy`, which isn't compatible with the original trait.
1058
1059 Consider removing the bound from the method or adding the bound to the original
1060 method definition in the trait.
1061 "##,
1062
1063 E0277: r##"
1064 You tried to use a type which doesn't implement some trait in a place which
1065 expected that trait. Erroneous code example:
1066
1067 ```compile_fail,E0277
1068 // here we declare the Foo trait with a bar method
1069 trait Foo {
1070     fn bar(&self);
1071 }
1072
1073 // we now declare a function which takes an object implementing the Foo trait
1074 fn some_func<T: Foo>(foo: T) {
1075     foo.bar();
1076 }
1077
1078 fn main() {
1079     // we now call the method with the i32 type, which doesn't implement
1080     // the Foo trait
1081     some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
1082 }
1083 ```
1084
1085 In order to fix this error, verify that the type you're using does implement
1086 the trait. Example:
1087
1088 ```
1089 trait Foo {
1090     fn bar(&self);
1091 }
1092
1093 fn some_func<T: Foo>(foo: T) {
1094     foo.bar(); // we can now use this method since i32 implements the
1095                // Foo trait
1096 }
1097
1098 // we implement the trait on the i32 type
1099 impl Foo for i32 {
1100     fn bar(&self) {}
1101 }
1102
1103 fn main() {
1104     some_func(5i32); // ok!
1105 }
1106 ```
1107
1108 Or in a generic context, an erroneous code example would look like:
1109
1110 ```compile_fail,E0277
1111 fn some_func<T>(foo: T) {
1112     println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1113                            //        implemented for the type `T`
1114 }
1115
1116 fn main() {
1117     // We now call the method with the i32 type,
1118     // which *does* implement the Debug trait.
1119     some_func(5i32);
1120 }
1121 ```
1122
1123 Note that the error here is in the definition of the generic function: Although
1124 we only call it with a parameter that does implement `Debug`, the compiler
1125 still rejects the function: It must work with all possible input types. In
1126 order to make this example compile, we need to restrict the generic type we're
1127 accepting:
1128
1129 ```
1130 use std::fmt;
1131
1132 // Restrict the input type to types that implement Debug.
1133 fn some_func<T: fmt::Debug>(foo: T) {
1134     println!("{:?}", foo);
1135 }
1136
1137 fn main() {
1138     // Calling the method is still fine, as i32 implements Debug.
1139     some_func(5i32);
1140
1141     // This would fail to compile now:
1142     // struct WithoutDebug;
1143     // some_func(WithoutDebug);
1144 }
1145 ```
1146
1147 Rust only looks at the signature of the called function, as such it must
1148 already specify all requirements that will be used for every type parameter.
1149 "##,
1150
1151 E0281: r##"
1152 You tried to supply a type which doesn't implement some trait in a location
1153 which expected that trait. This error typically occurs when working with
1154 `Fn`-based types. Erroneous code example:
1155
1156 ```compile_fail,E0281
1157 fn foo<F: Fn()>(x: F) { }
1158
1159 fn main() {
1160     // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1161     // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1162     // [E0281]
1163     foo(|y| { });
1164 }
1165 ```
1166
1167 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1168 arguments, but the closure we attempted to pass to it requires one argument.
1169 "##,
1170
1171 E0282: r##"
1172 This error indicates that type inference did not result in one unique possible
1173 type, and extra information is required. In most cases this can be provided
1174 by adding a type annotation. Sometimes you need to specify a generic type
1175 parameter manually.
1176
1177 A common example is the `collect` method on `Iterator`. It has a generic type
1178 parameter with a `FromIterator` bound, which for a `char` iterator is
1179 implemented by `Vec` and `String` among others. Consider the following snippet
1180 that reverses the characters of a string:
1181
1182 ```compile_fail,E0282
1183 let x = "hello".chars().rev().collect();
1184 ```
1185
1186 In this case, the compiler cannot infer what the type of `x` should be:
1187 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1188 use, you can use a type annotation on `x`:
1189
1190 ```
1191 let x: Vec<char> = "hello".chars().rev().collect();
1192 ```
1193
1194 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1195 the compiler can infer the rest:
1196
1197 ```
1198 let x: Vec<_> = "hello".chars().rev().collect();
1199 ```
1200
1201 Another way to provide the compiler with enough information, is to specify the
1202 generic type parameter:
1203
1204 ```
1205 let x = "hello".chars().rev().collect::<Vec<char>>();
1206 ```
1207
1208 Again, you need not specify the full type if the compiler can infer it:
1209
1210 ```
1211 let x = "hello".chars().rev().collect::<Vec<_>>();
1212 ```
1213
1214 Apart from a method or function with a generic type parameter, this error can
1215 occur when a type parameter of a struct or trait cannot be inferred. In that
1216 case it is not always possible to use a type annotation, because all candidates
1217 have the same return type. For instance:
1218
1219 ```compile_fail,E0282
1220 struct Foo<T> {
1221     num: T,
1222 }
1223
1224 impl<T> Foo<T> {
1225     fn bar() -> i32 {
1226         0
1227     }
1228
1229     fn baz() {
1230         let number = Foo::bar();
1231     }
1232 }
1233 ```
1234
1235 This will fail because the compiler does not know which instance of `Foo` to
1236 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1237 "##,
1238
1239 E0283: r##"
1240 This error occurs when the compiler doesn't have enough information
1241 to unambiguously choose an implementation.
1242
1243 For example:
1244
1245 ```compile_fail,E0283
1246 trait Generator {
1247     fn create() -> u32;
1248 }
1249
1250 struct Impl;
1251
1252 impl Generator for Impl {
1253     fn create() -> u32 { 1 }
1254 }
1255
1256 struct AnotherImpl;
1257
1258 impl Generator for AnotherImpl {
1259     fn create() -> u32 { 2 }
1260 }
1261
1262 fn main() {
1263     let cont: u32 = Generator::create();
1264     // error, impossible to choose one of Generator trait implementation
1265     // Impl or AnotherImpl? Maybe anything else?
1266 }
1267 ```
1268
1269 To resolve this error use the concrete type:
1270
1271 ```
1272 trait Generator {
1273     fn create() -> u32;
1274 }
1275
1276 struct AnotherImpl;
1277
1278 impl Generator for AnotherImpl {
1279     fn create() -> u32 { 2 }
1280 }
1281
1282 fn main() {
1283     let gen1 = AnotherImpl::create();
1284
1285     // if there are multiple methods with same name (different traits)
1286     let gen2 = <AnotherImpl as Generator>::create();
1287 }
1288 ```
1289 "##,
1290
1291 E0296: r##"
1292 This error indicates that the given recursion limit could not be parsed. Ensure
1293 that the value provided is a positive integer between quotes.
1294
1295 Erroneous code example:
1296
1297 ```compile_fail,E0296
1298 #![recursion_limit]
1299
1300 fn main() {}
1301 ```
1302
1303 And a working example:
1304
1305 ```
1306 #![recursion_limit="1000"]
1307
1308 fn main() {}
1309 ```
1310 "##,
1311
1312 E0308: r##"
1313 This error occurs when the compiler was unable to infer the concrete type of a
1314 variable. It can occur for several cases, the most common of which is a
1315 mismatch in the expected type that the compiler inferred for a variable's
1316 initializing expression, and the actual type explicitly assigned to the
1317 variable.
1318
1319 For example:
1320
1321 ```compile_fail,E0308
1322 let x: i32 = "I am not a number!";
1323 //     ~~~   ~~~~~~~~~~~~~~~~~~~~
1324 //      |             |
1325 //      |    initializing expression;
1326 //      |    compiler infers type `&str`
1327 //      |
1328 //    type `i32` assigned to variable `x`
1329 ```
1330
1331 Another situation in which this occurs is when you attempt to use the `try!`
1332 macro inside a function that does not return a `Result<T, E>`:
1333
1334 ```compile_fail,E0308
1335 use std::fs::File;
1336
1337 fn main() {
1338     let mut f = try!(File::create("foo.txt"));
1339 }
1340 ```
1341
1342 This code gives an error like this:
1343
1344 ```text
1345 <std macros>:5:8: 6:42 error: mismatched types:
1346  expected `()`,
1347      found `core::result::Result<_, _>`
1348  (expected (),
1349      found enum `core::result::Result`) [E0308]
1350 ```
1351
1352 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1353 `()` as its return type, hence the error.
1354 "##,
1355
1356 E0309: r##"
1357 Types in type definitions have lifetimes associated with them that represent
1358 how long the data stored within them is guaranteed to be live. This lifetime
1359 must be as long as the data needs to be alive, and missing the constraint that
1360 denotes this will cause this error.
1361
1362 ```compile_fail,E0309
1363 // This won't compile because T is not constrained, meaning the data
1364 // stored in it is not guaranteed to last as long as the reference
1365 struct Foo<'a, T> {
1366     foo: &'a T
1367 }
1368 ```
1369
1370 This will compile, because it has the constraint on the type parameter:
1371
1372 ```
1373 struct Foo<'a, T: 'a> {
1374     foo: &'a T
1375 }
1376 ```
1377 "##,
1378
1379 E0310: r##"
1380 Types in type definitions have lifetimes associated with them that represent
1381 how long the data stored within them is guaranteed to be live. This lifetime
1382 must be as long as the data needs to be alive, and missing the constraint that
1383 denotes this will cause this error.
1384
1385 ```compile_fail,E0310
1386 // This won't compile because T is not constrained to the static lifetime
1387 // the reference needs
1388 struct Foo<T> {
1389     foo: &'static T
1390 }
1391 ```
1392
1393 This will compile, because it has the constraint on the type parameter:
1394
1395 ```
1396 struct Foo<T: 'static> {
1397     foo: &'static T
1398 }
1399 ```
1400 "##,
1401
1402 E0312: r##"
1403 A lifetime of reference outlives lifetime of borrowed content.
1404
1405 Erroneous code example:
1406
1407 ```compile_fail,E0312
1408 fn make_child<'human, 'elve>(x: &mut &'human isize, y: &mut &'elve isize) {
1409     *x = *y;
1410     // error: lifetime of reference outlives lifetime of borrowed content
1411 }
1412 ```
1413
1414 The compiler cannot determine if the `human` lifetime will live long enough
1415 to keep up on the elve one. To solve this error, you have to give an
1416 explicit lifetime hierarchy:
1417
1418 ```
1419 fn make_child<'human, 'elve: 'human>(x: &mut &'human isize,
1420                                      y: &mut &'elve isize) {
1421     *x = *y; // ok!
1422 }
1423 ```
1424
1425 Or use the same lifetime for every variable:
1426
1427 ```
1428 fn make_child<'elve>(x: &mut &'elve isize, y: &mut &'elve isize) {
1429     *x = *y; // ok!
1430 }
1431 ```
1432 "##,
1433
1434 E0398: r##"
1435 In Rust 1.3, the default object lifetime bounds are expected to change, as
1436 described in RFC #1156 [1]. 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 ```ignore
1453 fn foo(arg: &Box<SomeTrait>) { ... }
1454 ```
1455
1456 You might change it to:
1457
1458 ```ignore
1459 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1460 ```
1461
1462 This explicitly states that you expect the trait object `SomeTrait` to contain
1463 references (with a maximum lifetime of `'a`).
1464
1465 [1]: https://github.com/rust-lang/rfcs/pull/1156
1466 "##,
1467
1468 E0452: r##"
1469 An invalid lint attribute has been given. Erroneous code example:
1470
1471 ```compile_fail,E0452
1472 #![allow(foo = "")] // error: malformed lint attribute
1473 ```
1474
1475 Lint attributes only accept a list of identifiers (where each identifier is a
1476 lint name). Ensure the attribute is of this form:
1477
1478 ```
1479 #![allow(foo)] // ok!
1480 // or:
1481 #![allow(foo, foo2)] // ok!
1482 ```
1483 "##,
1484
1485 E0453: r##"
1486 A lint check attribute was overruled by a `forbid` directive set as an
1487 attribute on an enclosing scope, or on the command line with the `-F` option.
1488
1489 Example of erroneous code:
1490
1491 ```compile_fail,E0453
1492 #![forbid(non_snake_case)]
1493
1494 #[allow(non_snake_case)]
1495 fn main() {
1496     let MyNumber = 2; // error: allow(non_snake_case) overruled by outer
1497                       //        forbid(non_snake_case)
1498 }
1499 ```
1500
1501 The `forbid` lint setting, like `deny`, turns the corresponding compiler
1502 warning into a hard error. Unlike `deny`, `forbid` prevents itself from being
1503 overridden by inner attributes.
1504
1505 If you're sure you want to override the lint check, you can change `forbid` to
1506 `deny` (or use `-D` instead of `-F` if the `forbid` setting was given as a
1507 command-line option) to allow the inner lint check attribute:
1508
1509 ```
1510 #![deny(non_snake_case)]
1511
1512 #[allow(non_snake_case)]
1513 fn main() {
1514     let MyNumber = 2; // ok!
1515 }
1516 ```
1517
1518 Otherwise, edit the code to pass the lint check, and remove the overruled
1519 attribute:
1520
1521 ```
1522 #![forbid(non_snake_case)]
1523
1524 fn main() {
1525     let my_number = 2;
1526 }
1527 ```
1528 "##,
1529
1530 E0478: r##"
1531 A lifetime bound was not satisfied.
1532
1533 Erroneous code example:
1534
1535 ```compile_fail,E0478
1536 // Check that the explicit lifetime bound (`'SnowWhite`, in this example) must
1537 // outlive all the superbounds from the trait (`'kiss`, in this example).
1538
1539 trait Wedding<'t>: 't { }
1540
1541 struct Prince<'kiss, 'SnowWhite> {
1542     child: Box<Wedding<'kiss> + 'SnowWhite>,
1543     // error: lifetime bound not satisfied
1544 }
1545 ```
1546
1547 In this example, the `'SnowWhite` lifetime is supposed to outlive the `'kiss`
1548 lifetime but the declaration of the `Prince` struct doesn't enforce it. To fix
1549 this issue, you need to specify it:
1550
1551 ```
1552 trait Wedding<'t>: 't { }
1553
1554 struct Prince<'kiss, 'SnowWhite: 'kiss> { // You say here that 'kiss must live
1555                                           // longer than 'SnowWhite.
1556     child: Box<Wedding<'kiss> + 'SnowWhite>, // And now it's all good!
1557 }
1558 ```
1559 "##,
1560
1561 E0496: r##"
1562 A lifetime name is shadowing another lifetime name. Erroneous code example:
1563
1564 ```compile_fail,E0496
1565 struct Foo<'a> {
1566     a: &'a i32,
1567 }
1568
1569 impl<'a> Foo<'a> {
1570     fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1571                            //        name that is already in scope
1572     }
1573 }
1574 ```
1575
1576 Please change the name of one of the lifetimes to remove this error. Example:
1577
1578 ```
1579 struct Foo<'a> {
1580     a: &'a i32,
1581 }
1582
1583 impl<'a> Foo<'a> {
1584     fn f<'b>(x: &'b i32) { // ok!
1585     }
1586 }
1587
1588 fn main() {
1589 }
1590 ```
1591 "##,
1592
1593 E0497: r##"
1594 A stability attribute was used outside of the standard library. Erroneous code
1595 example:
1596
1597 ```compile_fail
1598 #[stable] // error: stability attributes may not be used outside of the
1599           //        standard library
1600 fn foo() {}
1601 ```
1602
1603 It is not possible to use stability attributes outside of the standard library.
1604 Also, for now, it is not possible to write deprecation messages either.
1605 "##,
1606
1607 E0512: r##"
1608 Transmute with two differently sized types was attempted. Erroneous code
1609 example:
1610
1611 ```compile_fail,E0512
1612 fn takes_u8(_: u8) {}
1613
1614 fn main() {
1615     unsafe { takes_u8(::std::mem::transmute(0u16)); }
1616     // error: transmute called with differently sized types
1617 }
1618 ```
1619
1620 Please use types with same size or use the expected type directly. Example:
1621
1622 ```
1623 fn takes_u8(_: u8) {}
1624
1625 fn main() {
1626     unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
1627     // or:
1628     unsafe { takes_u8(0u8); } // ok!
1629 }
1630 ```
1631 "##,
1632
1633 E0517: r##"
1634 This error indicates that a `#[repr(..)]` attribute was placed on an
1635 unsupported item.
1636
1637 Examples of erroneous code:
1638
1639 ```compile_fail,E0517
1640 #[repr(C)]
1641 type Foo = u8;
1642
1643 #[repr(packed)]
1644 enum Foo {Bar, Baz}
1645
1646 #[repr(u8)]
1647 struct Foo {bar: bool, baz: bool}
1648
1649 #[repr(C)]
1650 impl Foo {
1651     // ...
1652 }
1653 ```
1654
1655 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1656 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1657 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1658
1659 These attributes do not work on typedefs, since typedefs are just aliases.
1660
1661 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1662 discriminant size for C-like enums (when there is no associated data, e.g.
1663 `enum Color {Red, Blue, Green}`), effectively setting the size of the enum to
1664 the size of the provided type. Such an enum can be cast to a value of the same
1665 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1666 with a constrained set of allowed values.
1667
1668 Only C-like enums can be cast to numerical primitives, so this attribute will
1669 not apply to structs.
1670
1671 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1672 representation of enums isn't strictly defined in Rust, and this attribute
1673 won't work on enums.
1674
1675 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
1676 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1677 SIMD. This doesn't make much sense for enums since they don't consist of a
1678 single list of data.
1679 "##,
1680
1681 E0518: r##"
1682 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1683 on something other than a function or method.
1684
1685 Examples of erroneous code:
1686
1687 ```compile_fail,E0518
1688 #[inline(always)]
1689 struct Foo;
1690
1691 #[inline(never)]
1692 impl Foo {
1693     // ...
1694 }
1695 ```
1696
1697 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1698 function. By default, the compiler does a pretty good job of figuring this out
1699 itself, but if you feel the need for annotations, `#[inline(always)]` and
1700 `#[inline(never)]` can override or force the compiler's decision.
1701
1702 If you wish to apply this attribute to all methods in an impl, manually annotate
1703 each method; it is not possible to annotate the entire impl with an `#[inline]`
1704 attribute.
1705 "##,
1706
1707 E0522: r##"
1708 The lang attribute is intended for marking special items that are built-in to
1709 Rust itself. This includes special traits (like `Copy` and `Sized`) that affect
1710 how the compiler behaves, as well as special functions that may be automatically
1711 invoked (such as the handler for out-of-bounds accesses when indexing a slice).
1712 Erroneous code example:
1713
1714 ```compile_fail,E0522
1715 #![feature(lang_items)]
1716
1717 #[lang = "cookie"]
1718 fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
1719     loop {}
1720 }
1721 ```
1722 "##,
1723
1724 E0525: r##"
1725 A closure was attempted to get used whereas it doesn't implement the expected
1726 trait.
1727
1728 Erroneous code example:
1729
1730 ```compile_fail,E0525
1731 struct X;
1732
1733 fn foo<T>(_: T) {}
1734 fn bar<T: Fn(u32)>(_: T) {}
1735
1736 fn main() {
1737     let x = X;
1738     let closure = |_| foo(x); // error: expected a closure that implements
1739                               //        the `Fn` trait, but this closure only
1740                               //        implements `FnOnce`
1741     bar(closure);
1742 }
1743 ```
1744
1745 In the example above, `closure` is an `FnOnce` closure whereas the `bar`
1746 function expected an `Fn` closure. In this case, it's simple to fix the issue,
1747 you just have to implement `Copy` and `Clone` traits on `struct X` and it'll
1748 be ok:
1749
1750 ```
1751 #[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
1752 struct X;
1753
1754 fn foo<T>(_: T) {}
1755 fn bar<T: Fn(u32)>(_: T) {}
1756
1757 fn main() {
1758     let x = X;
1759     let closure = |_| foo(x);
1760     bar(closure); // ok!
1761 }
1762 ```
1763
1764 To understand better how closures work in Rust, read:
1765 https://doc.rust-lang.org/book/closures.html
1766 "##,
1767
1768 }
1769
1770
1771 register_diagnostics! {
1772 //  E0006 // merged with E0005
1773 //  E0134,
1774 //  E0135,
1775     E0278, // requirement is not satisfied
1776     E0279, // requirement is not satisfied
1777     E0280, // requirement is not satisfied
1778     E0284, // cannot resolve type
1779 //  E0285, // overflow evaluation builtin bounds
1780 //  E0300, // unexpanded macro
1781 //  E0304, // expected signed integer constant
1782 //  E0305, // expected constant
1783     E0311, // thing may not live long enough
1784     E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1785     E0314, // closure outlives stack frame
1786     E0315, // cannot invoke closure outside of its lifetime
1787     E0316, // nested quantification of lifetimes
1788     E0473, // dereference of reference outside its lifetime
1789     E0474, // captured variable `..` does not outlive the enclosing closure
1790     E0475, // index of slice outside its lifetime
1791     E0476, // lifetime of the source pointer does not outlive lifetime bound...
1792     E0477, // the type `..` does not fulfill the required lifetime...
1793     E0479, // the type `..` (provided as the value of a type parameter) is...
1794     E0480, // lifetime of method receiver does not outlive the method call
1795     E0481, // lifetime of function argument does not outlive the function call
1796     E0482, // lifetime of return value does not outlive the function call
1797     E0483, // lifetime of operand does not outlive the operation
1798     E0484, // reference is not valid at the time of borrow
1799     E0485, // automatically reference is not valid at the time of borrow
1800     E0486, // type of expression contains references that are not valid during...
1801     E0487, // unsafe use of destructor: destructor might be called while...
1802     E0488, // lifetime of variable does not enclose its declaration
1803     E0489, // type/lifetime parameter not in scope here
1804     E0490, // a value of type `..` is borrowed for too long
1805     E0491, // in type `..`, reference has a longer lifetime than the data it...
1806     E0495, // cannot infer an appropriate lifetime due to conflicting requirements
1807     E0566  // conflicting representation hints
1808 }