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