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