]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/diagnostics.rs
Rollup merge of #56363 - Lucretiel:patch-3, r=shepmaster
[rust.git] / src / librustc_mir / diagnostics.rs
1 // Copyright 2015 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 register_long_diagnostics! {
14
15
16 E0001: r##"
17 #### Note: this error code is no longer emitted by the compiler.
18
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
24 one is too specific or the ordering is incorrect.
25
26 For example, the following `match` block has too many arms:
27
28 ```
29 match Some(0) {
30     Some(bar) => {/* ... */}
31     x => {/* ... */} // This handles the `None` case
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 #### Note: this error code is no longer emitted by the compiler.
45
46 This error indicates that an empty match expression is invalid because the type
47 it is matching on is non-empty (there exist values of this type). In safe code
48 it is impossible to create an instance of an empty type, so empty match
49 expressions are almost never desired. This error is typically fixed by adding
50 one or more cases to the match expression.
51
52 An example of an empty type is `enum Empty { }`. So, the following will work:
53
54 ```
55 enum Empty {}
56
57 fn foo(x: Empty) {
58     match x {
59         // empty
60     }
61 }
62 ```
63
64 However, this won't:
65
66 ```compile_fail
67 fn foo(x: Option<String>) {
68     match x {
69         // empty
70     }
71 }
72 ```
73 "##,
74
75 E0004: r##"
76 This error indicates that the compiler cannot guarantee a matching pattern for
77 one or more possible inputs to a match expression. Guaranteed matches are
78 required in order to assign values to match expressions, or alternatively,
79 determine the flow of execution. Erroneous code example:
80
81 ```compile_fail,E0004
82 enum Terminator {
83     HastaLaVistaBaby,
84     TalkToMyHand,
85 }
86
87 let x = Terminator::HastaLaVistaBaby;
88
89 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
90     Terminator::TalkToMyHand => {}
91 }
92 ```
93
94 If you encounter this error you must alter your patterns so that every possible
95 value of the input type is matched. For types with a small number of variants
96 (like enums) you should probably cover all cases explicitly. Alternatively, the
97 underscore `_` wildcard pattern can be added after all other patterns to match
98 "anything else". Example:
99
100 ```
101 enum Terminator {
102     HastaLaVistaBaby,
103     TalkToMyHand,
104 }
105
106 let x = Terminator::HastaLaVistaBaby;
107
108 match x {
109     Terminator::TalkToMyHand => {}
110     Terminator::HastaLaVistaBaby => {}
111 }
112
113 // or:
114
115 match x {
116     Terminator::TalkToMyHand => {}
117     _ => {}
118 }
119 ```
120 "##,
121
122 E0005: r##"
123 Patterns used to bind names must be irrefutable, that is, they must guarantee
124 that a name will be extracted in all cases. Erroneous code example:
125
126 ```compile_fail,E0005
127 let x = Some(1);
128 let Some(y) = x;
129 // error: refutable pattern in local binding: `None` not covered
130 ```
131
132 If you encounter this error you probably need to use a `match` or `if let` to
133 deal with the possibility of failure. Example:
134
135 ```
136 let x = Some(1);
137
138 match x {
139     Some(y) => {
140         // do something
141     },
142     None => {}
143 }
144
145 // or:
146
147 if let Some(y) = x {
148     // do something
149 }
150 ```
151 "##,
152
153 E0007: r##"
154 This error indicates that the bindings in a match arm would require a value to
155 be moved into more than one location, thus violating unique ownership. Code
156 like the following is invalid as it requires the entire `Option<String>` to be
157 moved into a variable called `op_string` while simultaneously requiring the
158 inner `String` to be moved into a variable called `s`.
159
160 ```compile_fail,E0007
161 let x = Some("s".to_string());
162
163 match x {
164     op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
165     None => {},
166 }
167 ```
168
169 See also the error E0303.
170 "##,
171
172 E0008: r##"
173 Names bound in match arms retain their type in pattern guards. As such, if a
174 name is bound by move in a pattern, it should also be moved to wherever it is
175 referenced in the pattern guard code. Doing so however would prevent the name
176 from being available in the body of the match arm. Consider the following:
177
178 ```compile_fail,E0008
179 match Some("hi".to_string()) {
180     Some(s) if s.len() == 0 => {}, // use s.
181     _ => {},
182 }
183 ```
184
185 The variable `s` has type `String`, and its use in the guard is as a variable of
186 type `String`. The guard code effectively executes in a separate scope to the
187 body of the arm, so the value would be moved into this anonymous scope and
188 therefore becomes unavailable in the body of the arm.
189
190 The problem above can be solved by using the `ref` keyword.
191
192 ```
193 match Some("hi".to_string()) {
194     Some(ref s) if s.len() == 0 => {},
195     _ => {},
196 }
197 ```
198
199 Though this example seems innocuous and easy to solve, the problem becomes clear
200 when it encounters functions which consume the value:
201
202 ```compile_fail,E0008
203 struct A{}
204
205 impl A {
206     fn consume(self) -> usize {
207         0
208     }
209 }
210
211 fn main() {
212     let a = Some(A{});
213     match a {
214         Some(y) if y.consume() > 0 => {}
215         _ => {}
216     }
217 }
218 ```
219
220 In this situation, even the `ref` keyword cannot solve it, since borrowed
221 content cannot be moved. This problem cannot be solved generally. If the value
222 can be cloned, here is a not-so-specific solution:
223
224 ```
225 #[derive(Clone)]
226 struct A{}
227
228 impl A {
229     fn consume(self) -> usize {
230         0
231     }
232 }
233
234 fn main() {
235     let a = Some(A{});
236     match a{
237         Some(ref y) if y.clone().consume() > 0 => {}
238         _ => {}
239     }
240 }
241 ```
242
243 If the value will be consumed in the pattern guard, using its clone will not
244 move its ownership, so the code works.
245 "##,
246
247 E0009: r##"
248 In a pattern, all values that don't implement the `Copy` trait have to be bound
249 the same way. The goal here is to avoid binding simultaneously by-move and
250 by-ref.
251
252 This limitation may be removed in a future version of Rust.
253
254 Erroneous code example:
255
256 ```compile_fail,E0009
257 struct X { x: (), }
258
259 let x = Some((X { x: () }, X { x: () }));
260 match x {
261     Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
262                             //        same pattern
263     None => panic!()
264 }
265 ```
266
267 You have two solutions:
268
269 Solution #1: Bind the pattern's values the same way.
270
271 ```
272 struct X { x: (), }
273
274 let x = Some((X { x: () }, X { x: () }));
275 match x {
276     Some((ref y, ref z)) => {},
277     // or Some((y, z)) => {}
278     None => panic!()
279 }
280 ```
281
282 Solution #2: Implement the `Copy` trait for the `X` structure.
283
284 However, please keep in mind that the first solution should be preferred.
285
286 ```
287 #[derive(Clone, Copy)]
288 struct X { x: (), }
289
290 let x = Some((X { x: () }, X { x: () }));
291 match x {
292     Some((y, ref z)) => {},
293     None => panic!()
294 }
295 ```
296 "##,
297
298 E0030: r##"
299 When matching against a range, the compiler verifies that the range is
300 non-empty.  Range patterns include both end-points, so this is equivalent to
301 requiring the start of the range to be less than or equal to the end of the
302 range.
303
304 For example:
305
306 ```compile_fail
307 match 5u32 {
308     // This range is ok, albeit pointless.
309     1 ..= 1 => {}
310     // This range is empty, and the compiler can tell.
311     1000 ..= 5 => {}
312 }
313 ```
314 "##,
315
316 E0158: r##"
317 `const` and `static` mean different things. A `const` is a compile-time
318 constant, an alias for a literal value. This property means you can match it
319 directly within a pattern.
320
321 The `static` keyword, on the other hand, guarantees a fixed location in memory.
322 This does not always mean that the value is constant. For example, a global
323 mutex can be declared `static` as well.
324
325 If you want to match against a `static`, consider using a guard instead:
326
327 ```
328 static FORTY_TWO: i32 = 42;
329
330 match Some(42) {
331     Some(x) if x == FORTY_TWO => {}
332     _ => {}
333 }
334 ```
335 "##,
336
337 E0162: r##"
338 An if-let pattern attempts to match the pattern, and enters the body if the
339 match was successful. If the match is irrefutable (when it cannot fail to
340 match), use a regular `let`-binding instead. For instance:
341
342 ```compile_fail,E0162
343 struct Irrefutable(i32);
344 let irr = Irrefutable(0);
345
346 // This fails to compile because the match is irrefutable.
347 if let Irrefutable(x) = irr {
348     // This body will always be executed.
349     // ...
350 }
351 ```
352
353 Try this instead:
354
355 ```
356 struct Irrefutable(i32);
357 let irr = Irrefutable(0);
358
359 let Irrefutable(x) = irr;
360 println!("{}", x);
361 ```
362 "##,
363
364 E0165: r##"
365 A while-let pattern attempts to match the pattern, and enters the body if the
366 match was successful. If the match is irrefutable (when it cannot fail to
367 match), use a regular `let`-binding inside a `loop` instead. For instance:
368
369 ```compile_fail,E0165
370 struct Irrefutable(i32);
371 let irr = Irrefutable(0);
372
373 // This fails to compile because the match is irrefutable.
374 while let Irrefutable(x) = irr {
375     // ...
376 }
377 ```
378
379 Try this instead:
380
381 ```no_run
382 struct Irrefutable(i32);
383 let irr = Irrefutable(0);
384
385 loop {
386     let Irrefutable(x) = irr;
387     // ...
388 }
389 ```
390 "##,
391
392 E0170: r##"
393 Enum variants are qualified by default. For example, given this type:
394
395 ```
396 enum Method {
397     GET,
398     POST,
399 }
400 ```
401
402 You would match it using:
403
404 ```
405 enum Method {
406     GET,
407     POST,
408 }
409
410 let m = Method::GET;
411
412 match m {
413     Method::GET => {},
414     Method::POST => {},
415 }
416 ```
417
418 If you don't qualify the names, the code will bind new variables named "GET" and
419 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
420 that happens.
421
422 Qualified names are good practice, and most code works well with them. But if
423 you prefer them unqualified, you can import the variants into scope:
424
425 ```
426 use Method::*;
427 enum Method { GET, POST }
428 # fn main() {}
429 ```
430
431 If you want others to be able to import variants from your module directly, use
432 `pub use`:
433
434 ```
435 pub use Method::*;
436 pub enum Method { GET, POST }
437 # fn main() {}
438 ```
439 "##,
440
441
442 E0297: r##"
443 #### Note: this error code is no longer emitted by the compiler.
444
445 Patterns used to bind names must be irrefutable. That is, they must guarantee
446 that a name will be extracted in all cases. Instead of pattern matching the
447 loop variable, consider using a `match` or `if let` inside the loop body. For
448 instance:
449
450 ```compile_fail,E0005
451 let xs : Vec<Option<i32>> = vec![Some(1), None];
452
453 // This fails because `None` is not covered.
454 for Some(x) in xs {
455     // ...
456 }
457 ```
458
459 Match inside the loop instead:
460
461 ```
462 let xs : Vec<Option<i32>> = vec![Some(1), None];
463
464 for item in xs {
465     match item {
466         Some(x) => {},
467         None => {},
468     }
469 }
470 ```
471
472 Or use `if let`:
473
474 ```
475 let xs : Vec<Option<i32>> = vec![Some(1), None];
476
477 for item in xs {
478     if let Some(x) = item {
479         // ...
480     }
481 }
482 ```
483 "##,
484
485 E0301: r##"
486 Mutable borrows are not allowed in pattern guards, because matching cannot have
487 side effects. Side effects could alter the matched object or the environment
488 on which the match depends in such a way, that the match would not be
489 exhaustive. For instance, the following would not match any arm if mutable
490 borrows were allowed:
491
492 ```compile_fail,E0301
493 match Some(()) {
494     None => { },
495     option if option.take().is_none() => {
496         /* impossible, option is `Some` */
497     },
498     Some(_) => { } // When the previous match failed, the option became `None`.
499 }
500 ```
501 "##,
502
503 E0302: r##"
504 Assignments are not allowed in pattern guards, because matching cannot have
505 side effects. Side effects could alter the matched object or the environment
506 on which the match depends in such a way, that the match would not be
507 exhaustive. For instance, the following would not match any arm if assignments
508 were allowed:
509
510 ```compile_fail,E0302
511 match Some(()) {
512     None => { },
513     option if { option = None; false } => { },
514     Some(_) => { } // When the previous match failed, the option became `None`.
515 }
516 ```
517 "##,
518
519 E0303: r##"
520 In certain cases it is possible for sub-bindings to violate memory safety.
521 Updates to the borrow checker in a future version of Rust may remove this
522 restriction, but for now patterns must be rewritten without sub-bindings.
523
524 Before:
525
526 ```compile_fail,E0303
527 match Some("hi".to_string()) {
528     ref op_string_ref @ Some(s) => {},
529     None => {},
530 }
531 ```
532
533 After:
534
535 ```
536 match Some("hi".to_string()) {
537     Some(ref s) => {
538         let op_string_ref = &Some(s);
539         // ...
540     },
541     None => {},
542 }
543 ```
544
545 The `op_string_ref` binding has type `&Option<&String>` in both cases.
546
547 See also https://github.com/rust-lang/rust/issues/14587
548 "##,
549
550 E0010: r##"
551 The value of statics and constants must be known at compile time, and they live
552 for the entire lifetime of a program. Creating a boxed value allocates memory on
553 the heap at runtime, and therefore cannot be done at compile time. Erroneous
554 code example:
555
556 ```compile_fail,E0010
557 #![feature(box_syntax)]
558
559 const CON : Box<i32> = box 0;
560 ```
561 "##,
562
563 E0013: r##"
564 Static and const variables can refer to other const variables. But a const
565 variable cannot refer to a static variable. For example, `Y` cannot refer to
566 `X` here:
567
568 ```compile_fail,E0013
569 static X: i32 = 42;
570 const Y: i32 = X;
571 ```
572
573 To fix this, the value can be extracted as a const and then used:
574
575 ```
576 const A: i32 = 42;
577 static X: i32 = A;
578 const Y: i32 = A;
579 ```
580 "##,
581
582 // FIXME(#24111) Change the language here when const fn stabilizes
583 E0015: r##"
584 The only functions that can be called in static or constant expressions are
585 `const` functions, and struct/enum constructors. `const` functions are only
586 available on a nightly compiler. Rust currently does not support more general
587 compile-time function execution.
588
589 ```
590 const FOO: Option<u8> = Some(1); // enum constructor
591 struct Bar {x: u8}
592 const BAR: Bar = Bar {x: 1}; // struct constructor
593 ```
594
595 See [RFC 911] for more details on the design of `const fn`s.
596
597 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
598 "##,
599
600 E0017: r##"
601 References in statics and constants may only refer to immutable values.
602 Erroneous code example:
603
604 ```compile_fail,E0017
605 static X: i32 = 1;
606 const C: i32 = 2;
607
608 // these three are not allowed:
609 const CR: &mut i32 = &mut C;
610 static STATIC_REF: &'static mut i32 = &mut X;
611 static CONST_REF: &'static mut i32 = &mut C;
612 ```
613
614 Statics are shared everywhere, and if they refer to mutable data one might
615 violate memory safety since holding multiple mutable references to shared data
616 is not allowed.
617
618 If you really want global mutable state, try using `static mut` or a global
619 `UnsafeCell`.
620 "##,
621
622 E0019: r##"
623 A function call isn't allowed in the const's initialization expression
624 because the expression's value must be known at compile-time. Erroneous code
625 example:
626
627 ```compile_fail
628 enum Test {
629     V1
630 }
631
632 impl Test {
633     fn test(&self) -> i32 {
634         12
635     }
636 }
637
638 fn main() {
639     const FOO: Test = Test::V1;
640
641     const A: i32 = FOO.test(); // You can't call Test::func() here!
642 }
643 ```
644
645 Remember: you can't use a function call inside a const's initialization
646 expression! However, you can totally use it anywhere else:
647
648 ```
649 enum Test {
650     V1
651 }
652
653 impl Test {
654     fn func(&self) -> i32 {
655         12
656     }
657 }
658
659 fn main() {
660     const FOO: Test = Test::V1;
661
662     FOO.func(); // here is good
663     let x = FOO.func(); // or even here!
664 }
665 ```
666 "##,
667
668 E0133: r##"
669 Unsafe code was used outside of an unsafe function or block.
670
671 Erroneous code example:
672
673 ```compile_fail,E0133
674 unsafe fn f() { return; } // This is the unsafe code
675
676 fn main() {
677     f(); // error: call to unsafe function requires unsafe function or block
678 }
679 ```
680
681 Using unsafe functionality is potentially dangerous and disallowed by safety
682 checks. Examples:
683
684 * Dereferencing raw pointers
685 * Calling functions via FFI
686 * Calling functions marked unsafe
687
688 These safety checks can be relaxed for a section of the code by wrapping the
689 unsafe instructions with an `unsafe` block. For instance:
690
691 ```
692 unsafe fn f() { return; }
693
694 fn main() {
695     unsafe { f(); } // ok!
696 }
697 ```
698
699 See also https://doc.rust-lang.org/book/first-edition/unsafe.html
700 "##,
701
702 E0373: r##"
703 This error occurs when an attempt is made to use data captured by a closure,
704 when that data may no longer exist. It's most commonly seen when attempting to
705 return a closure:
706
707 ```compile_fail,E0373
708 fn foo() -> Box<Fn(u32) -> u32> {
709     let x = 0u32;
710     Box::new(|y| x + y)
711 }
712 ```
713
714 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
715 closed-over data by reference. This means that once `foo()` returns, `x` no
716 longer exists. An attempt to access `x` within the closure would thus be
717 unsafe.
718
719 Another situation where this might be encountered is when spawning threads:
720
721 ```compile_fail,E0373
722 fn foo() {
723     let x = 0u32;
724     let y = 1u32;
725
726     let thr = std::thread::spawn(|| {
727         x + y
728     });
729 }
730 ```
731
732 Since our new thread runs in parallel, the stack frame containing `x` and `y`
733 may well have disappeared by the time we try to use them. Even if we call
734 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
735 stack frame won't disappear), we will not succeed: the compiler cannot prove
736 that this behaviour is safe, and so won't let us do it.
737
738 The solution to this problem is usually to switch to using a `move` closure.
739 This approach moves (or copies, where possible) data into the closure, rather
740 than taking references to it. For example:
741
742 ```
743 fn foo() -> Box<Fn(u32) -> u32> {
744     let x = 0u32;
745     Box::new(move |y| x + y)
746 }
747 ```
748
749 Now that the closure has its own copy of the data, there's no need to worry
750 about safety.
751 "##,
752
753 E0381: r##"
754 It is not allowed to use or capture an uninitialized variable. For example:
755
756 ```compile_fail,E0381
757 fn main() {
758     let x: i32;
759     let y = x; // error, use of possibly uninitialized variable
760 }
761 ```
762
763 To fix this, ensure that any declared variables are initialized before being
764 used. Example:
765
766 ```
767 fn main() {
768     let x: i32 = 0;
769     let y = x; // ok!
770 }
771 ```
772 "##,
773
774 E0382: r##"
775 This error occurs when an attempt is made to use a variable after its contents
776 have been moved elsewhere. For example:
777
778 ```compile_fail,E0382
779 struct MyStruct { s: u32 }
780
781 fn main() {
782     let mut x = MyStruct{ s: 5u32 };
783     let y = x;
784     x.s = 6;
785     println!("{}", x.s);
786 }
787 ```
788
789 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
790 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
791 of workarounds like `Rc`, a value cannot be owned by more than one variable.
792
793 Sometimes we don't need to move the value. Using a reference, we can let another
794 function borrow the value without changing its ownership. In the example below,
795 we don't actually have to move our string to `calculate_length`, we can give it
796 a reference to it with `&` instead.
797
798 ```
799 fn main() {
800     let s1 = String::from("hello");
801
802     let len = calculate_length(&s1);
803
804     println!("The length of '{}' is {}.", s1, len);
805 }
806
807 fn calculate_length(s: &String) -> usize {
808     s.len()
809 }
810 ```
811
812 A mutable reference can be created with `&mut`.
813
814 Sometimes we don't want a reference, but a duplicate. All types marked `Clone`
815 can be duplicated by calling `.clone()`. Subsequent changes to a clone do not
816 affect the original variable.
817
818 Most types in the standard library are marked `Clone`. The example below
819 demonstrates using `clone()` on a string. `s1` is first set to "many", and then
820 copied to `s2`. Then the first character of `s1` is removed, without affecting
821 `s2`. "any many" is printed to the console.
822
823 ```
824 fn main() {
825     let mut s1 = String::from("many");
826     let s2 = s1.clone();
827     s1.remove(0);
828     println!("{} {}", s1, s2);
829 }
830 ```
831
832 If we control the definition of a type, we can implement `Clone` on it ourselves
833 with `#[derive(Clone)]`.
834
835 Some types have no ownership semantics at all and are trivial to duplicate. An
836 example is `i32` and the other number types. We don't have to call `.clone()` to
837 clone them, because they are marked `Copy` in addition to `Clone`.  Implicit
838 cloning is more convenient in this case. We can mark our own types `Copy` if
839 all their members also are marked `Copy`.
840
841 In the example below, we implement a `Point` type. Because it only stores two
842 integers, we opt-out of ownership semantics with `Copy`. Then we can
843 `let p2 = p1` without `p1` being moved.
844
845 ```
846 #[derive(Copy, Clone)]
847 struct Point { x: i32, y: i32 }
848
849 fn main() {
850     let mut p1 = Point{ x: -1, y: 2 };
851     let p2 = p1;
852     p1.x = 1;
853     println!("p1: {}, {}", p1.x, p1.y);
854     println!("p2: {}, {}", p2.x, p2.y);
855 }
856 ```
857
858 Alternatively, if we don't control the struct's definition, or mutable shared
859 ownership is truly required, we can use `Rc` and `RefCell`:
860
861 ```
862 use std::cell::RefCell;
863 use std::rc::Rc;
864
865 struct MyStruct { s: u32 }
866
867 fn main() {
868     let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
869     let y = x.clone();
870     x.borrow_mut().s = 6;
871     println!("{}", x.borrow().s);
872 }
873 ```
874
875 With this approach, x and y share ownership of the data via the `Rc` (reference
876 count type). `RefCell` essentially performs runtime borrow checking: ensuring
877 that at most one writer or multiple readers can access the data at any one time.
878
879 If you wish to learn more about ownership in Rust, start with the chapter in the
880 Book:
881
882 https://doc.rust-lang.org/book/first-edition/ownership.html
883 "##,
884
885 E0383: r##"
886 This error occurs when an attempt is made to partially reinitialize a
887 structure that is currently uninitialized.
888
889 For example, this can happen when a drop has taken place:
890
891 ```compile_fail,E0383
892 struct Foo {
893     a: u32,
894 }
895 impl Drop for Foo {
896     fn drop(&mut self) { /* ... */ }
897 }
898
899 let mut x = Foo { a: 1 };
900 drop(x); // `x` is now uninitialized
901 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
902 ```
903
904 This error can be fixed by fully reinitializing the structure in question:
905
906 ```
907 struct Foo {
908     a: u32,
909 }
910 impl Drop for Foo {
911     fn drop(&mut self) { /* ... */ }
912 }
913
914 let mut x = Foo { a: 1 };
915 drop(x);
916 x = Foo { a: 2 };
917 ```
918 "##,
919
920 E0384: r##"
921 This error occurs when an attempt is made to reassign an immutable variable.
922 For example:
923
924 ```compile_fail,E0384
925 fn main() {
926     let x = 3;
927     x = 5; // error, reassignment of immutable variable
928 }
929 ```
930
931 By default, variables in Rust are immutable. To fix this error, add the keyword
932 `mut` after the keyword `let` when declaring the variable. For example:
933
934 ```
935 fn main() {
936     let mut x = 3;
937     x = 5;
938 }
939 ```
940 "##,
941
942 /*E0386: r##"
943 This error occurs when an attempt is made to mutate the target of a mutable
944 reference stored inside an immutable container.
945
946 For example, this can happen when storing a `&mut` inside an immutable `Box`:
947
948 ```compile_fail,E0386
949 let mut x: i64 = 1;
950 let y: Box<_> = Box::new(&mut x);
951 **y = 2; // error, cannot assign to data in an immutable container
952 ```
953
954 This error can be fixed by making the container mutable:
955
956 ```
957 let mut x: i64 = 1;
958 let mut y: Box<_> = Box::new(&mut x);
959 **y = 2;
960 ```
961
962 It can also be fixed by using a type with interior mutability, such as `Cell`
963 or `RefCell`:
964
965 ```
966 use std::cell::Cell;
967
968 let x: i64 = 1;
969 let y: Box<Cell<_>> = Box::new(Cell::new(x));
970 y.set(2);
971 ```
972 "##,*/
973
974 E0387: r##"
975 This error occurs when an attempt is made to mutate or mutably reference data
976 that a closure has captured immutably. Examples of this error are shown below:
977
978 ```compile_fail,E0387
979 // Accepts a function or a closure that captures its environment immutably.
980 // Closures passed to foo will not be able to mutate their closed-over state.
981 fn foo<F: Fn()>(f: F) { }
982
983 // Attempts to mutate closed-over data. Error message reads:
984 // `cannot assign to data in a captured outer variable...`
985 fn mutable() {
986     let mut x = 0u32;
987     foo(|| x = 2);
988 }
989
990 // Attempts to take a mutable reference to closed-over data.  Error message
991 // reads: `cannot borrow data mutably in a captured outer variable...`
992 fn mut_addr() {
993     let mut x = 0u32;
994     foo(|| { let y = &mut x; });
995 }
996 ```
997
998 The problem here is that foo is defined as accepting a parameter of type `Fn`.
999 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
1000 they capture their context immutably.
1001
1002 If the definition of `foo` is under your control, the simplest solution is to
1003 capture the data mutably. This can be done by defining `foo` to take FnMut
1004 rather than Fn:
1005
1006 ```
1007 fn foo<F: FnMut()>(f: F) { }
1008 ```
1009
1010 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
1011 interior mutability through a shared reference. Our example's `mutable`
1012 function could be redefined as below:
1013
1014 ```
1015 use std::cell::Cell;
1016
1017 fn foo<F: Fn()>(f: F) { }
1018
1019 fn mutable() {
1020     let x = Cell::new(0u32);
1021     foo(|| x.set(2));
1022 }
1023 ```
1024
1025 You can read more about cell types in the API documentation:
1026
1027 https://doc.rust-lang.org/std/cell/
1028 "##,
1029
1030 E0388: r##"
1031 E0388 was removed and is no longer issued.
1032 "##,
1033
1034 E0389: r##"
1035 An attempt was made to mutate data using a non-mutable reference. This
1036 commonly occurs when attempting to assign to a non-mutable reference of a
1037 mutable reference (`&(&mut T)`).
1038
1039 Example of erroneous code:
1040
1041 ```compile_fail,E0389
1042 struct FancyNum {
1043     num: u8,
1044 }
1045
1046 fn main() {
1047     let mut fancy = FancyNum{ num: 5 };
1048     let fancy_ref = &(&mut fancy);
1049     fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
1050     println!("{}", fancy_ref.num);
1051 }
1052 ```
1053
1054 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
1055 immutable reference to a value borrows it immutably. There can be multiple
1056 references of type `&(&mut T)` that point to the same value, so they must be
1057 immutable to prevent multiple mutable references to the same value.
1058
1059 To fix this, either remove the outer reference:
1060
1061 ```
1062 struct FancyNum {
1063     num: u8,
1064 }
1065
1066 fn main() {
1067     let mut fancy = FancyNum{ num: 5 };
1068
1069     let fancy_ref = &mut fancy;
1070     // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1071
1072     fancy_ref.num = 6; // No error!
1073
1074     println!("{}", fancy_ref.num);
1075 }
1076 ```
1077
1078 Or make the outer reference mutable:
1079
1080 ```
1081 struct FancyNum {
1082     num: u8
1083 }
1084
1085 fn main() {
1086     let mut fancy = FancyNum{ num: 5 };
1087
1088     let fancy_ref = &mut (&mut fancy);
1089     // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1090
1091     fancy_ref.num = 6; // No error!
1092
1093     println!("{}", fancy_ref.num);
1094 }
1095 ```
1096 "##,
1097
1098 E0161: r##"
1099 A value was moved. However, its size was not known at compile time, and only
1100 values of a known size can be moved.
1101
1102 Erroneous code example:
1103
1104 ```compile_fail
1105 #![feature(box_syntax)]
1106
1107 fn main() {
1108     let array: &[isize] = &[1, 2, 3];
1109     let _x: Box<[isize]> = box *array;
1110     // error: cannot move a value of type [isize]: the size of [isize] cannot
1111     //        be statically determined
1112 }
1113 ```
1114
1115 In Rust, you can only move a value when its size is known at compile time.
1116
1117 To work around this restriction, consider "hiding" the value behind a reference:
1118 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
1119 it around as usual. Example:
1120
1121 ```
1122 #![feature(box_syntax)]
1123
1124 fn main() {
1125     let array: &[isize] = &[1, 2, 3];
1126     let _x: Box<&[isize]> = box array; // ok!
1127 }
1128 ```
1129 "##,
1130
1131 E0492: r##"
1132 A borrow of a constant containing interior mutability was attempted. Erroneous
1133 code example:
1134
1135 ```compile_fail,E0492
1136 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
1137
1138 const A: AtomicUsize = ATOMIC_USIZE_INIT;
1139 static B: &'static AtomicUsize = &A;
1140 // error: cannot borrow a constant which may contain interior mutability,
1141 //        create a static instead
1142 ```
1143
1144 A `const` represents a constant value that should never change. If one takes
1145 a `&` reference to the constant, then one is taking a pointer to some memory
1146 location containing the value. Normally this is perfectly fine: most values
1147 can't be changed via a shared `&` pointer, but interior mutability would allow
1148 it. That is, a constant value could be mutated. On the other hand, a `static` is
1149 explicitly a single memory location, which can be mutated at will.
1150
1151 So, in order to solve this error, either use statics which are `Sync`:
1152
1153 ```
1154 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
1155
1156 static A: AtomicUsize = ATOMIC_USIZE_INIT;
1157 static B: &'static AtomicUsize = &A; // ok!
1158 ```
1159
1160 You can also have this error while using a cell type:
1161
1162 ```compile_fail,E0492
1163 use std::cell::Cell;
1164
1165 const A: Cell<usize> = Cell::new(1);
1166 const B: &Cell<usize> = &A;
1167 // error: cannot borrow a constant which may contain interior mutability,
1168 //        create a static instead
1169
1170 // or:
1171 struct C { a: Cell<usize> }
1172
1173 const D: C = C { a: Cell::new(1) };
1174 const E: &Cell<usize> = &D.a; // error
1175
1176 // or:
1177 const F: &C = &D; // error
1178 ```
1179
1180 This is because cell types do operations that are not thread-safe. Due to this,
1181 they don't implement Sync and thus can't be placed in statics.
1182
1183 However, if you still wish to use these types, you can achieve this by an unsafe
1184 wrapper:
1185
1186 ```
1187 use std::cell::Cell;
1188 use std::marker::Sync;
1189
1190 struct NotThreadSafe<T> {
1191     value: Cell<T>,
1192 }
1193
1194 unsafe impl<T> Sync for NotThreadSafe<T> {}
1195
1196 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1197 static B: &'static NotThreadSafe<usize> = &A; // ok!
1198 ```
1199
1200 Remember this solution is unsafe! You will have to ensure that accesses to the
1201 cell are synchronized.
1202 "##,
1203
1204 E0499: r##"
1205 A variable was borrowed as mutable more than once. Erroneous code example:
1206
1207 ```compile_fail,E0499
1208 let mut i = 0;
1209 let mut x = &mut i;
1210 let mut a = &mut i;
1211 // error: cannot borrow `i` as mutable more than once at a time
1212 ```
1213
1214 Please note that in rust, you can either have many immutable references, or one
1215 mutable reference. Take a look at
1216 https://doc.rust-lang.org/stable/book/references-and-borrowing.html for more
1217 information. Example:
1218
1219
1220 ```
1221 let mut i = 0;
1222 let mut x = &mut i; // ok!
1223
1224 // or:
1225 let mut i = 0;
1226 let a = &i; // ok!
1227 let b = &i; // still ok!
1228 let c = &i; // still ok!
1229 ```
1230 "##,
1231
1232 E0500: r##"
1233 A borrowed variable was used in another closure. Example of erroneous code:
1234
1235 ```compile_fail
1236 fn you_know_nothing(jon_snow: &mut i32) {
1237     let nights_watch = || {
1238         *jon_snow = 2;
1239     };
1240     let starks = || {
1241         *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1242                        //        but it is already borrowed
1243     };
1244 }
1245 ```
1246
1247 In here, `jon_snow` is already borrowed by the `nights_watch` closure, so it
1248 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
1249 you can put the closure in its own scope:
1250
1251 ```
1252 fn you_know_nothing(jon_snow: &mut i32) {
1253     {
1254         let nights_watch = || {
1255             *jon_snow = 2;
1256         };
1257     } // At this point, `jon_snow` is free.
1258     let starks = || {
1259         *jon_snow = 3;
1260     };
1261 }
1262 ```
1263
1264 Or, if the type implements the `Clone` trait, you can clone it between
1265 closures:
1266
1267 ```
1268 fn you_know_nothing(jon_snow: &mut i32) {
1269     let mut jon_copy = jon_snow.clone();
1270     let nights_watch = || {
1271         jon_copy = 2;
1272     };
1273     let starks = || {
1274         *jon_snow = 3;
1275     };
1276 }
1277 ```
1278 "##,
1279
1280 E0501: r##"
1281 This error indicates that a mutable variable is being used while it is still
1282 captured by a closure. Because the closure has borrowed the variable, it is not
1283 available for use until the closure goes out of scope.
1284
1285 Note that a capture will either move or borrow a variable, but in this
1286 situation, the closure is borrowing the variable. Take a look at
1287 http://rustbyexample.com/fn/closures/capture.html for more information about
1288 capturing.
1289
1290 Example of erroneous code:
1291
1292 ```compile_fail,E0501
1293 fn inside_closure(x: &mut i32) {
1294     // Actions which require unique access
1295 }
1296
1297 fn outside_closure(x: &mut i32) {
1298     // Actions which require unique access
1299 }
1300
1301 fn foo(a: &mut i32) {
1302     let bar = || {
1303         inside_closure(a)
1304     };
1305     outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1306                         //        closure requires unique access.
1307 }
1308 ```
1309
1310 To fix this error, you can place the closure in its own scope:
1311
1312 ```
1313 fn inside_closure(x: &mut i32) {}
1314 fn outside_closure(x: &mut i32) {}
1315
1316 fn foo(a: &mut i32) {
1317     {
1318         let bar = || {
1319             inside_closure(a)
1320         };
1321     } // borrow on `a` ends.
1322     outside_closure(a); // ok!
1323 }
1324 ```
1325
1326 Or you can pass the variable as a parameter to the closure:
1327
1328 ```
1329 fn inside_closure(x: &mut i32) {}
1330 fn outside_closure(x: &mut i32) {}
1331
1332 fn foo(a: &mut i32) {
1333     let bar = |s: &mut i32| {
1334         inside_closure(s)
1335     };
1336     outside_closure(a);
1337     bar(a);
1338 }
1339 ```
1340
1341 It may be possible to define the closure later:
1342
1343 ```
1344 fn inside_closure(x: &mut i32) {}
1345 fn outside_closure(x: &mut i32) {}
1346
1347 fn foo(a: &mut i32) {
1348     outside_closure(a);
1349     let bar = || {
1350         inside_closure(a)
1351     };
1352 }
1353 ```
1354 "##,
1355
1356 E0502: r##"
1357 This error indicates that you are trying to borrow a variable as mutable when it
1358 has already been borrowed as immutable.
1359
1360 Example of erroneous code:
1361
1362 ```compile_fail,E0502
1363 fn bar(x: &mut i32) {}
1364 fn foo(a: &mut i32) {
1365     let ref y = a; // a is borrowed as immutable.
1366     bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
1367             //        as immutable
1368 }
1369 ```
1370
1371 To fix this error, ensure that you don't have any other references to the
1372 variable before trying to access it mutably:
1373
1374 ```
1375 fn bar(x: &mut i32) {}
1376 fn foo(a: &mut i32) {
1377     bar(a);
1378     let ref y = a; // ok!
1379 }
1380 ```
1381
1382 For more information on the rust ownership system, take a look at
1383 https://doc.rust-lang.org/stable/book/references-and-borrowing.html.
1384 "##,
1385
1386 E0503: r##"
1387 A value was used after it was mutably borrowed.
1388
1389 Example of erroneous code:
1390
1391 ```compile_fail,E0503
1392 fn main() {
1393     let mut value = 3;
1394     // Create a mutable borrow of `value`. This borrow
1395     // lives until the end of this function.
1396     let _borrow = &mut value;
1397     let _sum = value + 1; // error: cannot use `value` because
1398                           //        it was mutably borrowed
1399 }
1400 ```
1401
1402 In this example, `value` is mutably borrowed by `borrow` and cannot be
1403 used to calculate `sum`. This is not possible because this would violate
1404 Rust's mutability rules.
1405
1406 You can fix this error by limiting the scope of the borrow:
1407
1408 ```
1409 fn main() {
1410     let mut value = 3;
1411     // By creating a new block, you can limit the scope
1412     // of the reference.
1413     {
1414         let _borrow = &mut value; // Use `_borrow` inside this block.
1415     }
1416     // The block has ended and with it the borrow.
1417     // You can now use `value` again.
1418     let _sum = value + 1;
1419 }
1420 ```
1421
1422 Or by cloning `value` before borrowing it:
1423
1424 ```
1425 fn main() {
1426     let mut value = 3;
1427     // We clone `value`, creating a copy.
1428     let value_cloned = value.clone();
1429     // The mutable borrow is a reference to `value` and
1430     // not to `value_cloned`...
1431     let _borrow = &mut value;
1432     // ... which means we can still use `value_cloned`,
1433     let _sum = value_cloned + 1;
1434     // even though the borrow only ends here.
1435 }
1436 ```
1437
1438 You can find more information about borrowing in the rust-book:
1439 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1440 "##,
1441
1442 E0504: r##"
1443 This error occurs when an attempt is made to move a borrowed variable into a
1444 closure.
1445
1446 Example of erroneous code:
1447
1448 ```compile_fail,E0504
1449 struct FancyNum {
1450     num: u8,
1451 }
1452
1453 fn main() {
1454     let fancy_num = FancyNum { num: 5 };
1455     let fancy_ref = &fancy_num;
1456
1457     let x = move || {
1458         println!("child function: {}", fancy_num.num);
1459         // error: cannot move `fancy_num` into closure because it is borrowed
1460     };
1461
1462     x();
1463     println!("main function: {}", fancy_ref.num);
1464 }
1465 ```
1466
1467 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1468 the closure `x`. There is no way to move a value into a closure while it is
1469 borrowed, as that would invalidate the borrow.
1470
1471 If the closure can't outlive the value being moved, try using a reference
1472 rather than moving:
1473
1474 ```
1475 struct FancyNum {
1476     num: u8,
1477 }
1478
1479 fn main() {
1480     let fancy_num = FancyNum { num: 5 };
1481     let fancy_ref = &fancy_num;
1482
1483     let x = move || {
1484         // fancy_ref is usable here because it doesn't move `fancy_num`
1485         println!("child function: {}", fancy_ref.num);
1486     };
1487
1488     x();
1489
1490     println!("main function: {}", fancy_num.num);
1491 }
1492 ```
1493
1494 If the value has to be borrowed and then moved, try limiting the lifetime of
1495 the borrow using a scoped block:
1496
1497 ```
1498 struct FancyNum {
1499     num: u8,
1500 }
1501
1502 fn main() {
1503     let fancy_num = FancyNum { num: 5 };
1504
1505     {
1506         let fancy_ref = &fancy_num;
1507         println!("main function: {}", fancy_ref.num);
1508         // `fancy_ref` goes out of scope here
1509     }
1510
1511     let x = move || {
1512         // `fancy_num` can be moved now (no more references exist)
1513         println!("child function: {}", fancy_num.num);
1514     };
1515
1516     x();
1517 }
1518 ```
1519
1520 If the lifetime of a reference isn't enough, such as in the case of threading,
1521 consider using an `Arc` to create a reference-counted value:
1522
1523 ```
1524 use std::sync::Arc;
1525 use std::thread;
1526
1527 struct FancyNum {
1528     num: u8,
1529 }
1530
1531 fn main() {
1532     let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1533     let fancy_ref2 = fancy_ref1.clone();
1534
1535     let x = thread::spawn(move || {
1536         // `fancy_ref1` can be moved and has a `'static` lifetime
1537         println!("child thread: {}", fancy_ref1.num);
1538     });
1539
1540     x.join().expect("child thread should finish");
1541     println!("main thread: {}", fancy_ref2.num);
1542 }
1543 ```
1544 "##,
1545
1546 E0505: r##"
1547 A value was moved out while it was still borrowed.
1548
1549 Erroneous code example:
1550
1551 ```compile_fail,E0505
1552 struct Value {}
1553
1554 fn eat(val: Value) {}
1555
1556 fn main() {
1557     let x = Value{};
1558     {
1559         let _ref_to_val: &Value = &x;
1560         eat(x);
1561     }
1562 }
1563 ```
1564
1565 Here, the function `eat` takes the ownership of `x`. However,
1566 `x` cannot be moved because it was borrowed to `_ref_to_val`.
1567 To fix that you can do few different things:
1568
1569 * Try to avoid moving the variable.
1570 * Release borrow before move.
1571 * Implement the `Copy` trait on the type.
1572
1573 Examples:
1574
1575 ```
1576 struct Value {}
1577
1578 fn eat(val: &Value) {}
1579
1580 fn main() {
1581     let x = Value{};
1582     {
1583         let _ref_to_val: &Value = &x;
1584         eat(&x); // pass by reference, if it's possible
1585     }
1586 }
1587 ```
1588
1589 Or:
1590
1591 ```
1592 struct Value {}
1593
1594 fn eat(val: Value) {}
1595
1596 fn main() {
1597     let x = Value{};
1598     {
1599         let _ref_to_val: &Value = &x;
1600     }
1601     eat(x); // release borrow and then move it.
1602 }
1603 ```
1604
1605 Or:
1606
1607 ```
1608 #[derive(Clone, Copy)] // implement Copy trait
1609 struct Value {}
1610
1611 fn eat(val: Value) {}
1612
1613 fn main() {
1614     let x = Value{};
1615     {
1616         let _ref_to_val: &Value = &x;
1617         eat(x); // it will be copied here.
1618     }
1619 }
1620 ```
1621
1622 You can find more information about borrowing in the rust-book:
1623 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1624 "##,
1625
1626 E0506: r##"
1627 This error occurs when an attempt is made to assign to a borrowed value.
1628
1629 Example of erroneous code:
1630
1631 ```compile_fail,E0506
1632 struct FancyNum {
1633     num: u8,
1634 }
1635
1636 fn main() {
1637     let mut fancy_num = FancyNum { num: 5 };
1638     let fancy_ref = &fancy_num;
1639     fancy_num = FancyNum { num: 6 };
1640     // error: cannot assign to `fancy_num` because it is borrowed
1641
1642     println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1643 }
1644 ```
1645
1646 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1647 be assigned to a new value as it would invalidate the reference.
1648
1649 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1650
1651 ```
1652 struct FancyNum {
1653     num: u8,
1654 }
1655
1656 fn main() {
1657     let mut fancy_num = FancyNum { num: 5 };
1658     let moved_num = fancy_num;
1659     fancy_num = FancyNum { num: 6 };
1660
1661     println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1662 }
1663 ```
1664
1665 If the value has to be borrowed, try limiting the lifetime of the borrow using
1666 a scoped block:
1667
1668 ```
1669 struct FancyNum {
1670     num: u8,
1671 }
1672
1673 fn main() {
1674     let mut fancy_num = FancyNum { num: 5 };
1675
1676     {
1677         let fancy_ref = &fancy_num;
1678         println!("Ref: {}", fancy_ref.num);
1679     }
1680
1681     // Works because `fancy_ref` is no longer in scope
1682     fancy_num = FancyNum { num: 6 };
1683     println!("Num: {}", fancy_num.num);
1684 }
1685 ```
1686
1687 Or by moving the reference into a function:
1688
1689 ```
1690 struct FancyNum {
1691     num: u8,
1692 }
1693
1694 fn main() {
1695     let mut fancy_num = FancyNum { num: 5 };
1696
1697     print_fancy_ref(&fancy_num);
1698
1699     // Works because function borrow has ended
1700     fancy_num = FancyNum { num: 6 };
1701     println!("Num: {}", fancy_num.num);
1702 }
1703
1704 fn print_fancy_ref(fancy_ref: &FancyNum){
1705     println!("Ref: {}", fancy_ref.num);
1706 }
1707 ```
1708 "##,
1709
1710 E0507: r##"
1711 You tried to move out of a value which was borrowed. Erroneous code example:
1712
1713 ```compile_fail,E0507
1714 use std::cell::RefCell;
1715
1716 struct TheDarkKnight;
1717
1718 impl TheDarkKnight {
1719     fn nothing_is_true(self) {}
1720 }
1721
1722 fn main() {
1723     let x = RefCell::new(TheDarkKnight);
1724
1725     x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1726 }
1727 ```
1728
1729 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1730 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1731 which is a borrow of the content owned by the `RefCell`. To fix this error,
1732 you have three choices:
1733
1734 * Try to avoid moving the variable.
1735 * Somehow reclaim the ownership.
1736 * Implement the `Copy` trait on the type.
1737
1738 Examples:
1739
1740 ```
1741 use std::cell::RefCell;
1742
1743 struct TheDarkKnight;
1744
1745 impl TheDarkKnight {
1746     fn nothing_is_true(&self) {} // First case, we don't take ownership
1747 }
1748
1749 fn main() {
1750     let x = RefCell::new(TheDarkKnight);
1751
1752     x.borrow().nothing_is_true(); // ok!
1753 }
1754 ```
1755
1756 Or:
1757
1758 ```
1759 use std::cell::RefCell;
1760
1761 struct TheDarkKnight;
1762
1763 impl TheDarkKnight {
1764     fn nothing_is_true(self) {}
1765 }
1766
1767 fn main() {
1768     let x = RefCell::new(TheDarkKnight);
1769     let x = x.into_inner(); // we get back ownership
1770
1771     x.nothing_is_true(); // ok!
1772 }
1773 ```
1774
1775 Or:
1776
1777 ```
1778 use std::cell::RefCell;
1779
1780 #[derive(Clone, Copy)] // we implement the Copy trait
1781 struct TheDarkKnight;
1782
1783 impl TheDarkKnight {
1784     fn nothing_is_true(self) {}
1785 }
1786
1787 fn main() {
1788     let x = RefCell::new(TheDarkKnight);
1789
1790     x.borrow().nothing_is_true(); // ok!
1791 }
1792 ```
1793
1794 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1795
1796 ```compile_fail,E0507
1797 struct TheDarkKnight;
1798
1799 impl TheDarkKnight {
1800     fn nothing_is_true(self) {}
1801 }
1802
1803 struct Batcave {
1804     knight: TheDarkKnight
1805 }
1806
1807 fn main() {
1808     let mut cave = Batcave {
1809         knight: TheDarkKnight
1810     };
1811     let borrowed = &mut cave;
1812
1813     borrowed.knight.nothing_is_true(); // E0507
1814 }
1815 ```
1816
1817 It is fine only if you put something back. `mem::replace` can be used for that:
1818
1819 ```
1820 # struct TheDarkKnight;
1821 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1822 # struct Batcave { knight: TheDarkKnight }
1823 use std::mem;
1824
1825 let mut cave = Batcave {
1826     knight: TheDarkKnight
1827 };
1828 let borrowed = &mut cave;
1829
1830 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1831 ```
1832
1833 You can find more information about borrowing in the rust-book:
1834 http://doc.rust-lang.org/book/first-edition/references-and-borrowing.html
1835 "##,
1836
1837 E0508: r##"
1838 A value was moved out of a non-copy fixed-size array.
1839
1840 Example of erroneous code:
1841
1842 ```compile_fail,E0508
1843 struct NonCopy;
1844
1845 fn main() {
1846     let array = [NonCopy; 1];
1847     let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1848                            //        a non-copy fixed-size array
1849 }
1850 ```
1851
1852 The first element was moved out of the array, but this is not
1853 possible because `NonCopy` does not implement the `Copy` trait.
1854
1855 Consider borrowing the element instead of moving it:
1856
1857 ```
1858 struct NonCopy;
1859
1860 fn main() {
1861     let array = [NonCopy; 1];
1862     let _value = &array[0]; // Borrowing is allowed, unlike moving.
1863 }
1864 ```
1865
1866 Alternatively, if your type implements `Clone` and you need to own the value,
1867 consider borrowing and then cloning:
1868
1869 ```
1870 #[derive(Clone)]
1871 struct NonCopy;
1872
1873 fn main() {
1874     let array = [NonCopy; 1];
1875     // Now you can clone the array element.
1876     let _value = array[0].clone();
1877 }
1878 ```
1879 "##,
1880
1881 E0509: r##"
1882 This error occurs when an attempt is made to move out of a value whose type
1883 implements the `Drop` trait.
1884
1885 Example of erroneous code:
1886
1887 ```compile_fail,E0509
1888 struct FancyNum {
1889     num: usize
1890 }
1891
1892 struct DropStruct {
1893     fancy: FancyNum
1894 }
1895
1896 impl Drop for DropStruct {
1897     fn drop(&mut self) {
1898         // Destruct DropStruct, possibly using FancyNum
1899     }
1900 }
1901
1902 fn main() {
1903     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1904     let fancy_field = drop_struct.fancy; // Error E0509
1905     println!("Fancy: {}", fancy_field.num);
1906     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1907 }
1908 ```
1909
1910 Here, we tried to move a field out of a struct of type `DropStruct` which
1911 implements the `Drop` trait. However, a struct cannot be dropped if one or
1912 more of its fields have been moved.
1913
1914 Structs implementing the `Drop` trait have an implicit destructor that gets
1915 called when they go out of scope. This destructor may use the fields of the
1916 struct, so moving out of the struct could make it impossible to run the
1917 destructor. Therefore, we must think of all values whose type implements the
1918 `Drop` trait as single units whose fields cannot be moved.
1919
1920 This error can be fixed by creating a reference to the fields of a struct,
1921 enum, or tuple using the `ref` keyword:
1922
1923 ```
1924 struct FancyNum {
1925     num: usize
1926 }
1927
1928 struct DropStruct {
1929     fancy: FancyNum
1930 }
1931
1932 impl Drop for DropStruct {
1933     fn drop(&mut self) {
1934         // Destruct DropStruct, possibly using FancyNum
1935     }
1936 }
1937
1938 fn main() {
1939     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1940     let ref fancy_field = drop_struct.fancy; // No more errors!
1941     println!("Fancy: {}", fancy_field.num);
1942     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1943 }
1944 ```
1945
1946 Note that this technique can also be used in the arms of a match expression:
1947
1948 ```
1949 struct FancyNum {
1950     num: usize
1951 }
1952
1953 enum DropEnum {
1954     Fancy(FancyNum)
1955 }
1956
1957 impl Drop for DropEnum {
1958     fn drop(&mut self) {
1959         // Destruct DropEnum, possibly using FancyNum
1960     }
1961 }
1962
1963 fn main() {
1964     // Creates and enum of type `DropEnum`, which implements `Drop`
1965     let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1966     match drop_enum {
1967         // Creates a reference to the inside of `DropEnum::Fancy`
1968         DropEnum::Fancy(ref fancy_field) => // No error!
1969             println!("It was fancy-- {}!", fancy_field.num),
1970     }
1971     // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1972 }
1973 ```
1974 "##,
1975
1976 E0510: r##"
1977 Cannot mutate place in this match guard.
1978
1979 When matching on a variable it cannot be mutated in the match guards, as this
1980 could cause the match to be non-exhaustive:
1981
1982 ```compile_fail,E0510
1983 #![feature(nll, bind_by_move_pattern_guards)]
1984 let mut x = Some(0);
1985 match x {
1986     None => (),
1987     Some(v) if { x = None; false } => (),
1988     Some(_) => (), // No longer matches
1989 }
1990 ```
1991
1992 Here executing `x = None` would modify the value being matched and require us
1993 to go "back in time" to the `None` arm.
1994 "##,
1995
1996 E0579: r##"
1997 When matching against an exclusive range, the compiler verifies that the range
1998 is non-empty. Exclusive range patterns include the start point but not the end
1999 point, so this is equivalent to requiring the start of the range to be less
2000 than the end of the range.
2001
2002 For example:
2003
2004 ```compile_fail
2005 match 5u32 {
2006     // This range is ok, albeit pointless.
2007     1 .. 2 => {}
2008     // This range is empty, and the compiler can tell.
2009     5 .. 5 => {}
2010 }
2011 ```
2012 "##,
2013
2014 E0515: r##"
2015 Cannot return value that references local variable
2016
2017 Local variables, function parameters and temporaries are all dropped before the
2018 end of the function body. So a reference to them cannot be returned.
2019
2020 ```compile_fail,E0515
2021 #![feature(nll)]
2022 fn get_dangling_reference() -> &'static i32 {
2023     let x = 0;
2024     &x
2025 }
2026 ```
2027
2028 ```compile_fail,E0515
2029 #![feature(nll)]
2030 use std::slice::Iter;
2031 fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
2032     let v = vec![1, 2, 3];
2033     v.iter()
2034 }
2035 ```
2036
2037 Consider returning an owned value instead:
2038
2039 ```
2040 use std::vec::IntoIter;
2041
2042 fn get_integer() -> i32 {
2043     let x = 0;
2044     x
2045 }
2046
2047 fn get_owned_iterator() -> IntoIter<i32> {
2048     let v = vec![1, 2, 3];
2049     v.into_iter()
2050 }
2051 ```
2052 "##,
2053
2054 E0595: r##"
2055 Closures cannot mutate immutable captured variables.
2056
2057 Erroneous code example:
2058
2059 ```compile_fail,E0595
2060 let x = 3; // error: closure cannot assign to immutable local variable `x`
2061 let mut c = || { x += 1 };
2062 ```
2063
2064 Make the variable binding mutable:
2065
2066 ```
2067 let mut x = 3; // ok!
2068 let mut c = || { x += 1 };
2069 ```
2070 "##,
2071
2072 E0596: r##"
2073 This error occurs because you tried to mutably borrow a non-mutable variable.
2074
2075 Example of erroneous code:
2076
2077 ```compile_fail,E0596
2078 let x = 1;
2079 let y = &mut x; // error: cannot borrow mutably
2080 ```
2081
2082 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2083 fails. To fix this error, you need to make `x` mutable:
2084
2085 ```
2086 let mut x = 1;
2087 let y = &mut x; // ok!
2088 ```
2089 "##,
2090
2091 E0597: r##"
2092 This error occurs because a borrow was made inside a variable which has a
2093 greater lifetime than the borrowed one.
2094
2095 Example of erroneous code:
2096
2097 ```compile_fail,E0597
2098 struct Foo<'a> {
2099     x: Option<&'a u32>,
2100 }
2101
2102 let mut x = Foo { x: None };
2103 let y = 0;
2104 x.x = Some(&y); // error: `y` does not live long enough
2105 ```
2106
2107 In here, `x` is created before `y` and therefore has a greater lifetime. Always
2108 keep in mind that values in a scope are dropped in the opposite order they are
2109 created. So to fix the previous example, just make the `y` lifetime greater than
2110 the `x`'s one:
2111
2112 ```
2113 struct Foo<'a> {
2114     x: Option<&'a u32>,
2115 }
2116
2117 let y = 0;
2118 let mut x = Foo { x: None };
2119 x.x = Some(&y);
2120 ```
2121 "##,
2122
2123 E0626: r##"
2124 This error occurs because a borrow in a generator persists across a
2125 yield point.
2126
2127 ```compile_fail,E0626
2128 # #![feature(generators, generator_trait)]
2129 # use std::ops::Generator;
2130 let mut b = || {
2131     let a = &String::new(); // <-- This borrow...
2132     yield (); // ...is still in scope here, when the yield occurs.
2133     println!("{}", a);
2134 };
2135 unsafe { b.resume() };
2136 ```
2137
2138 At present, it is not permitted to have a yield that occurs while a
2139 borrow is still in scope. To resolve this error, the borrow must
2140 either be "contained" to a smaller scope that does not overlap the
2141 yield or else eliminated in another way. So, for example, we might
2142 resolve the previous example by removing the borrow and just storing
2143 the integer by value:
2144
2145 ```
2146 # #![feature(generators, generator_trait)]
2147 # use std::ops::Generator;
2148 let mut b = || {
2149     let a = 3;
2150     yield ();
2151     println!("{}", a);
2152 };
2153 unsafe { b.resume() };
2154 ```
2155
2156 This is a very simple case, of course. In more complex cases, we may
2157 wish to have more than one reference to the value that was borrowed --
2158 in those cases, something like the `Rc` or `Arc` types may be useful.
2159
2160 This error also frequently arises with iteration:
2161
2162 ```compile_fail,E0626
2163 # #![feature(generators, generator_trait)]
2164 # use std::ops::Generator;
2165 let mut b = || {
2166   let v = vec![1,2,3];
2167   for &x in &v { // <-- borrow of `v` is still in scope...
2168     yield x; // ...when this yield occurs.
2169   }
2170 };
2171 unsafe { b.resume() };
2172 ```
2173
2174 Such cases can sometimes be resolved by iterating "by value" (or using
2175 `into_iter()`) to avoid borrowing:
2176
2177 ```
2178 # #![feature(generators, generator_trait)]
2179 # use std::ops::Generator;
2180 let mut b = || {
2181   let v = vec![1,2,3];
2182   for x in v { // <-- Take ownership of the values instead!
2183     yield x; // <-- Now yield is OK.
2184   }
2185 };
2186 unsafe { b.resume() };
2187 ```
2188
2189 If taking ownership is not an option, using indices can work too:
2190
2191 ```
2192 # #![feature(generators, generator_trait)]
2193 # use std::ops::Generator;
2194 let mut b = || {
2195   let v = vec![1,2,3];
2196   let len = v.len(); // (*)
2197   for i in 0..len {
2198     let x = v[i]; // (*)
2199     yield x; // <-- Now yield is OK.
2200   }
2201 };
2202 unsafe { b.resume() };
2203
2204 // (*) -- Unfortunately, these temporaries are currently required.
2205 // See <https://github.com/rust-lang/rust/issues/43122>.
2206 ```
2207 "##,
2208
2209 E0712: r##"
2210 This error occurs because a borrow of a thread-local variable was made inside a
2211 function which outlived the lifetime of the function.
2212
2213 Example of erroneous code:
2214
2215 ```compile_fail,E0712
2216 #![feature(nll)]
2217 #![feature(thread_local)]
2218
2219 #[thread_local]
2220 static FOO: u8 = 3;
2221
2222 fn main() {
2223     let a = &FOO; // error: thread-local variable borrowed past end of function
2224
2225     std::thread::spawn(move || {
2226         println!("{}", a);
2227     });
2228 }
2229 ```
2230 "##,
2231
2232 E0713: r##"
2233 This error occurs when an attempt is made to borrow state past the end of the
2234 lifetime of a type that implements the `Drop` trait.
2235
2236 Example of erroneous code:
2237
2238 ```compile_fail,E0713
2239 #![feature(nll)]
2240
2241 pub struct S<'a> { data: &'a mut String }
2242
2243 impl<'a> Drop for S<'a> {
2244     fn drop(&mut self) { self.data.push_str("being dropped"); }
2245 }
2246
2247 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2248 ```
2249
2250 Here, `demo` tries to borrow the string data held within its
2251 argument `s` and then return that borrow. However, `S` is
2252 declared as implementing `Drop`.
2253
2254 Structs implementing the `Drop` trait have an implicit destructor that
2255 gets called when they go out of scope. This destructor gets exclusive
2256 access to the fields of the struct when it runs.
2257
2258 This means that when `s` reaches the end of `demo`, its destructor
2259 gets exclusive access to its `&mut`-borrowed string data.  allowing
2260 another borrow of that string data (`p`), to exist across the drop of
2261 `s` would be a violation of the principle that `&mut`-borrows have
2262 exclusive, unaliased access to their referenced data.
2263
2264 This error can be fixed by changing `demo` so that the destructor does
2265 not run while the string-data is borrowed; for example by taking `S`
2266 by reference:
2267
2268 ```
2269 #![feature(nll)]
2270
2271 pub struct S<'a> { data: &'a mut String }
2272
2273 impl<'a> Drop for S<'a> {
2274     fn drop(&mut self) { self.data.push_str("being dropped"); }
2275 }
2276
2277 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2278 ```
2279
2280 Note that this approach needs a reference to S with lifetime `'a`.
2281 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2282 that after `demo` finishes executing, something else (such as the
2283 destructor!) could access `s.data` after the end of that shorter
2284 lifetime, which would again violate the `&mut`-borrow's exclusive
2285 access.
2286 "##,
2287
2288 E0716: r##"
2289 This error indicates that a temporary value is being dropped
2290 while a borrow is still in active use.
2291
2292 Erroneous code example:
2293
2294 ```compile_fail,E0716
2295 # #![feature(nll)]
2296 fn foo() -> i32 { 22 }
2297 fn bar(x: &i32) -> &i32 { x }
2298 let p = bar(&foo());
2299          // ------ creates a temporary
2300 let q = *p;
2301 ```
2302
2303 Here, the expression `&foo()` is borrowing the expression
2304 `foo()`. As `foo()` is call to a function, and not the name of
2305 a variable, this creates a **temporary** -- that temporary stores
2306 the return value from `foo()` so that it can be borrowed.
2307 So you might imagine that `let p = bar(&foo())` is equivalent
2308 to this:
2309
2310 ```compile_fail,E0597
2311 # fn foo() -> i32 { 22 }
2312 # fn bar(x: &i32) -> &i32 { x }
2313 let p = {
2314   let tmp = foo(); // the temporary
2315   bar(&tmp)
2316 }; // <-- tmp is freed as we exit this block
2317 let q = p;
2318 ```
2319
2320 Whenever a temporary is created, it is automatically dropped (freed)
2321 according to fixed rules. Ordinarily, the temporary is dropped
2322 at the end of the enclosing statement -- in this case, after the `let`.
2323 This is illustrated in the example above by showing that `tmp` would
2324 be freed as we exit the block.
2325
2326 To fix this problem, you need to create a local variable
2327 to store the value in rather than relying on a temporary.
2328 For example, you might change the original program to
2329 the following:
2330
2331 ```
2332 fn foo() -> i32 { 22 }
2333 fn bar(x: &i32) -> &i32 { x }
2334 let value = foo(); // dropped at the end of the enclosing block
2335 let p = bar(&value);
2336 let q = *p;
2337 ```
2338
2339 By introducing the explicit `let value`, we allocate storage
2340 that will last until the end of the enclosing block (when `value`
2341 goes out of scope). When we borrow `&value`, we are borrowing a
2342 local variable that already exists, and hence no temporary is created.
2343
2344 Temporaries are not always dropped at the end of the enclosing
2345 statement. In simple cases where the `&` expression is immediately
2346 stored into a variable, the compiler will automatically extend
2347 the lifetime of the temporary until the end of the enclosinb
2348 block. Therefore, an alternative way to fix the original
2349 program is to write `let tmp = &foo()` and not `let tmp = foo()`:
2350
2351 ```
2352 fn foo() -> i32 { 22 }
2353 fn bar(x: &i32) -> &i32 { x }
2354 let value = &foo();
2355 let p = bar(value);
2356 let q = *p;
2357 ```
2358
2359 Here, we are still borrowing `foo()`, but as the borrow is assigned
2360 directly into a variable, the temporary will not be dropped until
2361 the end of the enclosing block. Similar rules apply when temporaries
2362 are stored into aggregate structures like a tuple or struct:
2363
2364 ```
2365 // Here, two temporaries are created, but
2366 // as they are stored directly into `value`,
2367 // they are not dropped until the end of the
2368 // enclosing block.
2369 fn foo() -> i32 { 22 }
2370 let value = (&foo(), &foo());
2371 ```
2372 "##,
2373
2374 }
2375
2376 register_diagnostics! {
2377 //  E0298, // cannot compare constants
2378 //  E0299, // mismatched types between arms
2379 //  E0471, // constant evaluation error (in pattern)
2380 //    E0385, // {} in an aliasable location
2381     E0493, // destructors cannot be evaluated at compile-time
2382     E0521,  // borrowed data escapes outside of closure
2383     E0524, // two closures require unique access to `..` at the same time
2384     E0526, // shuffle indices are not constant
2385     E0594, // cannot assign to {}
2386     E0598, // lifetime of {} is too short to guarantee its contents can be...
2387     E0625, // thread-local statics cannot be accessed at compile-time
2388 }