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