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