]> git.lizzy.rs Git - rust.git/blob - src/librustc/diagnostics.rs
use a newtype for the variant discriminant instead of u64
[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
18 E0001: r##"
19 This error suggests that the expression arm corresponding to the noted pattern
20 will never be reached as for all possible values of the expression being
21 matched, one of the preceding patterns will match.
22
23 This means that perhaps some of the preceding patterns are too general, this one
24 is too specific or the ordering is incorrect.
25
26 For example, the following `match` block has too many arms:
27
28 ```
29 match foo {
30     Some(bar) => {/* ... */}
31     None => {/* ... */}
32     _ => {/* ... */} // All possible cases have already been handled
33 }
34 ```
35
36 `match` blocks have their patterns matched in order, so, for example, putting
37 a wildcard arm above a more specific arm will make the latter arm irrelevant.
38
39 Ensure the ordering of the match arm is correct and remove any superfluous
40 arms.
41 "##,
42
43 E0002: r##"
44 This error indicates that an empty match expression is invalid because the type
45 it is matching on is non-empty (there exist values of this type). In safe code
46 it is impossible to create an instance of an empty type, so empty match
47 expressions are almost never desired. This error is typically fixed by adding
48 one or more cases to the match expression.
49
50 An example of an empty type is `enum Empty { }`. So, the following will work:
51
52 ```
53 fn foo(x: Empty) {
54     match x {
55         // empty
56     }
57 }
58 ```
59
60 However, this won't:
61
62 ```
63 fn foo(x: Option<String>) {
64     match x {
65         // empty
66     }
67 }
68 ```
69 "##,
70
71 E0003: r##"
72 Not-a-Number (NaN) values cannot be compared for equality and hence can never
73 match the input to a match expression. So, the following will not compile:
74
75 ```
76 const NAN: f32 = 0.0 / 0.0;
77
78 match number {
79     NAN => { /* ... */ },
80     // ...
81 }
82 ```
83
84 To match against NaN values, you should instead use the `is_nan()` method in a
85 guard, like so:
86
87 ```
88 match number {
89     // ...
90     x if x.is_nan() => { /* ... */ }
91     // ...
92 }
93 ```
94 "##,
95
96 E0004: r##"
97 This error indicates that the compiler cannot guarantee a matching pattern for
98 one or more possible inputs to a match expression. Guaranteed matches are
99 required in order to assign values to match expressions, or alternatively,
100 determine the flow of execution.
101
102 If you encounter this error you must alter your patterns so that every possible
103 value of the input type is matched. For types with a small number of variants
104 (like enums) you should probably cover all cases explicitly. Alternatively, the
105 underscore `_` wildcard pattern can be added after all other patterns to match
106 "anything else".
107 "##,
108
109 E0005: r##"
110 Patterns used to bind names must be irrefutable, that is, they must guarantee
111 that a name will be extracted in all cases. If you encounter this error you
112 probably need to use a `match` or `if let` to deal with the possibility of
113 failure.
114 "##,
115
116 E0007: r##"
117 This error indicates that the bindings in a match arm would require a value to
118 be moved into more than one location, thus violating unique ownership. Code like
119 the following is invalid as it requires the entire `Option<String>` to be moved
120 into a variable called `op_string` while simultaneously requiring the inner
121 String to be moved into a variable called `s`.
122
123 ```
124 let x = Some("s".to_string());
125 match x {
126     op_string @ Some(s) => ...
127     None => ...
128 }
129 ```
130
131 See also Error 303.
132 "##,
133
134 E0008: r##"
135 Names bound in match arms retain their type in pattern guards. As such, if a
136 name is bound by move in a pattern, it should also be moved to wherever it is
137 referenced in the pattern guard code. Doing so however would prevent the name
138 from being available in the body of the match arm. Consider the following:
139
140 ```
141 match Some("hi".to_string()) {
142     Some(s) if s.len() == 0 => // use s.
143     ...
144 }
145 ```
146
147 The variable `s` has type `String`, and its use in the guard is as a variable of
148 type `String`. The guard code effectively executes in a separate scope to the
149 body of the arm, so the value would be moved into this anonymous scope and
150 therefore become unavailable in the body of the arm. Although this example seems
151 innocuous, the problem is most clear when considering functions that take their
152 argument by value.
153
154 ```
155 match Some("hi".to_string()) {
156     Some(s) if { drop(s); false } => (),
157     Some(s) => // use s.
158     ...
159 }
160 ```
161
162 The value would be dropped in the guard then become unavailable not only in the
163 body of that arm but also in all subsequent arms! The solution is to bind by
164 reference when using guards or refactor the entire expression, perhaps by
165 putting the condition inside the body of the arm.
166 "##,
167
168 E0009: r##"
169 In a pattern, all values that don't implement the `Copy` trait have to be bound
170 the same way. The goal here is to avoid binding simultaneously by-move and
171 by-ref.
172
173 This limitation may be removed in a future version of Rust.
174
175 Wrong example:
176
177 ```
178 struct X { x: (), }
179
180 let x = Some((X { x: () }, X { x: () }));
181 match x {
182     Some((y, ref z)) => {},
183     None => panic!()
184 }
185 ```
186
187 You have two solutions:
188
189 Solution #1: Bind the pattern's values the same way.
190
191 ```
192 struct X { x: (), }
193
194 let x = Some((X { x: () }, X { x: () }));
195 match x {
196     Some((ref y, ref z)) => {},
197     // or Some((y, z)) => {}
198     None => panic!()
199 }
200 ```
201
202 Solution #2: Implement the `Copy` trait for the `X` structure.
203
204 However, please keep in mind that the first solution should be preferred.
205
206 ```
207 #[derive(Clone, Copy)]
208 struct X { x: (), }
209
210 let x = Some((X { x: () }, X { x: () }));
211 match x {
212     Some((y, ref z)) => {},
213     None => panic!()
214 }
215 ```
216 "##,
217
218 E0010: r##"
219 The value of statics and constants must be known at compile time, and they live
220 for the entire lifetime of a program. Creating a boxed value allocates memory on
221 the heap at runtime, and therefore cannot be done at compile time. Erroneous
222 code example:
223
224 ```
225 #![feature(box_syntax)]
226
227 const CON : Box<i32> = box 0;
228 ```
229 "##,
230
231 E0011: r##"
232 Initializers for constants and statics are evaluated at compile time.
233 User-defined operators rely on user-defined functions, which cannot be evaluated
234 at compile time.
235
236 Bad example:
237
238 ```
239 use std::ops::Index;
240
241 struct Foo { a: u8 }
242
243 impl Index<u8> for Foo {
244     type Output = u8;
245
246     fn index<'a>(&'a self, idx: u8) -> &'a u8 { &self.a }
247 }
248
249 const a: Foo = Foo { a: 0u8 };
250 const b: u8 = a[0]; // Index trait is defined by the user, bad!
251 ```
252
253 Only operators on builtin types are allowed.
254
255 Example:
256
257 ```
258 const a: &'static [i32] = &[1, 2, 3];
259 const b: i32 = a[0]; // Good!
260 ```
261 "##,
262
263 E0013: r##"
264 Static and const variables can refer to other const variables. But a const
265 variable cannot refer to a static variable. For example, `Y` cannot refer to `X`
266 here:
267
268 ```
269 static X: i32 = 42;
270 const Y: i32 = X;
271 ```
272
273 To fix this, the value can be extracted as a const and then used:
274
275 ```
276 const A: i32 = 42;
277 static X: i32 = A;
278 const Y: i32 = A;
279 ```
280 "##,
281
282 E0014: r##"
283 Constants can only be initialized by a constant value or, in a future
284 version of Rust, a call to a const function. This error indicates the use
285 of a path (like a::b, or x) denoting something other than one of these
286 allowed items. Example:
287
288 ```
289 const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
290 ```
291
292 To avoid it, you have to replace the non-constant value:
293
294 ```
295 const FOO: i32 = { const X : i32 = 0; X };
296 // or even:
297 const FOO: i32 = { 0 }; // but brackets are useless here
298 ```
299 "##,
300
301 // FIXME(#24111) Change the language here when const fn stabilizes
302 E0015: r##"
303 The only functions that can be called in static or constant expressions are
304 `const` functions, and struct/enum constructors. `const` functions are only
305 available on a nightly compiler. Rust currently does not support more general
306 compile-time function execution.
307
308 ```
309 const FOO: Option<u8> = Some(1); // enum constructor
310 struct Bar {x: u8}
311 const BAR: Bar = Bar {x: 1}; // struct constructor
312 ```
313
314 See [RFC 911] for more details on the design of `const fn`s.
315
316 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
317 "##,
318
319 E0017: r##"
320 References in statics and constants may only refer to immutable values. Example:
321
322 ```
323 static X: i32 = 1;
324 const C: i32 = 2;
325
326 // these three are not allowed:
327 const CR: &'static mut i32 = &mut C;
328 static STATIC_REF: &'static mut i32 = &mut X;
329 static CONST_REF: &'static mut i32 = &mut C;
330 ```
331
332 Statics are shared everywhere, and if they refer to mutable data one might
333 violate memory safety since holding multiple mutable references to shared data
334 is not allowed.
335
336 If you really want global mutable state, try using `static mut` or a global
337 `UnsafeCell`.
338 "##,
339
340 E0018: r##"
341 The value of static and const variables must be known at compile time. You
342 can't cast a pointer as an integer because we can't know what value the
343 address will take.
344
345 However, pointers to other constants' addresses are allowed in constants,
346 example:
347
348 ```
349 const X: u32 = 50;
350 const Y: *const u32 = &X;
351 ```
352
353 Therefore, casting one of these non-constant pointers to an integer results
354 in a non-constant integer which lead to this error. Example:
355
356 ```
357 const X: u32 = 1;
358 const Y: usize = &X as *const u32 as usize;
359 println!("{}", Y);
360 ```
361 "##,
362
363 E0019: r##"
364 A function call isn't allowed in the const's initialization expression
365 because the expression's value must be known at compile-time. Example of
366 erroneous code:
367
368 ```
369 enum Test {
370     V1
371 }
372
373 impl Test {
374     fn test(&self) -> i32 {
375         12
376     }
377 }
378
379 fn main() {
380     const FOO: Test = Test::V1;
381
382     const A: i32 = FOO.test(); // You can't call Test::func() here !
383 }
384 ```
385
386 Remember: you can't use a function call inside a const's initialization
387 expression! However, you can totally use it anywhere else:
388
389 ```
390 fn main() {
391     const FOO: Test = Test::V1;
392
393     FOO.func(); // here is good
394     let x = FOO.func(); // or even here!
395 }
396 ```
397 "##,
398
399 E0020: r##"
400 This error indicates that an attempt was made to divide by zero (or take the
401 remainder of a zero divisor) in a static or constant expression. Erroneous
402 code example:
403
404 ```
405 const X: i32 = 42 / 0;
406 // error: attempted to divide by zero in a constant expression
407 ```
408 "##,
409
410 E0030: r##"
411 When matching against a range, the compiler verifies that the range is
412 non-empty.  Range patterns include both end-points, so this is equivalent to
413 requiring the start of the range to be less than or equal to the end of the
414 range.
415
416 For example:
417
418 ```
419 match 5u32 {
420     // This range is ok, albeit pointless.
421     1 ... 1 => ...
422     // This range is empty, and the compiler can tell.
423     1000 ... 5 => ...
424 }
425 ```
426 "##,
427
428 E0038: r####"
429 Trait objects like `Box<Trait>` can only be constructed when certain
430 requirements are satisfied by the trait in question.
431
432 Trait objects are a form of dynamic dispatch and use a dynamically sized type
433 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
434 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
435 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
436 (among other things) for dynamic dispatch. This design mandates some
437 restrictions on the types of traits that are allowed to be used in trait
438 objects, which are collectively termed as 'object safety' rules.
439
440 Attempting to create a trait object for a non object-safe trait will trigger
441 this error.
442
443 There are various rules:
444
445 ### The trait cannot require `Self: Sized`
446
447 When `Trait` is treated as a type, the type does not implement the special
448 `Sized` trait, because the type does not have a known size at compile time and
449 can only be accessed behind a pointer. Thus, if we have a trait like the
450 following:
451
452 ```
453 trait Foo where Self: Sized {
454
455 }
456 ```
457
458 we cannot create an object of type `Box<Foo>` or `&Foo` since in this case
459 `Self` would not be `Sized`.
460
461 Generally, `Self : Sized` is used to indicate that the trait should not be used
462 as a trait object. If the trait comes from your own crate, consider removing
463 this restriction.
464
465 ### Method references the `Self` type in its arguments or return type
466
467 This happens when a trait has a method like the following:
468
469 ```
470 trait Trait {
471     fn foo(&self) -> Self;
472 }
473
474 impl Trait for String {
475     fn foo(&self) -> Self {
476         "hi".to_owned()
477     }
478 }
479
480 impl Trait for u8 {
481     fn foo(&self) -> Self {
482         1
483     }
484 }
485 ```
486
487 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
488 cause this problem)
489
490 In such a case, the compiler cannot predict the return type of `foo()` in a
491 situation like the following:
492
493 ```
494 fn call_foo(x: Box<Trait>) {
495     let y = x.foo(); // What type is y?
496     // ...
497 }
498 ```
499
500 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
501 on them to mark them as explicitly unavailable to trait objects. The
502 functionality will still be available to all other implementers, including
503 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
504
505 ```
506 trait Trait {
507     fn foo(&self) -> Self where Self: Sized;
508     // more functions
509 }
510 ```
511
512 Now, `foo()` can no longer be called on a trait object, but you will now be
513 allowed to make a trait object, and that will be able to call any object-safe
514 methods". With such a bound, one can still call `foo()` on types implementing
515 that trait that aren't behind trait objects.
516
517 ### Method has generic type parameters
518
519 As mentioned before, trait objects contain pointers to method tables. So, if we
520 have:
521
522 ```
523 trait Trait {
524     fn foo(&self);
525 }
526 impl Trait for String {
527     fn foo(&self) {
528         // implementation 1
529     }
530 }
531 impl Trait for u8 {
532     fn foo(&self) {
533         // implementation 2
534     }
535 }
536 // ...
537 ```
538
539 At compile time each implementation of `Trait` will produce a table containing
540 the various methods (and other items) related to the implementation.
541
542 This works fine, but when the method gains generic parameters, we can have a
543 problem.
544
545 Usually, generic parameters get _monomorphized_. For example, if I have
546
547 ```
548 fn foo<T>(x: T) {
549     // ...
550 }
551 ```
552
553 the machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
554 other type substitution is different. Hence the compiler generates the
555 implementation on-demand. If you call `foo()` with a `bool` parameter, the
556 compiler will only generate code for `foo::<bool>()`. When we have additional
557 type parameters, the number of monomorphized implementations the compiler
558 generates does not grow drastically, since the compiler will only generate an
559 implementation if the function is called with unparametrized substitutions
560 (i.e., substitutions where none of the substituted types are themselves
561 parametrized).
562
563 However, with trait objects we have to make a table containing _every_ object
564 that implements the trait. Now, if it has type parameters, we need to add
565 implementations for every type that implements the trait, and there could
566 theoretically be an infinite number of types.
567
568 For example, with:
569
570 ```
571 trait Trait {
572     fn foo<T>(&self, on: T);
573     // more methods
574 }
575 impl Trait for String {
576     fn foo<T>(&self, on: T) {
577         // implementation 1
578     }
579 }
580 impl Trait for u8 {
581     fn foo<T>(&self, on: T) {
582         // implementation 2
583     }
584 }
585 // 8 more implementations
586 ```
587
588 Now, if we have the following code:
589
590 ```
591 fn call_foo(thing: Box<Trait>) {
592     thing.foo(true); // this could be any one of the 8 types above
593     thing.foo(1);
594     thing.foo("hello");
595 }
596 ```
597
598 we don't just need to create a table of all implementations of all methods of
599 `Trait`, we need to create such a table, for each different type fed to
600 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
601 types being fed to `foo()`) = 30 implementations!
602
603 With real world traits these numbers can grow drastically.
604
605 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
606 fix for the sub-error above if you do not intend to call the method with type
607 parameters:
608
609 ```
610 trait Trait {
611     fn foo<T>(&self, on: T) where Self: Sized;
612     // more methods
613 }
614 ```
615
616 If this is not an option, consider replacing the type parameter with another
617 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
618 of types you intend to feed to this method is limited, consider manually listing
619 out the methods of different types.
620
621 ### Method has no receiver
622
623 Methods that do not take a `self` parameter can't be called since there won't be
624 a way to get a pointer to the method table for them
625
626 ```
627 trait Foo {
628     fn foo() -> u8;
629 }
630 ```
631
632 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
633 an implementation.
634
635 Adding a `Self: Sized` bound to these methods will generally make this compile.
636
637 ```
638 trait Foo {
639     fn foo() -> u8 where Self: Sized;
640 }
641 ```
642
643 ### The trait cannot use `Self` as a type parameter in the supertrait listing
644
645 This is similar to the second sub-error, but subtler. It happens in situations
646 like the following:
647
648 ```
649 trait Super<A> {}
650
651 trait Trait: Super<Self> {
652 }
653
654 struct Foo;
655
656 impl Super<Foo> for Foo{}
657
658 impl Trait for Foo {}
659 ```
660
661 Here, the supertrait might have methods as follows:
662
663 ```
664 trait Super<A> {
665     fn get_a(&self) -> A; // note that this is object safe!
666 }
667 ```
668
669 If the trait `Foo` was deriving from something like `Super<String>` or
670 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
671 `get_a()` will definitely return an object of that type.
672
673 However, if it derives from `Super<Self>`, even though `Super` is object safe,
674 the method `get_a()` would return an object of unknown type when called on the
675 function. `Self` type parameters let us make object safe traits no longer safe,
676 so they are forbidden when specifying supertraits.
677
678 There's no easy fix for this, generally code will need to be refactored so that
679 you no longer need to derive from `Super<Self>`.
680 "####,
681
682 E0109: r##"
683 You tried to give a type parameter to a type which doesn't need it. Erroneous
684 code example:
685
686 ```
687 type X = u32<i32>; // error: type parameters are not allowed on this type
688 ```
689
690 Please check that you used the correct type and recheck its definition. Perhaps
691 it doesn't need the type parameter.
692
693 Example:
694
695 ```
696 type X = u32; // this compiles
697 ```
698
699 Note that type parameters for enum-variant constructors go after the variant,
700 not after the enum (Option::None::<u32>, not Option::<u32>::None).
701 "##,
702
703 E0110: r##"
704 You tried to give a lifetime parameter to a type which doesn't need it.
705 Erroneous code example:
706
707 ```
708 type X = u32<'static>; // error: lifetime parameters are not allowed on
709                        //        this type
710 ```
711
712 Please check that the correct type was used and recheck its definition; perhaps
713 it doesn't need the lifetime parameter. Example:
714
715 ```
716 type X = u32; // ok!
717 ```
718 "##,
719
720 E0133: r##"
721 Using unsafe functionality, is potentially dangerous and disallowed
722 by safety checks. Examples:
723
724 - Dereferencing raw pointers
725 - Calling functions via FFI
726 - Calling functions marked unsafe
727
728 These safety checks can be relaxed for a section of the code
729 by wrapping the unsafe instructions with an `unsafe` block. For instance:
730
731 ```
732 unsafe fn f() { return; }
733
734 fn main() {
735     unsafe { f(); }
736 }
737 ```
738
739 See also https://doc.rust-lang.org/book/unsafe.html
740 "##,
741
742 // This shouldn't really ever trigger since the repeated value error comes first
743 E0136: r##"
744 A binary can only have one entry point, and by default that entry point is the
745 function `main()`. If there are multiple such functions, please rename one.
746 "##,
747
748 E0137: r##"
749 This error indicates that the compiler found multiple functions with the
750 `#[main]` attribute. This is an error because there must be a unique entry
751 point into a Rust program.
752 "##,
753
754 E0138: r##"
755 This error indicates that the compiler found multiple functions with the
756 `#[start]` attribute. This is an error because there must be a unique entry
757 point into a Rust program.
758 "##,
759
760 // FIXME link this to the relevant turpl chapters for instilling fear of the
761 //       transmute gods in the user
762 E0139: r##"
763 There are various restrictions on transmuting between types in Rust; for example
764 types being transmuted must have the same size. To apply all these restrictions,
765 the compiler must know the exact types that may be transmuted. When type
766 parameters are involved, this cannot always be done.
767
768 So, for example, the following is not allowed:
769
770 ```
771 struct Foo<T>(Vec<T>)
772
773 fn foo<T>(x: Vec<T>) {
774     // we are transmuting between Vec<T> and Foo<T> here
775     let y: Foo<T> = unsafe { transmute(x) };
776     // do something with y
777 }
778 ```
779
780 In this specific case there's a good chance that the transmute is harmless (but
781 this is not guaranteed by Rust). However, when alignment and enum optimizations
782 come into the picture, it's quite likely that the sizes may or may not match
783 with different type parameter substitutions. It's not possible to check this for
784 _all_ possible types, so `transmute()` simply only accepts types without any
785 unsubstituted type parameters.
786
787 If you need this, there's a good chance you're doing something wrong. Keep in
788 mind that Rust doesn't guarantee much about the layout of different structs
789 (even two structs with identical declarations may have different layouts). If
790 there is a solution that avoids the transmute entirely, try it instead.
791
792 If it's possible, hand-monomorphize the code by writing the function for each
793 possible type substitution. It's possible to use traits to do this cleanly,
794 for example:
795
796 ```
797 trait MyTransmutableType {
798     fn transmute(Vec<Self>) -> Foo<Self>
799 }
800
801 impl MyTransmutableType for u8 {
802     fn transmute(x: Foo<u8>) -> Vec<u8> {
803         transmute(x)
804     }
805 }
806 impl MyTransmutableType for String {
807     fn transmute(x: Foo<String>) -> Vec<String> {
808         transmute(x)
809     }
810 }
811 // ... more impls for the types you intend to transmute
812
813 fn foo<T: MyTransmutableType>(x: Vec<T>) {
814     let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
815     // do something with y
816 }
817 ```
818
819 Each impl will be checked for a size match in the transmute as usual, and since
820 there are no unbound type parameters involved, this should compile unless there
821 is a size mismatch in one of the impls.
822
823 It is also possible to manually transmute:
824
825 ```
826 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
827 ```
828
829 Note that this does not move `v` (unlike `transmute`), and may need a
830 call to `mem::forget(v)` in case you want to avoid destructors being called.
831 "##,
832
833 E0152: r##"
834 Lang items are already implemented in the standard library. Unless you are
835 writing a free-standing application (e.g. a kernel), you do not need to provide
836 them yourself.
837
838 You can build a free-standing crate by adding `#![no_std]` to the crate
839 attributes:
840
841 ```
842 #![no_std]
843 ```
844
845 See also https://doc.rust-lang.org/book/no-stdlib.html
846 "##,
847
848 E0158: r##"
849 `const` and `static` mean different things. A `const` is a compile-time
850 constant, an alias for a literal value. This property means you can match it
851 directly within a pattern.
852
853 The `static` keyword, on the other hand, guarantees a fixed location in memory.
854 This does not always mean that the value is constant. For example, a global
855 mutex can be declared `static` as well.
856
857 If you want to match against a `static`, consider using a guard instead:
858
859 ```
860 static FORTY_TWO: i32 = 42;
861 match Some(42) {
862     Some(x) if x == FORTY_TWO => ...
863     ...
864 }
865 ```
866 "##,
867
868 E0161: r##"
869 In Rust, you can only move a value when its size is known at compile time.
870
871 To work around this restriction, consider "hiding" the value behind a reference:
872 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
873 it around as usual.
874 "##,
875
876 E0162: r##"
877 An if-let pattern attempts to match the pattern, and enters the body if the
878 match was successful. If the match is irrefutable (when it cannot fail to
879 match), use a regular `let`-binding instead. For instance:
880
881 ```
882 struct Irrefutable(i32);
883 let irr = Irrefutable(0);
884
885 // This fails to compile because the match is irrefutable.
886 if let Irrefutable(x) = irr {
887     // This body will always be executed.
888     foo(x);
889 }
890
891 // Try this instead:
892 let Irrefutable(x) = irr;
893 foo(x);
894 ```
895 "##,
896
897 E0165: r##"
898 A while-let pattern attempts to match the pattern, and enters the body if the
899 match was successful. If the match is irrefutable (when it cannot fail to
900 match), use a regular `let`-binding inside a `loop` instead. For instance:
901
902 ```
903 struct Irrefutable(i32);
904 let irr = Irrefutable(0);
905
906 // This fails to compile because the match is irrefutable.
907 while let Irrefutable(x) = irr {
908     ...
909 }
910
911 // Try this instead:
912 loop {
913     let Irrefutable(x) = irr;
914     ...
915 }
916 ```
917 "##,
918
919 E0170: r##"
920 Enum variants are qualified by default. For example, given this type:
921
922 ```
923 enum Method {
924     GET,
925     POST
926 }
927 ```
928
929 you would match it using:
930
931 ```
932 match m {
933     Method::GET => ...
934     Method::POST => ...
935 }
936 ```
937
938 If you don't qualify the names, the code will bind new variables named "GET" and
939 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
940 that happens.
941
942 Qualified names are good practice, and most code works well with them. But if
943 you prefer them unqualified, you can import the variants into scope:
944
945 ```
946 use Method::*;
947 enum Method { GET, POST }
948 ```
949
950 If you want others to be able to import variants from your module directly, use
951 `pub use`:
952
953 ```
954 pub use Method::*;
955 enum Method { GET, POST }
956 ```
957 "##,
958
959 E0229: r##"
960 An associated type binding was done outside of the type parameter declaration
961 and `where` clause. Erroneous code example:
962
963 ```
964 pub trait Foo {
965     type A;
966     fn boo(&self) -> <Self as Foo>::A;
967 }
968
969 struct Bar;
970
971 impl Foo for isize {
972     type A = usize;
973     fn boo(&self) -> usize { 42 }
974 }
975
976 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
977 // error: associated type bindings are not allowed here
978 ```
979
980 To solve this error, please move the type bindings in the type parameter
981 declaration:
982
983 ```
984 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
985 ```
986
987 or in the `where` clause:
988
989 ```
990 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
991 ```
992 "##,
993
994 E0261: r##"
995 When using a lifetime like `'a` in a type, it must be declared before being
996 used.
997
998 These two examples illustrate the problem:
999
1000 ```
1001 // error, use of undeclared lifetime name `'a`
1002 fn foo(x: &'a str) { }
1003
1004 struct Foo {
1005     // error, use of undeclared lifetime name `'a`
1006     x: &'a str,
1007 }
1008 ```
1009
1010 These can be fixed by declaring lifetime parameters:
1011
1012 ```
1013 fn foo<'a>(x: &'a str) { }
1014
1015 struct Foo<'a> {
1016     x: &'a str,
1017 }
1018 ```
1019 "##,
1020
1021 E0262: r##"
1022 Declaring certain lifetime names in parameters is disallowed. For example,
1023 because the `'static` lifetime is a special built-in lifetime name denoting
1024 the lifetime of the entire program, this is an error:
1025
1026 ```
1027 // error, invalid lifetime parameter name `'static`
1028 fn foo<'static>(x: &'static str) { }
1029 ```
1030 "##,
1031
1032 E0263: r##"
1033 A lifetime name cannot be declared more than once in the same scope. For
1034 example:
1035
1036 ```
1037 // error, lifetime name `'a` declared twice in the same scope
1038 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
1039 ```
1040 "##,
1041
1042 E0264: r##"
1043 An unknown external lang item was used. Erroneous code example:
1044
1045 ```
1046 #![feature(lang_items)]
1047
1048 extern "C" {
1049     #[lang = "cake"] // error: unknown external lang item: `cake`
1050     fn cake();
1051 }
1052 ```
1053
1054 A list of available external lang items is available in
1055 `src/librustc/middle/weak_lang_items.rs`. Example:
1056
1057 ```
1058 #![feature(lang_items)]
1059
1060 extern "C" {
1061     #[lang = "panic_fmt"] // ok!
1062     fn cake();
1063 }
1064 ```
1065 "##,
1066
1067 E0265: r##"
1068 This error indicates that a static or constant references itself.
1069 All statics and constants need to resolve to a value in an acyclic manner.
1070
1071 For example, neither of the following can be sensibly compiled:
1072
1073 ```
1074 const X: u32 = X;
1075 ```
1076
1077 ```
1078 const X: u32 = Y;
1079 const Y: u32 = X;
1080 ```
1081 "##,
1082
1083 E0267: r##"
1084 This error indicates the use of a loop keyword (`break` or `continue`) inside a
1085 closure but outside of any loop. Erroneous code example:
1086
1087 ```
1088 let w = || { break; }; // error: `break` inside of a closure
1089 ```
1090
1091 `break` and `continue` keywords can be used as normal inside closures as long as
1092 they are also contained within a loop. To halt the execution of a closure you
1093 should instead use a return statement. Example:
1094
1095 ```
1096 let w = || {
1097     for _ in 0..10 {
1098         break;
1099     }
1100 };
1101
1102 w();
1103 ```
1104 "##,
1105
1106 E0268: r##"
1107 This error indicates the use of a loop keyword (`break` or `continue`) outside
1108 of a loop. Without a loop to break out of or continue in, no sensible action can
1109 be taken. Erroneous code example:
1110
1111 ```
1112 fn some_func() {
1113     break; // error: `break` outside of loop
1114 }
1115 ```
1116
1117 Please verify that you are using `break` and `continue` only in loops. Example:
1118
1119 ```
1120 fn some_func() {
1121     for _ in 0..10 {
1122         break; // ok!
1123     }
1124 }
1125 ```
1126 "##,
1127
1128 E0269: r##"
1129 Functions must eventually return a value of their return type. For example, in
1130 the following function
1131
1132 ```
1133 fn foo(x: u8) -> u8 {
1134     if x > 0 {
1135         x // alternatively, `return x`
1136     }
1137     // nothing here
1138 }
1139 ```
1140
1141 if the condition is true, the value `x` is returned, but if the condition is
1142 false, control exits the `if` block and reaches a place where nothing is being
1143 returned. All possible control paths must eventually return a `u8`, which is not
1144 happening here.
1145
1146 An easy fix for this in a complicated function is to specify a default return
1147 value, if possible:
1148
1149 ```
1150 fn foo(x: u8) -> u8 {
1151     if x > 0 {
1152         x // alternatively, `return x`
1153     }
1154     // lots of other if branches
1155     0 // return 0 if all else fails
1156 }
1157 ```
1158
1159 It is advisable to find out what the unhandled cases are and check for them,
1160 returning an appropriate value or panicking if necessary.
1161 "##,
1162
1163 E0270: r##"
1164 Rust lets you define functions which are known to never return, i.e. are
1165 'diverging', by marking its return type as `!`.
1166
1167 For example, the following functions never return:
1168
1169 ```
1170 fn foo() -> ! {
1171     loop {}
1172 }
1173
1174 fn bar() -> ! {
1175     foo() // foo() is diverging, so this will diverge too
1176 }
1177
1178 fn baz() -> ! {
1179     panic!(); // this macro internally expands to a call to a diverging function
1180 }
1181
1182 ```
1183
1184 Such functions can be used in a place where a value is expected without
1185 returning a value of that type,  for instance:
1186
1187 ```
1188 let y = match x {
1189     1 => 1,
1190     2 => 4,
1191     _ => foo() // diverging function called here
1192 };
1193 println!("{}", y)
1194 ```
1195
1196 If the third arm of the match block is reached, since `foo()` doesn't ever
1197 return control to the match block, it is fine to use it in a place where an
1198 integer was expected. The `match` block will never finish executing, and any
1199 point where `y` (like the print statement) is needed will not be reached.
1200
1201 However, if we had a diverging function that actually does finish execution
1202
1203 ```
1204 fn foo() -> {
1205     loop {break;}
1206 }
1207 ```
1208
1209 then we would have an unknown value for `y` in the following code:
1210
1211 ```
1212 let y = match x {
1213     1 => 1,
1214     2 => 4,
1215     _ => foo()
1216 };
1217 println!("{}", y);
1218 ```
1219
1220 In the previous example, the print statement was never reached when the wildcard
1221 match arm was hit, so we were okay with `foo()` not returning an integer that we
1222 could set to `y`. But in this example, `foo()` actually does return control, so
1223 the print statement will be executed with an uninitialized value.
1224
1225 Obviously we cannot have functions which are allowed to be used in such
1226 positions and yet can return control. So, if you are defining a function that
1227 returns `!`, make sure that there is no way for it to actually finish executing.
1228 "##,
1229
1230 E0271: r##"
1231 This is because of a type mismatch between the associated type of some
1232 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1233 and another type `U` that is required to be equal to `T::Bar`, but is not.
1234 Examples follow.
1235
1236 Here is a basic example:
1237
1238 ```
1239 trait Trait { type AssociatedType; }
1240 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1241     println!("in foo");
1242 }
1243 impl Trait for i8 { type AssociatedType = &'static str; }
1244 foo(3_i8);
1245 ```
1246
1247 Here is that same example again, with some explanatory comments:
1248
1249 ```
1250 trait Trait { type AssociatedType; }
1251
1252 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1253 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1254 //                        |            |
1255 //         This says `foo` can         |
1256 //           only be used with         |
1257 //              some type that         |
1258 //         implements `Trait`.         |
1259 //                                     |
1260 //                             This says not only must
1261 //                             `T` be an impl of `Trait`
1262 //                             but also that the impl
1263 //                             must assign the type `u32`
1264 //                             to the associated type.
1265     println!("in foo");
1266 }
1267
1268 impl Trait for i8 { type AssociatedType = &'static str; }
1269 ~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1270 //      |                             |
1271 // `i8` does have                     |
1272 // implementation                     |
1273 // of `Trait`...                      |
1274 //                     ... but it is an implementation
1275 //                     that assigns `&'static str` to
1276 //                     the associated type.
1277
1278 foo(3_i8);
1279 // Here, we invoke `foo` with an `i8`, which does not satisfy
1280 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
1281 // therefore the type-checker complains with this error code.
1282 ```
1283
1284 Here is a more subtle instance of the same problem, that can
1285 arise with for-loops in Rust:
1286
1287 ```
1288 let vs: Vec<i32> = vec![1, 2, 3, 4];
1289 for v in &vs {
1290     match v {
1291         1 => {}
1292         _ => {}
1293     }
1294 }
1295 ```
1296
1297 The above fails because of an analogous type mismatch,
1298 though may be harder to see. Again, here are some
1299 explanatory comments for the same example:
1300
1301 ```
1302 {
1303     let vs = vec![1, 2, 3, 4];
1304
1305     // `for`-loops use a protocol based on the `Iterator`
1306     // trait. Each item yielded in a `for` loop has the
1307     // type `Iterator::Item` -- that is, `Item` is the
1308     // associated type of the concrete iterator impl.
1309     for v in &vs {
1310 //      ~    ~~~
1311 //      |     |
1312 //      |    We borrow `vs`, iterating over a sequence of
1313 //      |    *references* of type `&Elem` (where `Elem` is
1314 //      |    vector's element type). Thus, the associated
1315 //      |    type `Item` must be a reference `&`-type ...
1316 //      |
1317 //  ... and `v` has the type `Iterator::Item`, as dictated by
1318 //  the `for`-loop protocol ...
1319
1320         match v {
1321             1 => {}
1322 //          ~
1323 //          |
1324 // ... but *here*, `v` is forced to have some integral type;
1325 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1326 // match the pattern `1` ...
1327
1328             _ => {}
1329         }
1330
1331 // ... therefore, the compiler complains, because it sees
1332 // an attempt to solve the equations
1333 // `some integral-type` = type-of-`v`
1334 //                      = `Iterator::Item`
1335 //                      = `&Elem` (i.e. `some reference type`)
1336 //
1337 // which cannot possibly all be true.
1338
1339     }
1340 }
1341 ```
1342
1343 To avoid those issues, you have to make the types match correctly.
1344 So we can fix the previous examples like this:
1345
1346 ```
1347 // Basic Example:
1348 trait Trait { type AssociatedType; }
1349 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1350     println!("in foo");
1351 }
1352 impl Trait for i8 { type AssociatedType = &'static str; }
1353 foo(3_i8);
1354
1355 // For-Loop Example:
1356 let vs = vec![1, 2, 3, 4];
1357 for v in &vs {
1358     match v {
1359         &1 => {}
1360         _ => {}
1361     }
1362 }
1363 ```
1364 "##,
1365
1366 E0272: r##"
1367 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1368 message for when a particular trait isn't implemented on a type placed in a
1369 position that needs that trait. For example, when the following code is
1370 compiled:
1371
1372 ```
1373 fn foo<T: Index<u8>>(x: T){}
1374
1375 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1376 trait Index<Idx> { ... }
1377
1378 foo(true); // `bool` does not implement `Index<u8>`
1379 ```
1380
1381 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1382 note saying "the type `bool` cannot be indexed by `u8`".
1383
1384 As you can see, you can specify type parameters in curly braces for substitution
1385 with the actual types (using the regular format string syntax) in a given
1386 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1387 `bool`) that we tried to use.
1388
1389 This error appears when the curly braces contain an identifier which doesn't
1390 match with any of the type parameters or the string `Self`. This might happen if
1391 you misspelled a type parameter, or if you intended to use literal curly braces.
1392 If it is the latter, escape the curly braces with a second curly brace of the
1393 same type; e.g. a literal `{` is `{{`
1394 "##,
1395
1396 E0273: r##"
1397 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1398 message for when a particular trait isn't implemented on a type placed in a
1399 position that needs that trait. For example, when the following code is
1400 compiled:
1401
1402 ```
1403 fn foo<T: Index<u8>>(x: T){}
1404
1405 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1406 trait Index<Idx> { ... }
1407
1408 foo(true); // `bool` does not implement `Index<u8>`
1409 ```
1410
1411 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1412 note saying "the type `bool` cannot be indexed by `u8`".
1413
1414 As you can see, you can specify type parameters in curly braces for substitution
1415 with the actual types (using the regular format string syntax) in a given
1416 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1417 `bool`) that we tried to use.
1418
1419 This error appears when the curly braces do not contain an identifier. Please
1420 add one of the same name as a type parameter. If you intended to use literal
1421 braces, use `{{` and `}}` to escape them.
1422 "##,
1423
1424 E0274: r##"
1425 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1426 message for when a particular trait isn't implemented on a type placed in a
1427 position that needs that trait. For example, when the following code is
1428 compiled:
1429
1430 ```
1431 fn foo<T: Index<u8>>(x: T){}
1432
1433 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1434 trait Index<Idx> { ... }
1435
1436 foo(true); // `bool` does not implement `Index<u8>`
1437 ```
1438
1439 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1440 note saying "the type `bool` cannot be indexed by `u8`".
1441
1442 For this to work, some note must be specified. An empty attribute will not do
1443 anything, please remove the attribute or add some helpful note for users of the
1444 trait.
1445 "##,
1446
1447 E0275: r##"
1448 This error occurs when there was a recursive trait requirement that overflowed
1449 before it could be evaluated. Often this means that there is unbounded recursion
1450 in resolving some type bounds.
1451
1452 For example, in the following code
1453
1454 ```
1455 trait Foo {}
1456
1457 struct Bar<T>(T);
1458
1459 impl<T> Foo for T where Bar<T>: Foo {}
1460 ```
1461
1462 to determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1463 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To determine
1464 this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is clearly a
1465 recursive requirement that can't be resolved directly.
1466
1467 Consider changing your trait bounds so that they're less self-referential.
1468 "##,
1469
1470 E0276: r##"
1471 This error occurs when a bound in an implementation of a trait does not match
1472 the bounds specified in the original trait. For example:
1473
1474 ```
1475 trait Foo {
1476  fn foo<T>(x: T);
1477 }
1478
1479 impl Foo for bool {
1480  fn foo<T>(x: T) where T: Copy {}
1481 }
1482 ```
1483
1484 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1485 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1486 bound that `T` is `Copy`, which isn't compatible with the original trait.
1487
1488 Consider removing the bound from the method or adding the bound to the original
1489 method definition in the trait.
1490 "##,
1491
1492 E0277: r##"
1493 You tried to use a type which doesn't implement some trait in a place which
1494 expected that trait. Erroneous code example:
1495
1496 ```
1497 // here we declare the Foo trait with a bar method
1498 trait Foo {
1499     fn bar(&self);
1500 }
1501
1502 // we now declare a function which takes an object implementing the Foo trait
1503 fn some_func<T: Foo>(foo: T) {
1504     foo.bar();
1505 }
1506
1507 fn main() {
1508     // we now call the method with the i32 type, which doesn't implement
1509     // the Foo trait
1510     some_func(5i32); // error: the trait `Foo` is not implemented for the
1511                      //     type `i32`
1512 }
1513 ```
1514
1515 In order to fix this error, verify that the type you're using does implement
1516 the trait. Example:
1517
1518 ```
1519 trait Foo {
1520     fn bar(&self);
1521 }
1522
1523 fn some_func<T: Foo>(foo: T) {
1524     foo.bar(); // we can now use this method since i32 implements the
1525                // Foo trait
1526 }
1527
1528 // we implement the trait on the i32 type
1529 impl Foo for i32 {
1530     fn bar(&self) {}
1531 }
1532
1533 fn main() {
1534     some_func(5i32); // ok!
1535 }
1536 ```
1537 "##,
1538
1539 E0281: r##"
1540 You tried to supply a type which doesn't implement some trait in a location
1541 which expected that trait. This error typically occurs when working with
1542 `Fn`-based types. Erroneous code example:
1543
1544 ```
1545 fn foo<F: Fn()>(x: F) { }
1546
1547 fn main() {
1548     // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1549     // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1550     // [E0281]
1551     foo(|y| { });
1552 }
1553 ```
1554
1555 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1556 arguments, but the closure we attempted to pass to it requires one argument.
1557 "##,
1558
1559 E0282: r##"
1560 This error indicates that type inference did not result in one unique possible
1561 type, and extra information is required. In most cases this can be provided
1562 by adding a type annotation. Sometimes you need to specify a generic type
1563 parameter manually.
1564
1565 A common example is the `collect` method on `Iterator`. It has a generic type
1566 parameter with a `FromIterator` bound, which for a `char` iterator is
1567 implemented by `Vec` and `String` among others. Consider the following snippet
1568 that reverses the characters of a string:
1569
1570 ```
1571 let x = "hello".chars().rev().collect();
1572 ```
1573
1574 In this case, the compiler cannot infer what the type of `x` should be:
1575 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1576 use, you can use a type annotation on `x`:
1577
1578 ```
1579 let x: Vec<char> = "hello".chars().rev().collect();
1580 ```
1581
1582 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1583 the compiler can infer the rest:
1584
1585 ```
1586 let x: Vec<_> = "hello".chars().rev().collect();
1587 ```
1588
1589 Another way to provide the compiler with enough information, is to specify the
1590 generic type parameter:
1591
1592 ```
1593 let x = "hello".chars().rev().collect::<Vec<char>>();
1594 ```
1595
1596 Again, you need not specify the full type if the compiler can infer it:
1597
1598 ```
1599 let x = "hello".chars().rev().collect::<Vec<_>>();
1600 ```
1601
1602 Apart from a method or function with a generic type parameter, this error can
1603 occur when a type parameter of a struct or trait cannot be inferred. In that
1604 case it is not always possible to use a type annotation, because all candidates
1605 have the same return type. For instance:
1606
1607 ```
1608 struct Foo<T> {
1609     // Some fields omitted.
1610 }
1611
1612 impl<T> Foo<T> {
1613     fn bar() -> i32 {
1614         0
1615     }
1616
1617     fn baz() {
1618         let number = Foo::bar();
1619     }
1620 }
1621 ```
1622
1623 This will fail because the compiler does not know which instance of `Foo` to
1624 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1625 "##,
1626
1627 E0283: r##"
1628 This error occurs when the compiler doesn't have enough information
1629 to unambiguously choose an implementation.
1630
1631 For example:
1632
1633 ```
1634 trait Generator {
1635     fn create() -> u32;
1636 }
1637
1638 struct Impl;
1639 impl Generator for Impl {
1640     fn create() -> u32 { 1 }
1641 }
1642
1643 struct AnotherImpl;
1644 impl Generator for AnotherImpl {
1645     fn create() -> u32 { 2 }
1646 }
1647
1648 fn main() {
1649     let cont: u32 = Generator::create();
1650     // error, impossible to choose one of Generator trait implementation
1651     // Impl or AnotherImpl? Maybe anything else?
1652 }
1653 ```
1654
1655 To resolve this error use the concrete type:
1656
1657 ```
1658 fn main() {
1659     let gen1 = AnotherImpl::create();
1660
1661     // if there are multiple methods with same name (different traits)
1662     let gen2 = <AnotherImpl as Generator>::create();
1663 }
1664 ```
1665 "##,
1666
1667 E0296: r##"
1668 This error indicates that the given recursion limit could not be parsed. Ensure
1669 that the value provided is a positive integer between quotes, like so:
1670
1671 ```
1672 #![recursion_limit="1000"]
1673 ```
1674 "##,
1675
1676 E0297: r##"
1677 Patterns used to bind names must be irrefutable. That is, they must guarantee
1678 that a name will be extracted in all cases. Instead of pattern matching the
1679 loop variable, consider using a `match` or `if let` inside the loop body. For
1680 instance:
1681
1682 ```
1683 // This fails because `None` is not covered.
1684 for Some(x) in xs {
1685     ...
1686 }
1687
1688 // Match inside the loop instead:
1689 for item in xs {
1690     match item {
1691         Some(x) => ...
1692         None => ...
1693     }
1694 }
1695
1696 // Or use `if let`:
1697 for item in xs {
1698     if let Some(x) = item {
1699         ...
1700     }
1701 }
1702 ```
1703 "##,
1704
1705 E0301: r##"
1706 Mutable borrows are not allowed in pattern guards, because matching cannot have
1707 side effects. Side effects could alter the matched object or the environment
1708 on which the match depends in such a way, that the match would not be
1709 exhaustive. For instance, the following would not match any arm if mutable
1710 borrows were allowed:
1711
1712 ```
1713 match Some(()) {
1714     None => { },
1715     option if option.take().is_none() => { /* impossible, option is `Some` */ },
1716     Some(_) => { } // When the previous match failed, the option became `None`.
1717 }
1718 ```
1719 "##,
1720
1721 E0302: r##"
1722 Assignments are not allowed in pattern guards, because matching cannot have
1723 side effects. Side effects could alter the matched object or the environment
1724 on which the match depends in such a way, that the match would not be
1725 exhaustive. For instance, the following would not match any arm if assignments
1726 were allowed:
1727
1728 ```
1729 match Some(()) {
1730     None => { },
1731     option if { option = None; false } { },
1732     Some(_) => { } // When the previous match failed, the option became `None`.
1733 }
1734 ```
1735 "##,
1736
1737 E0303: r##"
1738 In certain cases it is possible for sub-bindings to violate memory safety.
1739 Updates to the borrow checker in a future version of Rust may remove this
1740 restriction, but for now patterns must be rewritten without sub-bindings.
1741
1742 ```
1743 // Before.
1744 match Some("hi".to_string()) {
1745     ref op_string_ref @ Some(ref s) => ...
1746     None => ...
1747 }
1748
1749 // After.
1750 match Some("hi".to_string()) {
1751     Some(ref s) => {
1752         let op_string_ref = &Some(s);
1753         ...
1754     }
1755     None => ...
1756 }
1757 ```
1758
1759 The `op_string_ref` binding has type `&Option<&String>` in both cases.
1760
1761 See also https://github.com/rust-lang/rust/issues/14587
1762 "##,
1763
1764 E0306: r##"
1765 In an array literal `[x; N]`, `N` is the number of elements in the array. This
1766 number cannot be negative.
1767 "##,
1768
1769 E0307: r##"
1770 The length of an array is part of its type. For this reason, this length must be
1771 a compile-time constant.
1772 "##,
1773
1774 E0308: r##"
1775 This error occurs when the compiler was unable to infer the concrete type of a
1776 variable. It can occur for several cases, the most common of which is a
1777 mismatch in the expected type that the compiler inferred for a variable's
1778 initializing expression, and the actual type explicitly assigned to the
1779 variable.
1780
1781 For example:
1782
1783 ```
1784 let x: i32 = "I am not a number!";
1785 //     ~~~   ~~~~~~~~~~~~~~~~~~~~
1786 //      |             |
1787 //      |    initializing expression;
1788 //      |    compiler infers type `&str`
1789 //      |
1790 //    type `i32` assigned to variable `x`
1791 ```
1792
1793 Another situation in which this occurs is when you attempt to use the `try!`
1794 macro inside a function that does not return a `Result<T, E>`:
1795
1796 ```
1797 use std::fs::File;
1798
1799 fn main() {
1800     let mut f = try!(File::create("foo.txt"));
1801 }
1802 ```
1803
1804 This code gives an error like this:
1805
1806 ```text
1807 <std macros>:5:8: 6:42 error: mismatched types:
1808  expected `()`,
1809      found `core::result::Result<_, _>`
1810  (expected (),
1811      found enum `core::result::Result`) [E0308]
1812 ```
1813
1814 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1815 `()` as its return type, hence the error.
1816 "##,
1817
1818 E0309: r##"
1819 Types in type definitions have lifetimes associated with them that represent
1820 how long the data stored within them is guaranteed to be live. This lifetime
1821 must be as long as the data needs to be alive, and missing the constraint that
1822 denotes this will cause this error.
1823
1824 ```
1825 // This won't compile because T is not constrained, meaning the data
1826 // stored in it is not guaranteed to last as long as the reference
1827 struct Foo<'a, T> {
1828     foo: &'a T
1829 }
1830
1831 // This will compile, because it has the constraint on the type parameter
1832 struct Foo<'a, T: 'a> {
1833     foo: &'a T
1834 }
1835 ```
1836 "##,
1837
1838 E0310: r##"
1839 Types in type definitions have lifetimes associated with them that represent
1840 how long the data stored within them is guaranteed to be live. This lifetime
1841 must be as long as the data needs to be alive, and missing the constraint that
1842 denotes this will cause this error.
1843
1844 ```
1845 // This won't compile because T is not constrained to the static lifetime
1846 // the reference needs
1847 struct Foo<T> {
1848     foo: &'static T
1849 }
1850
1851 // This will compile, because it has the constraint on the type parameter
1852 struct Foo<T: 'static> {
1853     foo: &'static T
1854 }
1855 ```
1856 "##,
1857
1858 E0378: r##"
1859 Method calls that aren't calls to inherent `const` methods are disallowed
1860 in statics, constants, and constant functions.
1861
1862 For example:
1863
1864 ```
1865 const BAZ: i32 = Foo(25).bar(); // error, `bar` isn't `const`
1866
1867 struct Foo(i32);
1868
1869 impl Foo {
1870     const fn foo(&self) -> i32 {
1871         self.bar() // error, `bar` isn't `const`
1872     }
1873
1874     fn bar(&self) -> i32 { self.0 }
1875 }
1876 ```
1877
1878 For more information about `const fn`'s, see [RFC 911].
1879
1880 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
1881 "##,
1882
1883 E0394: r##"
1884 From [RFC 246]:
1885
1886  > It is invalid for a static to reference another static by value. It is
1887  > required that all references be borrowed.
1888
1889 [RFC 246]: https://github.com/rust-lang/rfcs/pull/246
1890 "##,
1891
1892 E0395: r##"
1893 The value assigned to a constant expression must be known at compile time,
1894 which is not the case when comparing raw pointers. Erroneous code example:
1895
1896 ```
1897 static foo: i32 = 42;
1898 static bar: i32 = 43;
1899
1900 static baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1901 // error: raw pointers cannot be compared in statics!
1902 ```
1903
1904 Please check that the result of the comparison can be determined at compile time
1905 or isn't assigned to a constant expression. Example:
1906
1907 ```
1908 static foo: i32 = 42;
1909 static bar: i32 = 43;
1910
1911 let baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1912 // baz isn't a constant expression so it's ok
1913 ```
1914 "##,
1915
1916 E0396: r##"
1917 The value assigned to a constant expression must be known at compile time,
1918 which is not the case when dereferencing raw pointers. Erroneous code
1919 example:
1920
1921 ```
1922 const foo: i32 = 42;
1923 const baz: *const i32 = (&foo as *const i32);
1924
1925 const deref: i32 = *baz;
1926 // error: raw pointers cannot be dereferenced in constants
1927 ```
1928
1929 To fix this error, please do not assign this value to a constant expression.
1930 Example:
1931
1932 ```
1933 const foo: i32 = 42;
1934 const baz: *const i32 = (&foo as *const i32);
1935
1936 unsafe { let deref: i32 = *baz; }
1937 // baz isn't a constant expression so it's ok
1938 ```
1939
1940 You'll also note that this assignment must be done in an unsafe block!
1941 "##,
1942
1943 E0397: r##"
1944 It is not allowed for a mutable static to allocate or have destructors. For
1945 example:
1946
1947 ```
1948 // error: mutable statics are not allowed to have boxes
1949 static mut FOO: Option<Box<usize>> = None;
1950
1951 // error: mutable statics are not allowed to have destructors
1952 static mut BAR: Option<Vec<i32>> = None;
1953 ```
1954 "##,
1955
1956 E0398: r##"
1957 In Rust 1.3, the default object lifetime bounds are expected to
1958 change, as described in RFC #1156 [1]. You are getting a warning
1959 because the compiler thinks it is possible that this change will cause
1960 a compilation error in your code. It is possible, though unlikely,
1961 that this is a false alarm.
1962
1963 The heart of the change is that where `&'a Box<SomeTrait>` used to
1964 default to `&'a Box<SomeTrait+'a>`, it now defaults to `&'a
1965 Box<SomeTrait+'static>` (here, `SomeTrait` is the name of some trait
1966 type). Note that the only types which are affected are references to
1967 boxes, like `&Box<SomeTrait>` or `&[Box<SomeTrait>]`.  More common
1968 types like `&SomeTrait` or `Box<SomeTrait>` are unaffected.
1969
1970 To silence this warning, edit your code to use an explicit bound.
1971 Most of the time, this means that you will want to change the
1972 signature of a function that you are calling. For example, if
1973 the error is reported on a call like `foo(x)`, and `foo` is
1974 defined as follows:
1975
1976 ```
1977 fn foo(arg: &Box<SomeTrait>) { ... }
1978 ```
1979
1980 you might change it to:
1981
1982 ```
1983 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1984 ```
1985
1986 This explicitly states that you expect the trait object `SomeTrait` to
1987 contain references (with a maximum lifetime of `'a`).
1988
1989 [1]: https://github.com/rust-lang/rfcs/pull/1156
1990 "##,
1991
1992 E0400: r##"
1993 A user-defined dereference was attempted in an invalid context. Erroneous
1994 code example:
1995
1996 ```
1997 use std::ops::Deref;
1998
1999 struct A;
2000
2001 impl Deref for A {
2002     type Target = str;
2003
2004     fn deref(&self)-> &str { "foo" }
2005 }
2006
2007 const S: &'static str = &A;
2008 // error: user-defined dereference operators are not allowed in constants
2009
2010 fn main() {
2011     let foo = S;
2012 }
2013 ```
2014
2015 You cannot directly use a dereference operation whilst initializing a constant
2016 or a static. To fix this error, restructure your code to avoid this dereference,
2017 perhaps moving it inline:
2018
2019 ```
2020 use std::ops::Deref;
2021
2022 struct A;
2023
2024 impl Deref for A {
2025     type Target = str;
2026
2027     fn deref(&self)-> &str { "foo" }
2028 }
2029
2030 fn main() {
2031     let foo : &str = &A;
2032 }
2033 ```
2034 "##,
2035
2036 E0452: r##"
2037 An invalid lint attribute has been given. Erroneous code example:
2038
2039 ```
2040 #![allow(foo = "")] // error: malformed lint attribute
2041 ```
2042
2043 Lint attributes only accept a list of identifiers (where each identifier is a
2044 lint name). Ensure the attribute is of this form:
2045
2046 ```
2047 #![allow(foo)] // ok!
2048 // or:
2049 #![allow(foo, foo2)] // ok!
2050 ```
2051 "##,
2052
2053 E0492: r##"
2054 A borrow of a constant containing interior mutability was attempted. Erroneous
2055 code example:
2056
2057 ```
2058 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
2059
2060 const A: AtomicUsize = ATOMIC_USIZE_INIT;
2061 static B: &'static AtomicUsize = &A;
2062 // error: cannot borrow a constant which contains interior mutability, create a
2063 //        static instead
2064 ```
2065
2066 A `const` represents a constant value that should never change. If one takes
2067 a `&` reference to the constant, then one is taking a pointer to some memory
2068 location containing the value. Normally this is perfectly fine: most values
2069 can't be changed via a shared `&` pointer, but interior mutability would allow
2070 it. That is, a constant value could be mutated. On the other hand, a `static` is
2071 explicitly a single memory location, which can be mutated at will.
2072
2073 So, in order to solve this error, either use statics which are `Sync`:
2074
2075 ```
2076 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
2077
2078 static A: AtomicUsize = ATOMIC_USIZE_INIT;
2079 static B: &'static AtomicUsize = &A; // ok!
2080 ```
2081
2082 You can also have this error while using a cell type:
2083
2084 ```
2085 #![feature(const_fn)]
2086
2087 use std::cell::Cell;
2088
2089 const A: Cell<usize> = Cell::new(1);
2090 const B: &'static Cell<usize> = &A;
2091 // error: cannot borrow a constant which contains interior mutability, create
2092 //        a static instead
2093
2094 // or:
2095 struct C { a: Cell<usize> }
2096
2097 const D: C = C { a: Cell::new(1) };
2098 const E: &'static Cell<usize> = &D.a; // error
2099
2100 // or:
2101 const F: &'static C = &D; // error
2102 ```
2103
2104 This is because cell types do operations that are not thread-safe. Due to this,
2105 they don't implement Sync and thus can't be placed in statics. In this
2106 case, `StaticMutex` would work just fine, but it isn't stable yet:
2107 https://doc.rust-lang.org/nightly/std/sync/struct.StaticMutex.html
2108
2109 However, if you still wish to use these types, you can achieve this by an unsafe
2110 wrapper:
2111
2112 ```
2113 #![feature(const_fn)]
2114
2115 use std::cell::Cell;
2116 use std::marker::Sync;
2117
2118 struct NotThreadSafe<T> {
2119     value: Cell<T>,
2120 }
2121
2122 unsafe impl<T> Sync for NotThreadSafe<T> {}
2123
2124 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
2125 static B: &'static NotThreadSafe<usize> = &A; // ok!
2126 ```
2127
2128 Remember this solution is unsafe! You will have to ensure that accesses to the
2129 cell are synchronized.
2130 "##,
2131
2132 E0493: r##"
2133 A type with a destructor was assigned to an invalid type of variable. Erroneous
2134 code example:
2135
2136 ```
2137 struct Foo {
2138     a: u32
2139 }
2140
2141 impl Drop for Foo {
2142     fn drop(&mut self) {}
2143 }
2144
2145 const F : Foo = Foo { a : 0 };
2146 // error: constants are not allowed to have destructors
2147 static S : Foo = Foo { a : 0 };
2148 // error: statics are not allowed to have destructors
2149 ```
2150
2151 To solve this issue, please use a type which does allow the usage of type with
2152 destructors.
2153 "##,
2154
2155 E0494: r##"
2156 A reference of an interior static was assigned to another const/static.
2157 Erroneous code example:
2158
2159 ```
2160 struct Foo {
2161     a: u32
2162 }
2163
2164 static S : Foo = Foo { a : 0 };
2165 static A : &'static u32 = &S.a;
2166 // error: cannot refer to the interior of another static, use a
2167 //        constant instead
2168 ```
2169
2170 The "base" variable has to be a const if you want another static/const variable
2171 to refer to one of its fields. Example:
2172
2173 ```
2174 struct Foo {
2175     a: u32
2176 }
2177
2178 const S : Foo = Foo { a : 0 };
2179 static A : &'static u32 = &S.a; // ok!
2180 ```
2181 "##,
2182
2183 E0496: r##"
2184 A lifetime name is shadowing another lifetime name. Erroneous code example:
2185
2186 ```
2187 struct Foo<'a> {
2188     a: &'a i32,
2189 }
2190
2191 impl<'a> Foo<'a> {
2192     fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
2193                            //        name that is already in scope
2194     }
2195 }
2196 ```
2197
2198 Please change the name of one of the lifetimes to remove this error. Example:
2199
2200 ```
2201 struct Foo<'a> {
2202     a: &'a i32,
2203 }
2204
2205 impl<'a> Foo<'a> {
2206     fn f<'b>(x: &'b i32) { // ok!
2207     }
2208 }
2209
2210 fn main() {
2211 }
2212 ```
2213 "##,
2214
2215 E0497: r##"
2216 A stability attribute was used outside of the standard library. Erroneous code
2217 example:
2218
2219 ```
2220 #[stable] // error: stability attributes may not be used outside of the
2221           //        standard library
2222 fn foo() {}
2223 ```
2224
2225 It is not possible to use stability attributes outside of the standard library.
2226 Also, for now, it is not possible to write deprecation messages either.
2227 "##,
2228
2229 E0517: r##"
2230 This error indicates that a `#[repr(..)]` attribute was placed on an unsupported
2231 item.
2232
2233 Examples of erroneous code:
2234
2235 ```
2236 #[repr(C)]
2237 type Foo = u8;
2238
2239 #[repr(packed)]
2240 enum Foo {Bar, Baz}
2241
2242 #[repr(u8)]
2243 struct Foo {bar: bool, baz: bool}
2244
2245 #[repr(C)]
2246 impl Foo {
2247     ...
2248 }
2249 ```
2250
2251  - The `#[repr(C)]` attribute can only be placed on structs and enums
2252  - The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs
2253  - The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums
2254
2255 These attributes do not work on typedefs, since typedefs are just aliases.
2256
2257 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
2258 discriminant size for C-like enums (when there is no associated data, e.g. `enum
2259 Color {Red, Blue, Green}`), effectively setting the size of the enum to the size
2260 of the provided type. Such an enum can be cast to a value of the same type as
2261 well. In short, `#[repr(u8)]` makes the enum behave like an integer with a
2262 constrained set of allowed values.
2263
2264 Only C-like enums can be cast to numerical primitives, so this attribute will
2265 not apply to structs.
2266
2267 `#[repr(packed)]` reduces padding to make the struct size smaller. The
2268 representation of enums isn't strictly defined in Rust, and this attribute won't
2269 work on enums.
2270
2271 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
2272 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
2273 SIMD. This doesn't make much sense for enums since they don't consist of a
2274 single list of data.
2275 "##,
2276
2277 E0518: r##"
2278 This error indicates that an `#[inline(..)]` attribute was incorrectly placed on
2279 something other than a function or method.
2280
2281 Examples of erroneous code:
2282
2283 ```
2284 #[inline(always)]
2285 struct Foo;
2286
2287 #[inline(never)]
2288 impl Foo {
2289     ...
2290 }
2291 ```
2292
2293 `#[inline]` hints the compiler whether or not to attempt to inline a method or
2294 function. By default, the compiler does a pretty good job of figuring this out
2295 itself, but if you feel the need for annotations, `#[inline(always)]` and
2296 `#[inline(never)]` can override or force the compiler's decision.
2297
2298 If you wish to apply this attribute to all methods in an impl, manually annotate
2299 each method; it is not possible to annotate the entire impl with an `#[inline]`
2300 attribute.
2301 "##,
2302
2303 }
2304
2305
2306 register_diagnostics! {
2307     // E0006 // merged with E0005
2308 //  E0134,
2309 //  E0135,
2310     E0278, // requirement is not satisfied
2311     E0279, // requirement is not satisfied
2312     E0280, // requirement is not satisfied
2313     E0284, // cannot resolve type
2314     E0285, // overflow evaluation builtin bounds
2315     E0298, // mismatched types between arms
2316     E0299, // mismatched types between arms
2317     // E0300, // unexpanded macro
2318     // E0304, // expected signed integer constant
2319     // E0305, // expected constant
2320     E0311, // thing may not live long enough
2321     E0312, // lifetime of reference outlives lifetime of borrowed content
2322     E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
2323     E0314, // closure outlives stack frame
2324     E0315, // cannot invoke closure outside of its lifetime
2325     E0316, // nested quantification of lifetimes
2326     E0453, // overruled by outer forbid
2327     E0471, // constant evaluation error: ..
2328     E0473, // dereference of reference outside its lifetime
2329     E0474, // captured variable `..` does not outlive the enclosing closure
2330     E0475, // index of slice outside its lifetime
2331     E0476, // lifetime of the source pointer does not outlive lifetime bound...
2332     E0477, // the type `..` does not fulfill the required lifetime...
2333     E0478, // lifetime bound not satisfied
2334     E0479, // the type `..` (provided as the value of a type parameter) is...
2335     E0480, // lifetime of method receiver does not outlive the method call
2336     E0481, // lifetime of function argument does not outlive the function call
2337     E0482, // lifetime of return value does not outlive the function call
2338     E0483, // lifetime of operand does not outlive the operation
2339     E0484, // reference is not valid at the time of borrow
2340     E0485, // automatically reference is not valid at the time of borrow
2341     E0486, // type of expression contains references that are not valid during...
2342     E0487, // unsafe use of destructor: destructor might be called while...
2343     E0488, // lifetime of variable does not enclose its declaration
2344     E0489, // type/lifetime parameter not in scope here
2345     E0490, // a value of type `..` is borrowed for too long
2346     E0491, // in type `..`, reference has a longer lifetime than the data it...
2347     E0495, // cannot infer an appropriate lifetime due to conflicting requirements
2348 }