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