]> git.lizzy.rs Git - rust.git/blob - src/librustc/diagnostics.rs
Improve E0277 error message in a generic context
[rust.git] / src / librustc / diagnostics.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_snake_case)]
12
13 // Error messages for EXXXX errors.
14 // Each message should start and end with a new line, and be wrapped to 80 characters.
15 // In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
16 register_long_diagnostics! {
17 E0020: r##"
18 This error indicates that an attempt was made to divide by zero (or take the
19 remainder of a zero divisor) in a static or constant expression. Erroneous
20 code example:
21
22 ```compile_fail
23 const X: i32 = 42 / 0;
24 // error: attempted to divide by zero in a constant expression
25 ```
26 "##,
27
28 E0038: r##"
29 Trait objects like `Box<Trait>` can only be constructed when certain
30 requirements are satisfied by the trait in question.
31
32 Trait objects are a form of dynamic dispatch and use a dynamically sized type
33 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
34 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
35 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
36 (among other things) for dynamic dispatch. This design mandates some
37 restrictions on the types of traits that are allowed to be used in trait
38 objects, which are collectively termed as 'object safety' rules.
39
40 Attempting to create a trait object for a non object-safe trait will trigger
41 this error.
42
43 There are various rules:
44
45 ### The trait cannot require `Self: Sized`
46
47 When `Trait` is treated as a type, the type does not implement the special
48 `Sized` trait, because the type does not have a known size at compile time and
49 can only be accessed behind a pointer. Thus, if we have a trait like the
50 following:
51
52 ```
53 trait Foo where Self: Sized {
54
55 }
56 ```
57
58 We cannot create an object of type `Box<Foo>` or `&Foo` since in this case
59 `Self` would not be `Sized`.
60
61 Generally, `Self : Sized` is used to indicate that the trait should not be used
62 as a trait object. If the trait comes from your own crate, consider removing
63 this restriction.
64
65 ### Method references the `Self` type in its arguments or return type
66
67 This happens when a trait has a method like the following:
68
69 ```compile_fail
70 trait Trait {
71     fn foo(&self) -> Self;
72 }
73
74 impl Trait for String {
75     fn foo(&self) -> Self {
76         "hi".to_owned()
77     }
78 }
79
80 impl Trait for u8 {
81     fn foo(&self) -> Self {
82         1
83     }
84 }
85 ```
86
87 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
88 cause this problem.)
89
90 In such a case, the compiler cannot predict the return type of `foo()` in a
91 situation like the following:
92
93 ```compile_fail
94 trait Trait {
95     fn foo(&self) -> Self;
96 }
97
98 fn call_foo(x: Box<Trait>) {
99     let y = x.foo(); // What type is y?
100     // ...
101 }
102 ```
103
104 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
105 on them to mark them as explicitly unavailable to trait objects. The
106 functionality will still be available to all other implementers, including
107 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
108
109 ```
110 trait Trait {
111     fn foo(&self) -> Self where Self: Sized;
112     // more functions
113 }
114 ```
115
116 Now, `foo()` can no longer be called on a trait object, but you will now be
117 allowed to make a trait object, and that will be able to call any object-safe
118 methods". With such a bound, one can still call `foo()` on types implementing
119 that trait that aren't behind trait objects.
120
121 ### Method has generic type parameters
122
123 As mentioned before, trait objects contain pointers to method tables. So, if we
124 have:
125
126 ```
127 trait Trait {
128     fn foo(&self);
129 }
130
131 impl Trait for String {
132     fn foo(&self) {
133         // implementation 1
134     }
135 }
136
137 impl Trait for u8 {
138     fn foo(&self) {
139         // implementation 2
140     }
141 }
142 // ...
143 ```
144
145 At compile time each implementation of `Trait` will produce a table containing
146 the various methods (and other items) related to the implementation.
147
148 This works fine, but when the method gains generic parameters, we can have a
149 problem.
150
151 Usually, generic parameters get _monomorphized_. For example, if I have
152
153 ```
154 fn foo<T>(x: T) {
155     // ...
156 }
157 ```
158
159 The machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
160 other type substitution is different. Hence the compiler generates the
161 implementation on-demand. If you call `foo()` with a `bool` parameter, the
162 compiler will only generate code for `foo::<bool>()`. When we have additional
163 type parameters, the number of monomorphized implementations the compiler
164 generates does not grow drastically, since the compiler will only generate an
165 implementation if the function is called with unparametrized substitutions
166 (i.e., substitutions where none of the substituted types are themselves
167 parametrized).
168
169 However, with trait objects we have to make a table containing _every_ object
170 that implements the trait. Now, if it has type parameters, we need to add
171 implementations for every type that implements the trait, and there could
172 theoretically be an infinite number of types.
173
174 For example, with:
175
176 ```
177 trait Trait {
178     fn foo<T>(&self, on: T);
179     // more methods
180 }
181
182 impl Trait for String {
183     fn foo<T>(&self, on: T) {
184         // implementation 1
185     }
186 }
187
188 impl Trait for u8 {
189     fn foo<T>(&self, on: T) {
190         // implementation 2
191     }
192 }
193
194 // 8 more implementations
195 ```
196
197 Now, if we have the following code:
198
199 ```ignore
200 fn call_foo(thing: Box<Trait>) {
201     thing.foo(true); // this could be any one of the 8 types above
202     thing.foo(1);
203     thing.foo("hello");
204 }
205 ```
206
207 We don't just need to create a table of all implementations of all methods of
208 `Trait`, we need to create such a table, for each different type fed to
209 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
210 types being fed to `foo()`) = 30 implementations!
211
212 With real world traits these numbers can grow drastically.
213
214 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
215 fix for the sub-error above if you do not intend to call the method with type
216 parameters:
217
218 ```
219 trait Trait {
220     fn foo<T>(&self, on: T) where Self: Sized;
221     // more methods
222 }
223 ```
224
225 If this is not an option, consider replacing the type parameter with another
226 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
227 of types you intend to feed to this method is limited, consider manually listing
228 out the methods of different types.
229
230 ### Method has no receiver
231
232 Methods that do not take a `self` parameter can't be called since there won't be
233 a way to get a pointer to the method table for them.
234
235 ```
236 trait Foo {
237     fn foo() -> u8;
238 }
239 ```
240
241 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
242 an implementation.
243
244 Adding a `Self: Sized` bound to these methods will generally make this compile.
245
246 ```
247 trait Foo {
248     fn foo() -> u8 where Self: Sized;
249 }
250 ```
251
252 ### The trait cannot use `Self` as a type parameter in the supertrait listing
253
254 This is similar to the second sub-error, but subtler. It happens in situations
255 like the following:
256
257 ```compile_fail
258 trait Super<A> {}
259
260 trait Trait: Super<Self> {
261 }
262
263 struct Foo;
264
265 impl Super<Foo> for Foo{}
266
267 impl Trait for Foo {}
268 ```
269
270 Here, the supertrait might have methods as follows:
271
272 ```
273 trait Super<A> {
274     fn get_a(&self) -> A; // note that this is object safe!
275 }
276 ```
277
278 If the trait `Foo` was deriving from something like `Super<String>` or
279 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
280 `get_a()` will definitely return an object of that type.
281
282 However, if it derives from `Super<Self>`, even though `Super` is object safe,
283 the method `get_a()` would return an object of unknown type when called on the
284 function. `Self` type parameters let us make object safe traits no longer safe,
285 so they are forbidden when specifying supertraits.
286
287 There's no easy fix for this, generally code will need to be refactored so that
288 you no longer need to derive from `Super<Self>`.
289 "##,
290
291 E0072: r##"
292 When defining a recursive struct or enum, any use of the type being defined
293 from inside the definition must occur behind a pointer (like `Box` or `&`).
294 This is because structs and enums must have a well-defined size, and without
295 the pointer the size of the type would need to be unbounded.
296
297 Consider the following erroneous definition of a type for a list of bytes:
298
299 ```compile_fail
300 // error, invalid recursive struct type
301 struct ListNode {
302     head: u8,
303     tail: Option<ListNode>,
304 }
305 ```
306
307 This type cannot have a well-defined size, because it needs to be arbitrarily
308 large (since we would be able to nest `ListNode`s to any depth). Specifically,
309
310 ```plain
311 size of `ListNode` = 1 byte for `head`
312                    + 1 byte for the discriminant of the `Option`
313                    + size of `ListNode`
314 ```
315
316 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
317
318 ```
319 struct ListNode {
320     head: u8,
321     tail: Option<Box<ListNode>>,
322 }
323 ```
324
325 This works because `Box` is a pointer, so its size is well-known.
326 "##,
327
328 E0109: r##"
329 You tried to give a type parameter to a type which doesn't need it. Erroneous
330 code example:
331
332 ```compile_fail
333 type X = u32<i32>; // error: type parameters are not allowed on this type
334 ```
335
336 Please check that you used the correct type and recheck its definition. Perhaps
337 it doesn't need the type parameter.
338
339 Example:
340
341 ```
342 type X = u32; // this compiles
343 ```
344
345 Note that type parameters for enum-variant constructors go after the variant,
346 not after the enum (Option::None::<u32>, not Option::<u32>::None).
347 "##,
348
349 E0110: r##"
350 You tried to give a lifetime parameter to a type which doesn't need it.
351 Erroneous code example:
352
353 ```compile_fail
354 type X = u32<'static>; // error: lifetime parameters are not allowed on
355                        //        this type
356 ```
357
358 Please check that the correct type was used and recheck its definition; perhaps
359 it doesn't need the lifetime parameter. Example:
360
361 ```
362 type X = u32; // ok!
363 ```
364 "##,
365
366 E0133: r##"
367 Using unsafe functionality is potentially dangerous and disallowed by safety
368 checks. Examples:
369
370 * Dereferencing raw pointers
371 * Calling functions via FFI
372 * Calling functions marked unsafe
373
374 These safety checks can be relaxed for a section of the code by wrapping the
375 unsafe instructions with an `unsafe` block. For instance:
376
377 ```
378 unsafe fn f() { return; }
379
380 fn main() {
381     unsafe { f(); }
382 }
383 ```
384
385 See also https://doc.rust-lang.org/book/unsafe.html
386 "##,
387
388 // This shouldn't really ever trigger since the repeated value error comes first
389 E0136: r##"
390 A binary can only have one entry point, and by default that entry point is the
391 function `main()`. If there are multiple such functions, please rename one.
392 "##,
393
394 E0137: r##"
395 This error indicates that the compiler found multiple functions with the
396 `#[main]` attribute. This is an error because there must be a unique entry
397 point into a Rust program.
398 "##,
399
400 E0138: r##"
401 This error indicates that the compiler found multiple functions with the
402 `#[start]` attribute. This is an error because there must be a unique entry
403 point into a Rust program.
404 "##,
405
406 // FIXME link this to the relevant turpl chapters for instilling fear of the
407 //       transmute gods in the user
408 E0139: r##"
409 There are various restrictions on transmuting between types in Rust; for example
410 types being transmuted must have the same size. To apply all these restrictions,
411 the compiler must know the exact types that may be transmuted. When type
412 parameters are involved, this cannot always be done.
413
414 So, for example, the following is not allowed:
415
416 ```compile_fail
417 struct Foo<T>(Vec<T>);
418
419 fn foo<T>(x: Vec<T>) {
420     // we are transmuting between Vec<T> and Foo<T> here
421     let y: Foo<T> = unsafe { transmute(x) };
422     // do something with y
423 }
424 ```
425
426 In this specific case there's a good chance that the transmute is harmless (but
427 this is not guaranteed by Rust). However, when alignment and enum optimizations
428 come into the picture, it's quite likely that the sizes may or may not match
429 with different type parameter substitutions. It's not possible to check this for
430 _all_ possible types, so `transmute()` simply only accepts types without any
431 unsubstituted type parameters.
432
433 If you need this, there's a good chance you're doing something wrong. Keep in
434 mind that Rust doesn't guarantee much about the layout of different structs
435 (even two structs with identical declarations may have different layouts). If
436 there is a solution that avoids the transmute entirely, try it instead.
437
438 If it's possible, hand-monomorphize the code by writing the function for each
439 possible type substitution. It's possible to use traits to do this cleanly,
440 for example:
441
442 ```ignore
443 struct Foo<T>(Vec<T>);
444
445 trait MyTransmutableType {
446     fn transmute(Vec<Self>) -> Foo<Self>;
447 }
448
449 impl MyTransmutableType for u8 {
450     fn transmute(x: Foo<u8>) -> Vec<u8> {
451         transmute(x)
452     }
453 }
454
455 impl MyTransmutableType for String {
456     fn transmute(x: Foo<String>) -> Vec<String> {
457         transmute(x)
458     }
459 }
460
461 // ... more impls for the types you intend to transmute
462
463 fn foo<T: MyTransmutableType>(x: Vec<T>) {
464     let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
465     // do something with y
466 }
467 ```
468
469 Each impl will be checked for a size match in the transmute as usual, and since
470 there are no unbound type parameters involved, this should compile unless there
471 is a size mismatch in one of the impls.
472
473 It is also possible to manually transmute:
474
475 ```ignore
476 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
477 ```
478
479 Note that this does not move `v` (unlike `transmute`), and may need a
480 call to `mem::forget(v)` in case you want to avoid destructors being called.
481 "##,
482
483 E0152: r##"
484 Lang items are already implemented in the standard library. Unless you are
485 writing a free-standing application (e.g. a kernel), you do not need to provide
486 them yourself.
487
488 You can build a free-standing crate by adding `#![no_std]` to the crate
489 attributes:
490
491 ```
492 #![no_std]
493 ```
494
495 See also https://doc.rust-lang.org/book/no-stdlib.html
496 "##,
497
498 E0229: r##"
499 An associated type binding was done outside of the type parameter declaration
500 and `where` clause. Erroneous code example:
501
502 ```compile_fail
503 pub trait Foo {
504     type A;
505     fn boo(&self) -> <Self as Foo>::A;
506 }
507
508 struct Bar;
509
510 impl Foo for isize {
511     type A = usize;
512     fn boo(&self) -> usize { 42 }
513 }
514
515 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
516 // error: associated type bindings are not allowed here
517 ```
518
519 To solve this error, please move the type bindings in the type parameter
520 declaration:
521
522 ```ignore
523 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
524 ```
525
526 Or in the `where` clause:
527
528 ```ignore
529 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
530 ```
531 "##,
532
533 E0261: r##"
534 When using a lifetime like `'a` in a type, it must be declared before being
535 used.
536
537 These two examples illustrate the problem:
538
539 ```compile_fail
540 // error, use of undeclared lifetime name `'a`
541 fn foo(x: &'a str) { }
542
543 struct Foo {
544     // error, use of undeclared lifetime name `'a`
545     x: &'a str,
546 }
547 ```
548
549 These can be fixed by declaring lifetime parameters:
550
551 ```
552 fn foo<'a>(x: &'a str) {}
553
554 struct Foo<'a> {
555     x: &'a str,
556 }
557 ```
558 "##,
559
560 E0262: r##"
561 Declaring certain lifetime names in parameters is disallowed. For example,
562 because the `'static` lifetime is a special built-in lifetime name denoting
563 the lifetime of the entire program, this is an error:
564
565 ```compile_fail
566 // error, invalid lifetime parameter name `'static`
567 fn foo<'static>(x: &'static str) { }
568 ```
569 "##,
570
571 E0263: r##"
572 A lifetime name cannot be declared more than once in the same scope. For
573 example:
574
575 ```compile_fail
576 // error, lifetime name `'a` declared twice in the same scope
577 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
578 ```
579 "##,
580
581 E0264: r##"
582 An unknown external lang item was used. Erroneous code example:
583
584 ```compile_fail
585 #![feature(lang_items)]
586
587 extern "C" {
588     #[lang = "cake"] // error: unknown external lang item: `cake`
589     fn cake();
590 }
591 ```
592
593 A list of available external lang items is available in
594 `src/librustc/middle/weak_lang_items.rs`. Example:
595
596 ```
597 #![feature(lang_items)]
598
599 extern "C" {
600     #[lang = "panic_fmt"] // ok!
601     fn cake();
602 }
603 ```
604 "##,
605
606 E0269: r##"
607 Functions must eventually return a value of their return type. For example, in
608 the following function:
609
610 ```compile_fail
611 fn foo(x: u8) -> u8 {
612     if x > 0 {
613         x // alternatively, `return x`
614     }
615     // nothing here
616 }
617 ```
618
619 If the condition is true, the value `x` is returned, but if the condition is
620 false, control exits the `if` block and reaches a place where nothing is being
621 returned. All possible control paths must eventually return a `u8`, which is not
622 happening here.
623
624 An easy fix for this in a complicated function is to specify a default return
625 value, if possible:
626
627 ```ignore
628 fn foo(x: u8) -> u8 {
629     if x > 0 {
630         x // alternatively, `return x`
631     }
632     // lots of other if branches
633     0 // return 0 if all else fails
634 }
635 ```
636
637 It is advisable to find out what the unhandled cases are and check for them,
638 returning an appropriate value or panicking if necessary.
639 "##,
640
641 E0270: r##"
642 Rust lets you define functions which are known to never return, i.e. are
643 'diverging', by marking its return type as `!`.
644
645 For example, the following functions never return:
646
647 ```no_run
648 fn foo() -> ! {
649     loop {}
650 }
651
652 fn bar() -> ! {
653     foo() // foo() is diverging, so this will diverge too
654 }
655
656 fn baz() -> ! {
657     panic!(); // this macro internally expands to a call to a diverging function
658 }
659 ```
660
661 Such functions can be used in a place where a value is expected without
662 returning a value of that type, for instance:
663
664 ```no_run
665 fn foo() -> ! {
666     loop {}
667 }
668
669 let x = 3;
670
671 let y = match x {
672     1 => 1,
673     2 => 4,
674     _ => foo() // diverging function called here
675 };
676
677 println!("{}", y)
678 ```
679
680 If the third arm of the match block is reached, since `foo()` doesn't ever
681 return control to the match block, it is fine to use it in a place where an
682 integer was expected. The `match` block will never finish executing, and any
683 point where `y` (like the print statement) is needed will not be reached.
684
685 However, if we had a diverging function that actually does finish execution:
686
687 ```ignore
688 fn foo() -> ! {
689     loop {break;}
690 }
691 ```
692
693 Then we would have an unknown value for `y` in the following code:
694
695 ```no_run
696 fn foo() -> ! {
697     loop {}
698 }
699
700 let x = 3;
701
702 let y = match x {
703     1 => 1,
704     2 => 4,
705     _ => foo()
706 };
707
708 println!("{}", y);
709 ```
710
711 In the previous example, the print statement was never reached when the
712 wildcard match arm was hit, so we were okay with `foo()` not returning an
713 integer that we could set to `y`. But in this example, `foo()` actually does
714 return control, so the print statement will be executed with an uninitialized
715 value.
716
717 Obviously we cannot have functions which are allowed to be used in such
718 positions and yet can return control. So, if you are defining a function that
719 returns `!`, make sure that there is no way for it to actually finish
720 executing.
721 "##,
722
723 E0271: r##"
724 This is because of a type mismatch between the associated type of some
725 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
726 and another type `U` that is required to be equal to `T::Bar`, but is not.
727 Examples follow.
728
729 Here is a basic example:
730
731 ```compile_fail
732 trait Trait { type AssociatedType; }
733
734 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
735     println!("in foo");
736 }
737
738 impl Trait for i8 { type AssociatedType = &'static str; }
739
740 foo(3_i8);
741 ```
742
743 Here is that same example again, with some explanatory comments:
744
745 ```ignore
746 trait Trait { type AssociatedType; }
747
748 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
749 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
750 //                        |            |
751 //         This says `foo` can         |
752 //           only be used with         |
753 //              some type that         |
754 //         implements `Trait`.         |
755 //                                     |
756 //                             This says not only must
757 //                             `T` be an impl of `Trait`
758 //                             but also that the impl
759 //                             must assign the type `u32`
760 //                             to the associated type.
761     println!("in foo");
762 }
763
764 impl Trait for i8 { type AssociatedType = &'static str; }
765 ~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 //      |                             |
767 // `i8` does have                     |
768 // implementation                     |
769 // of `Trait`...                      |
770 //                     ... but it is an implementation
771 //                     that assigns `&'static str` to
772 //                     the associated type.
773
774 foo(3_i8);
775 // Here, we invoke `foo` with an `i8`, which does not satisfy
776 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
777 // therefore the type-checker complains with this error code.
778 ```
779
780 Here is a more subtle instance of the same problem, that can
781 arise with for-loops in Rust:
782
783 ```compile_fail
784 let vs: Vec<i32> = vec![1, 2, 3, 4];
785 for v in &vs {
786     match v {
787         1 => {},
788         _ => {},
789     }
790 }
791 ```
792
793 The above fails because of an analogous type mismatch,
794 though may be harder to see. Again, here are some
795 explanatory comments for the same example:
796
797 ```ignore
798 {
799     let vs = vec![1, 2, 3, 4];
800
801     // `for`-loops use a protocol based on the `Iterator`
802     // trait. Each item yielded in a `for` loop has the
803     // type `Iterator::Item` -- that is, `Item` is the
804     // associated type of the concrete iterator impl.
805     for v in &vs {
806 //      ~    ~~~
807 //      |     |
808 //      |    We borrow `vs`, iterating over a sequence of
809 //      |    *references* of type `&Elem` (where `Elem` is
810 //      |    vector's element type). Thus, the associated
811 //      |    type `Item` must be a reference `&`-type ...
812 //      |
813 //  ... and `v` has the type `Iterator::Item`, as dictated by
814 //  the `for`-loop protocol ...
815
816         match v {
817             1 => {}
818 //          ~
819 //          |
820 // ... but *here*, `v` is forced to have some integral type;
821 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
822 // match the pattern `1` ...
823
824             _ => {}
825         }
826
827 // ... therefore, the compiler complains, because it sees
828 // an attempt to solve the equations
829 // `some integral-type` = type-of-`v`
830 //                      = `Iterator::Item`
831 //                      = `&Elem` (i.e. `some reference type`)
832 //
833 // which cannot possibly all be true.
834
835     }
836 }
837 ```
838
839 To avoid those issues, you have to make the types match correctly.
840 So we can fix the previous examples like this:
841
842 ```
843 // Basic Example:
844 trait Trait { type AssociatedType; }
845
846 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
847     println!("in foo");
848 }
849
850 impl Trait for i8 { type AssociatedType = &'static str; }
851
852 foo(3_i8);
853
854 // For-Loop Example:
855 let vs = vec![1, 2, 3, 4];
856 for v in &vs {
857     match v {
858         &1 => {}
859         _ => {}
860     }
861 }
862 ```
863 "##,
864
865 E0272: r##"
866 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
867 message for when a particular trait isn't implemented on a type placed in a
868 position that needs that trait. For example, when the following code is
869 compiled:
870
871 ```compile_fail
872 fn foo<T: Index<u8>>(x: T){}
873
874 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
875 trait Index<Idx> { /* ... */ }
876
877 foo(true); // `bool` does not implement `Index<u8>`
878 ```
879
880 There will be an error about `bool` not implementing `Index<u8>`, followed by a
881 note saying "the type `bool` cannot be indexed by `u8`".
882
883 As you can see, you can specify type parameters in curly braces for
884 substitution with the actual types (using the regular format string syntax) in
885 a given situation. Furthermore, `{Self}` will substitute to the type (in this
886 case, `bool`) that we tried to use.
887
888 This error appears when the curly braces contain an identifier which doesn't
889 match with any of the type parameters or the string `Self`. This might happen
890 if you misspelled a type parameter, or if you intended to use literal curly
891 braces. If it is the latter, escape the curly braces with a second curly brace
892 of the same type; e.g. a literal `{` is `{{`.
893 "##,
894
895 E0273: r##"
896 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
897 message for when a particular trait isn't implemented on a type placed in a
898 position that needs that trait. For example, when the following code is
899 compiled:
900
901 ```compile_fail
902 fn foo<T: Index<u8>>(x: T){}
903
904 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
905 trait Index<Idx> { /* ... */ }
906
907 foo(true); // `bool` does not implement `Index<u8>`
908 ```
909
910 there will be an error about `bool` not implementing `Index<u8>`, followed by a
911 note saying "the type `bool` cannot be indexed by `u8`".
912
913 As you can see, you can specify type parameters in curly braces for
914 substitution with the actual types (using the regular format string syntax) in
915 a given situation. Furthermore, `{Self}` will substitute to the type (in this
916 case, `bool`) that we tried to use.
917
918 This error appears when the curly braces do not contain an identifier. Please
919 add one of the same name as a type parameter. If you intended to use literal
920 braces, use `{{` and `}}` to escape them.
921 "##,
922
923 E0274: r##"
924 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
925 message for when a particular trait isn't implemented on a type placed in a
926 position that needs that trait. For example, when the following code is
927 compiled:
928
929 ```compile_fail
930 fn foo<T: Index<u8>>(x: T){}
931
932 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
933 trait Index<Idx> { /* ... */ }
934
935 foo(true); // `bool` does not implement `Index<u8>`
936 ```
937
938 there will be an error about `bool` not implementing `Index<u8>`, followed by a
939 note saying "the type `bool` cannot be indexed by `u8`".
940
941 For this to work, some note must be specified. An empty attribute will not do
942 anything, please remove the attribute or add some helpful note for users of the
943 trait.
944 "##,
945
946 E0275: r##"
947 This error occurs when there was a recursive trait requirement that overflowed
948 before it could be evaluated. Often this means that there is unbounded
949 recursion in resolving some type bounds.
950
951 For example, in the following code:
952
953 ```compile_fail
954 trait Foo {}
955
956 struct Bar<T>(T);
957
958 impl<T> Foo for T where Bar<T>: Foo {}
959 ```
960
961 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
962 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
963 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
964 clearly a recursive requirement that can't be resolved directly.
965
966 Consider changing your trait bounds so that they're less self-referential.
967 "##,
968
969 E0276: r##"
970 This error occurs when a bound in an implementation of a trait does not match
971 the bounds specified in the original trait. For example:
972
973 ```compile_fail
974 trait Foo {
975     fn foo<T>(x: T);
976 }
977
978 impl Foo for bool {
979     fn foo<T>(x: T) where T: Copy {}
980 }
981 ```
982
983 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
984 take any type `T`. However, in the `impl` for `bool`, we have added an extra
985 bound that `T` is `Copy`, which isn't compatible with the original trait.
986
987 Consider removing the bound from the method or adding the bound to the original
988 method definition in the trait.
989 "##,
990
991 E0277: r##"
992 You tried to use a type which doesn't implement some trait in a place which
993 expected that trait. Erroneous code example:
994
995 ```compile_fail
996 // here we declare the Foo trait with a bar method
997 trait Foo {
998     fn bar(&self);
999 }
1000
1001 // we now declare a function which takes an object implementing the Foo trait
1002 fn some_func<T: Foo>(foo: T) {
1003     foo.bar();
1004 }
1005
1006 fn main() {
1007     // we now call the method with the i32 type, which doesn't implement
1008     // the Foo trait
1009     some_func(5i32); // error: the trait `Foo` is not implemented for the
1010                      //        type `i32`
1011 }
1012 ```
1013
1014 In order to fix this error, verify that the type you're using does implement
1015 the trait. Example:
1016
1017 ```
1018 trait Foo {
1019     fn bar(&self);
1020 }
1021
1022 fn some_func<T: Foo>(foo: T) {
1023     foo.bar(); // we can now use this method since i32 implements the
1024                // Foo trait
1025 }
1026
1027 // we implement the trait on the i32 type
1028 impl Foo for i32 {
1029     fn bar(&self) {}
1030 }
1031
1032 fn main() {
1033     some_func(5i32); // ok!
1034 }
1035 ```
1036
1037 Or in a generic context, an erroneous code example would look like:
1038 ```compile_fail
1039 fn some_func<T>(foo: T) {
1040     println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1041                            //        implemented for the type `T`
1042 }
1043
1044 fn main() {
1045     // We now call the method with the i32 type,
1046     // which *does* implement the Debug trait.
1047     some_func(5i32);
1048 }
1049 ```
1050
1051 Note that the error here is in the definition of the generic function: Although
1052 we only call it with a parameter that does implement `Debug`, the compiler
1053 still rejects the function: It must work with all possible input types. In
1054 order to make this example compile, we need to restrict the generic type we're
1055 accepting:
1056 ```
1057 use std::fmt;
1058
1059 // Restrict the input type to types that implement Debug.
1060 fn some_func<T: fmt::Debug>(foo: T) {
1061     println!("{:?}", foo);
1062 }
1063
1064 fn main() {
1065     // Calling the method is still fine, as i32 implements Debug.
1066     some_func(5i32);
1067
1068     // This would fail to compile now:
1069     // struct WithoutDebug;
1070     // some_func(WithoutDebug);
1071 }
1072
1073 Rust only looks at the signature of the called function, as such it must
1074 already specify all requirements that will be used for every type parameter.
1075 ```
1076
1077 "##,
1078
1079 E0281: r##"
1080 You tried to supply a type which doesn't implement some trait in a location
1081 which expected that trait. This error typically occurs when working with
1082 `Fn`-based types. Erroneous code example:
1083
1084 ```compile_fail
1085 fn foo<F: Fn()>(x: F) { }
1086
1087 fn main() {
1088     // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1089     // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1090     // [E0281]
1091     foo(|y| { });
1092 }
1093 ```
1094
1095 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1096 arguments, but the closure we attempted to pass to it requires one argument.
1097 "##,
1098
1099 E0282: r##"
1100 This error indicates that type inference did not result in one unique possible
1101 type, and extra information is required. In most cases this can be provided
1102 by adding a type annotation. Sometimes you need to specify a generic type
1103 parameter manually.
1104
1105 A common example is the `collect` method on `Iterator`. It has a generic type
1106 parameter with a `FromIterator` bound, which for a `char` iterator is
1107 implemented by `Vec` and `String` among others. Consider the following snippet
1108 that reverses the characters of a string:
1109
1110 ```compile_fail
1111 let x = "hello".chars().rev().collect();
1112 ```
1113
1114 In this case, the compiler cannot infer what the type of `x` should be:
1115 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1116 use, you can use a type annotation on `x`:
1117
1118 ```
1119 let x: Vec<char> = "hello".chars().rev().collect();
1120 ```
1121
1122 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1123 the compiler can infer the rest:
1124
1125 ```
1126 let x: Vec<_> = "hello".chars().rev().collect();
1127 ```
1128
1129 Another way to provide the compiler with enough information, is to specify the
1130 generic type parameter:
1131
1132 ```
1133 let x = "hello".chars().rev().collect::<Vec<char>>();
1134 ```
1135
1136 Again, you need not specify the full type if the compiler can infer it:
1137
1138 ```
1139 let x = "hello".chars().rev().collect::<Vec<_>>();
1140 ```
1141
1142 Apart from a method or function with a generic type parameter, this error can
1143 occur when a type parameter of a struct or trait cannot be inferred. In that
1144 case it is not always possible to use a type annotation, because all candidates
1145 have the same return type. For instance:
1146
1147 ```compile_fail
1148 struct Foo<T> {
1149     num: T,
1150 }
1151
1152 impl<T> Foo<T> {
1153     fn bar() -> i32 {
1154         0
1155     }
1156
1157     fn baz() {
1158         let number = Foo::bar();
1159     }
1160 }
1161 ```
1162
1163 This will fail because the compiler does not know which instance of `Foo` to
1164 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1165 "##,
1166
1167 E0283: r##"
1168 This error occurs when the compiler doesn't have enough information
1169 to unambiguously choose an implementation.
1170
1171 For example:
1172
1173 ```compile_fail
1174 trait Generator {
1175     fn create() -> u32;
1176 }
1177
1178 struct Impl;
1179
1180 impl Generator for Impl {
1181     fn create() -> u32 { 1 }
1182 }
1183
1184 struct AnotherImpl;
1185
1186 impl Generator for AnotherImpl {
1187     fn create() -> u32 { 2 }
1188 }
1189
1190 fn main() {
1191     let cont: u32 = Generator::create();
1192     // error, impossible to choose one of Generator trait implementation
1193     // Impl or AnotherImpl? Maybe anything else?
1194 }
1195 ```
1196
1197 To resolve this error use the concrete type:
1198
1199 ```
1200 trait Generator {
1201     fn create() -> u32;
1202 }
1203
1204 struct AnotherImpl;
1205
1206 impl Generator for AnotherImpl {
1207     fn create() -> u32 { 2 }
1208 }
1209
1210 fn main() {
1211     let gen1 = AnotherImpl::create();
1212
1213     // if there are multiple methods with same name (different traits)
1214     let gen2 = <AnotherImpl as Generator>::create();
1215 }
1216 ```
1217 "##,
1218
1219 E0296: r##"
1220 This error indicates that the given recursion limit could not be parsed. Ensure
1221 that the value provided is a positive integer between quotes, like so:
1222
1223 ```
1224 #![recursion_limit="1000"]
1225 ```
1226 "##,
1227
1228 E0308: r##"
1229 This error occurs when the compiler was unable to infer the concrete type of a
1230 variable. It can occur for several cases, the most common of which is a
1231 mismatch in the expected type that the compiler inferred for a variable's
1232 initializing expression, and the actual type explicitly assigned to the
1233 variable.
1234
1235 For example:
1236
1237 ```compile_fail
1238 let x: i32 = "I am not a number!";
1239 //     ~~~   ~~~~~~~~~~~~~~~~~~~~
1240 //      |             |
1241 //      |    initializing expression;
1242 //      |    compiler infers type `&str`
1243 //      |
1244 //    type `i32` assigned to variable `x`
1245 ```
1246
1247 Another situation in which this occurs is when you attempt to use the `try!`
1248 macro inside a function that does not return a `Result<T, E>`:
1249
1250 ```compile_fail
1251 use std::fs::File;
1252
1253 fn main() {
1254     let mut f = try!(File::create("foo.txt"));
1255 }
1256 ```
1257
1258 This code gives an error like this:
1259
1260 ```text
1261 <std macros>:5:8: 6:42 error: mismatched types:
1262  expected `()`,
1263      found `core::result::Result<_, _>`
1264  (expected (),
1265      found enum `core::result::Result`) [E0308]
1266 ```
1267
1268 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1269 `()` as its return type, hence the error.
1270 "##,
1271
1272 E0309: r##"
1273 Types in type definitions have lifetimes associated with them that represent
1274 how long the data stored within them is guaranteed to be live. This lifetime
1275 must be as long as the data needs to be alive, and missing the constraint that
1276 denotes this will cause this error.
1277
1278 ```compile_fail
1279 // This won't compile because T is not constrained, meaning the data
1280 // stored in it is not guaranteed to last as long as the reference
1281 struct Foo<'a, T> {
1282     foo: &'a T
1283 }
1284 ```
1285
1286 This will compile, because it has the constraint on the type parameter:
1287
1288 ```
1289 struct Foo<'a, T: 'a> {
1290     foo: &'a T
1291 }
1292 ```
1293 "##,
1294
1295 E0310: r##"
1296 Types in type definitions have lifetimes associated with them that represent
1297 how long the data stored within them is guaranteed to be live. This lifetime
1298 must be as long as the data needs to be alive, and missing the constraint that
1299 denotes this will cause this error.
1300
1301 ```compile_fail
1302 // This won't compile because T is not constrained to the static lifetime
1303 // the reference needs
1304 struct Foo<T> {
1305     foo: &'static T
1306 }
1307
1308 This will compile, because it has the constraint on the type parameter:
1309
1310 ```
1311 struct Foo<T: 'static> {
1312     foo: &'static T
1313 }
1314 ```
1315 "##,
1316
1317 E0398: r##"
1318 In Rust 1.3, the default object lifetime bounds are expected to change, as
1319 described in RFC #1156 [1]. You are getting a warning because the compiler
1320 thinks it is possible that this change will cause a compilation error in your
1321 code. It is possible, though unlikely, that this is a false alarm.
1322
1323 The heart of the change is that where `&'a Box<SomeTrait>` used to default to
1324 `&'a Box<SomeTrait+'a>`, it now defaults to `&'a Box<SomeTrait+'static>` (here,
1325 `SomeTrait` is the name of some trait type). Note that the only types which are
1326 affected are references to boxes, like `&Box<SomeTrait>` or
1327 `&[Box<SomeTrait>]`. More common types like `&SomeTrait` or `Box<SomeTrait>`
1328 are unaffected.
1329
1330 To silence this warning, edit your code to use an explicit bound. Most of the
1331 time, this means that you will want to change the signature of a function that
1332 you are calling. For example, if the error is reported on a call like `foo(x)`,
1333 and `foo` is defined as follows:
1334
1335 ```ignore
1336 fn foo(arg: &Box<SomeTrait>) { ... }
1337 ```
1338
1339 You might change it to:
1340
1341 ```ignore
1342 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1343 ```
1344
1345 This explicitly states that you expect the trait object `SomeTrait` to contain
1346 references (with a maximum lifetime of `'a`).
1347
1348 [1]: https://github.com/rust-lang/rfcs/pull/1156
1349 "##,
1350
1351 E0452: r##"
1352 An invalid lint attribute has been given. Erroneous code example:
1353
1354 ```compile_fail
1355 #![allow(foo = "")] // error: malformed lint attribute
1356 ```
1357
1358 Lint attributes only accept a list of identifiers (where each identifier is a
1359 lint name). Ensure the attribute is of this form:
1360
1361 ```
1362 #![allow(foo)] // ok!
1363 // or:
1364 #![allow(foo, foo2)] // ok!
1365 ```
1366 "##,
1367
1368 E0496: r##"
1369 A lifetime name is shadowing another lifetime name. Erroneous code example:
1370
1371 ```compile_fail
1372 struct Foo<'a> {
1373     a: &'a i32,
1374 }
1375
1376 impl<'a> Foo<'a> {
1377     fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1378                            //        name that is already in scope
1379     }
1380 }
1381 ```
1382
1383 Please change the name of one of the lifetimes to remove this error. Example:
1384
1385 ```
1386 struct Foo<'a> {
1387     a: &'a i32,
1388 }
1389
1390 impl<'a> Foo<'a> {
1391     fn f<'b>(x: &'b i32) { // ok!
1392     }
1393 }
1394
1395 fn main() {
1396 }
1397 ```
1398 "##,
1399
1400 E0497: r##"
1401 A stability attribute was used outside of the standard library. Erroneous code
1402 example:
1403
1404 ```compile_fail
1405 #[stable] // error: stability attributes may not be used outside of the
1406           //        standard library
1407 fn foo() {}
1408 ```
1409
1410 It is not possible to use stability attributes outside of the standard library.
1411 Also, for now, it is not possible to write deprecation messages either.
1412 "##,
1413
1414 E0517: r##"
1415 This error indicates that a `#[repr(..)]` attribute was placed on an
1416 unsupported item.
1417
1418 Examples of erroneous code:
1419
1420 ```compile_fail
1421 #[repr(C)]
1422 type Foo = u8;
1423
1424 #[repr(packed)]
1425 enum Foo {Bar, Baz}
1426
1427 #[repr(u8)]
1428 struct Foo {bar: bool, baz: bool}
1429
1430 #[repr(C)]
1431 impl Foo {
1432     // ...
1433 }
1434 ```
1435
1436 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1437 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1438 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1439
1440 These attributes do not work on typedefs, since typedefs are just aliases.
1441
1442 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1443 discriminant size for C-like enums (when there is no associated data, e.g.
1444 `enum Color {Red, Blue, Green}`), effectively setting the size of the enum to
1445 the size of the provided type. Such an enum can be cast to a value of the same
1446 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1447 with a constrained set of allowed values.
1448
1449 Only C-like enums can be cast to numerical primitives, so this attribute will
1450 not apply to structs.
1451
1452 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1453 representation of enums isn't strictly defined in Rust, and this attribute
1454 won't work on enums.
1455
1456 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
1457 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1458 SIMD. This doesn't make much sense for enums since they don't consist of a
1459 single list of data.
1460 "##,
1461
1462 E0518: r##"
1463 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1464 on something other than a function or method.
1465
1466 Examples of erroneous code:
1467
1468 ```compile_fail
1469 #[inline(always)]
1470 struct Foo;
1471
1472 #[inline(never)]
1473 impl Foo {
1474     // ...
1475 }
1476 ```
1477
1478 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1479 function. By default, the compiler does a pretty good job of figuring this out
1480 itself, but if you feel the need for annotations, `#[inline(always)]` and
1481 `#[inline(never)]` can override or force the compiler's decision.
1482
1483 If you wish to apply this attribute to all methods in an impl, manually annotate
1484 each method; it is not possible to annotate the entire impl with an `#[inline]`
1485 attribute.
1486 "##,
1487
1488 E0522: r##"
1489 The lang attribute is intended for marking special items that are built-in to
1490 Rust itself. This includes special traits (like `Copy` and `Sized`) that affect
1491 how the compiler behaves, as well as special functions that may be automatically
1492 invoked (such as the handler for out-of-bounds accesses when indexing a slice).
1493 Erroneous code example:
1494
1495 ```compile_fail
1496 #![feature(lang_items)]
1497
1498 #[lang = "cookie"]
1499 fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
1500     loop {}
1501 }
1502 ```
1503 "##,
1504
1505 }
1506
1507
1508 register_diagnostics! {
1509 //  E0006 // merged with E0005
1510 //  E0134,
1511 //  E0135,
1512     E0278, // requirement is not satisfied
1513     E0279, // requirement is not satisfied
1514     E0280, // requirement is not satisfied
1515     E0284, // cannot resolve type
1516 //  E0285, // overflow evaluation builtin bounds
1517 //  E0300, // unexpanded macro
1518 //  E0304, // expected signed integer constant
1519 //  E0305, // expected constant
1520     E0311, // thing may not live long enough
1521     E0312, // lifetime of reference outlives lifetime of borrowed content
1522     E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1523     E0314, // closure outlives stack frame
1524     E0315, // cannot invoke closure outside of its lifetime
1525     E0316, // nested quantification of lifetimes
1526     E0453, // overruled by outer forbid
1527     E0473, // dereference of reference outside its lifetime
1528     E0474, // captured variable `..` does not outlive the enclosing closure
1529     E0475, // index of slice outside its lifetime
1530     E0476, // lifetime of the source pointer does not outlive lifetime bound...
1531     E0477, // the type `..` does not fulfill the required lifetime...
1532     E0478, // lifetime bound not satisfied
1533     E0479, // the type `..` (provided as the value of a type parameter) is...
1534     E0480, // lifetime of method receiver does not outlive the method call
1535     E0481, // lifetime of function argument does not outlive the function call
1536     E0482, // lifetime of return value does not outlive the function call
1537     E0483, // lifetime of operand does not outlive the operation
1538     E0484, // reference is not valid at the time of borrow
1539     E0485, // automatically reference is not valid at the time of borrow
1540     E0486, // type of expression contains references that are not valid during...
1541     E0487, // unsafe use of destructor: destructor might be called while...
1542     E0488, // lifetime of variable does not enclose its declaration
1543     E0489, // type/lifetime parameter not in scope here
1544     E0490, // a value of type `..` is borrowed for too long
1545     E0491, // in type `..`, reference has a longer lifetime than the data it...
1546     E0495, // cannot infer an appropriate lifetime due to conflicting requirements
1547 }