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