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