]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/diagnostics.rs
Rollup merge of #57860 - jethrogb:jb/sgx-os-ffi, r=joshtriplett
[rust.git] / src / librustc_mir / diagnostics.rs
1 #![allow(non_snake_case)]
2
3 register_long_diagnostics! {
4
5
6 E0001: r##"
7 #### Note: this error code is no longer emitted by the compiler.
8
9 This error suggests that the expression arm corresponding to the noted pattern
10 will never be reached as for all possible values of the expression being
11 matched, one of the preceding patterns will match.
12
13 This means that perhaps some of the preceding patterns are too general, this
14 one is too specific or the ordering is incorrect.
15
16 For example, the following `match` block has too many arms:
17
18 ```
19 match Some(0) {
20     Some(bar) => {/* ... */}
21     x => {/* ... */} // This handles the `None` case
22     _ => {/* ... */} // All possible cases have already been handled
23 }
24 ```
25
26 `match` blocks have their patterns matched in order, so, for example, putting
27 a wildcard arm above a more specific arm will make the latter arm irrelevant.
28
29 Ensure the ordering of the match arm is correct and remove any superfluous
30 arms.
31 "##,
32
33 E0002: r##"
34 #### Note: this error code is no longer emitted by the compiler.
35
36 This error indicates that an empty match expression is invalid because the type
37 it is matching on is non-empty (there exist values of this type). In safe code
38 it is impossible to create an instance of an empty type, so empty match
39 expressions are almost never desired. This error is typically fixed by adding
40 one or more cases to the match expression.
41
42 An example of an empty type is `enum Empty { }`. So, the following will work:
43
44 ```
45 enum Empty {}
46
47 fn foo(x: Empty) {
48     match x {
49         // empty
50     }
51 }
52 ```
53
54 However, this won't:
55
56 ```compile_fail
57 fn foo(x: Option<String>) {
58     match x {
59         // empty
60     }
61 }
62 ```
63 "##,
64
65 E0004: r##"
66 This error indicates that the compiler cannot guarantee a matching pattern for
67 one or more possible inputs to a match expression. Guaranteed matches are
68 required in order to assign values to match expressions, or alternatively,
69 determine the flow of execution. Erroneous code example:
70
71 ```compile_fail,E0004
72 enum Terminator {
73     HastaLaVistaBaby,
74     TalkToMyHand,
75 }
76
77 let x = Terminator::HastaLaVistaBaby;
78
79 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
80     Terminator::TalkToMyHand => {}
81 }
82 ```
83
84 If you encounter this error you must alter your patterns so that every possible
85 value of the input type is matched. For types with a small number of variants
86 (like enums) you should probably cover all cases explicitly. Alternatively, the
87 underscore `_` wildcard pattern can be added after all other patterns to match
88 "anything else". Example:
89
90 ```
91 enum Terminator {
92     HastaLaVistaBaby,
93     TalkToMyHand,
94 }
95
96 let x = Terminator::HastaLaVistaBaby;
97
98 match x {
99     Terminator::TalkToMyHand => {}
100     Terminator::HastaLaVistaBaby => {}
101 }
102
103 // or:
104
105 match x {
106     Terminator::TalkToMyHand => {}
107     _ => {}
108 }
109 ```
110 "##,
111
112 E0005: r##"
113 Patterns used to bind names must be irrefutable, that is, they must guarantee
114 that a name will be extracted in all cases. Erroneous code example:
115
116 ```compile_fail,E0005
117 let x = Some(1);
118 let Some(y) = x;
119 // error: refutable pattern in local binding: `None` not covered
120 ```
121
122 If you encounter this error you probably need to use a `match` or `if let` to
123 deal with the possibility of failure. Example:
124
125 ```
126 let x = Some(1);
127
128 match x {
129     Some(y) => {
130         // do something
131     },
132     None => {}
133 }
134
135 // or:
136
137 if let Some(y) = x {
138     // do something
139 }
140 ```
141 "##,
142
143 E0007: r##"
144 This error indicates that the bindings in a match arm would require a value to
145 be moved into more than one location, thus violating unique ownership. Code
146 like the following is invalid as it requires the entire `Option<String>` to be
147 moved into a variable called `op_string` while simultaneously requiring the
148 inner `String` to be moved into a variable called `s`.
149
150 ```compile_fail,E0007
151 let x = Some("s".to_string());
152
153 match x {
154     op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
155     None => {},
156 }
157 ```
158
159 See also the error E0303.
160 "##,
161
162 E0008: r##"
163 Names bound in match arms retain their type in pattern guards. As such, if a
164 name is bound by move in a pattern, it should also be moved to wherever it is
165 referenced in the pattern guard code. Doing so however would prevent the name
166 from being available in the body of the match arm. Consider the following:
167
168 ```compile_fail,E0008
169 match Some("hi".to_string()) {
170     Some(s) if s.len() == 0 => {}, // use s.
171     _ => {},
172 }
173 ```
174
175 The variable `s` has type `String`, and its use in the guard is as a variable of
176 type `String`. The guard code effectively executes in a separate scope to the
177 body of the arm, so the value would be moved into this anonymous scope and
178 therefore becomes unavailable in the body of the arm.
179
180 The problem above can be solved by using the `ref` keyword.
181
182 ```
183 match Some("hi".to_string()) {
184     Some(ref s) if s.len() == 0 => {},
185     _ => {},
186 }
187 ```
188
189 Though this example seems innocuous and easy to solve, the problem becomes clear
190 when it encounters functions which consume the value:
191
192 ```compile_fail,E0008
193 struct A{}
194
195 impl A {
196     fn consume(self) -> usize {
197         0
198     }
199 }
200
201 fn main() {
202     let a = Some(A{});
203     match a {
204         Some(y) if y.consume() > 0 => {}
205         _ => {}
206     }
207 }
208 ```
209
210 In this situation, even the `ref` keyword cannot solve it, since borrowed
211 content cannot be moved. This problem cannot be solved generally. If the value
212 can be cloned, here is a not-so-specific solution:
213
214 ```
215 #[derive(Clone)]
216 struct A{}
217
218 impl A {
219     fn consume(self) -> usize {
220         0
221     }
222 }
223
224 fn main() {
225     let a = Some(A{});
226     match a{
227         Some(ref y) if y.clone().consume() > 0 => {}
228         _ => {}
229     }
230 }
231 ```
232
233 If the value will be consumed in the pattern guard, using its clone will not
234 move its ownership, so the code works.
235 "##,
236
237 E0009: r##"
238 In a pattern, all values that don't implement the `Copy` trait have to be bound
239 the same way. The goal here is to avoid binding simultaneously by-move and
240 by-ref.
241
242 This limitation may be removed in a future version of Rust.
243
244 Erroneous code example:
245
246 ```compile_fail,E0009
247 struct X { x: (), }
248
249 let x = Some((X { x: () }, X { x: () }));
250 match x {
251     Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
252                             //        same pattern
253     None => panic!()
254 }
255 ```
256
257 You have two solutions:
258
259 Solution #1: Bind the pattern's values the same way.
260
261 ```
262 struct X { x: (), }
263
264 let x = Some((X { x: () }, X { x: () }));
265 match x {
266     Some((ref y, ref z)) => {},
267     // or Some((y, z)) => {}
268     None => panic!()
269 }
270 ```
271
272 Solution #2: Implement the `Copy` trait for the `X` structure.
273
274 However, please keep in mind that the first solution should be preferred.
275
276 ```
277 #[derive(Clone, Copy)]
278 struct X { x: (), }
279
280 let x = Some((X { x: () }, X { x: () }));
281 match x {
282     Some((y, ref z)) => {},
283     None => panic!()
284 }
285 ```
286 "##,
287
288 E0030: r##"
289 When matching against a range, the compiler verifies that the range is
290 non-empty.  Range patterns include both end-points, so this is equivalent to
291 requiring the start of the range to be less than or equal to the end of the
292 range.
293
294 For example:
295
296 ```compile_fail
297 match 5u32 {
298     // This range is ok, albeit pointless.
299     1 ..= 1 => {}
300     // This range is empty, and the compiler can tell.
301     1000 ..= 5 => {}
302 }
303 ```
304 "##,
305
306 E0158: r##"
307 `const` and `static` mean different things. A `const` is a compile-time
308 constant, an alias for a literal value. This property means you can match it
309 directly within a pattern.
310
311 The `static` keyword, on the other hand, guarantees a fixed location in memory.
312 This does not always mean that the value is constant. For example, a global
313 mutex can be declared `static` as well.
314
315 If you want to match against a `static`, consider using a guard instead:
316
317 ```
318 static FORTY_TWO: i32 = 42;
319
320 match Some(42) {
321     Some(x) if x == FORTY_TWO => {}
322     _ => {}
323 }
324 ```
325 "##,
326
327 E0162: r##"
328 #### 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/first-edition/unsafe.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/first-edition/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, ATOMIC_USIZE_INIT};
1131
1132 const A: AtomicUsize = ATOMIC_USIZE_INIT;
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, ATOMIC_USIZE_INIT};
1149
1150 static A: AtomicUsize = ATOMIC_USIZE_INIT;
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/stable/book/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/stable/book/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/stable/book/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 eat(val: Value) {}
1549
1550 fn main() {
1551     let x = Value{};
1552     {
1553         let _ref_to_val: &Value = &x;
1554         eat(x);
1555     }
1556 }
1557 ```
1558
1559 Here, the function `eat` takes the ownership of `x`. However,
1560 `x` cannot be moved because it was borrowed to `_ref_to_val`.
1561 To fix that you can do few different things:
1562
1563 * Try to avoid moving the variable.
1564 * Release borrow before move.
1565 * Implement the `Copy` trait on the type.
1566
1567 Examples:
1568
1569 ```
1570 struct Value {}
1571
1572 fn eat(val: &Value) {}
1573
1574 fn main() {
1575     let x = Value{};
1576     {
1577         let _ref_to_val: &Value = &x;
1578         eat(&x); // pass by reference, if it's possible
1579     }
1580 }
1581 ```
1582
1583 Or:
1584
1585 ```
1586 struct Value {}
1587
1588 fn eat(val: Value) {}
1589
1590 fn main() {
1591     let x = Value{};
1592     {
1593         let _ref_to_val: &Value = &x;
1594     }
1595     eat(x); // release borrow and then move it.
1596 }
1597 ```
1598
1599 Or:
1600
1601 ```
1602 #[derive(Clone, Copy)] // implement Copy trait
1603 struct Value {}
1604
1605 fn eat(val: Value) {}
1606
1607 fn main() {
1608     let x = Value{};
1609     {
1610         let _ref_to_val: &Value = &x;
1611         eat(x); // it will be copied here.
1612     }
1613 }
1614 ```
1615
1616 You can find more information about borrowing in the rust-book:
1617 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1618 "##,
1619
1620 E0506: r##"
1621 This error occurs when an attempt is made to assign to a borrowed value.
1622
1623 Example of erroneous code:
1624
1625 ```compile_fail,E0506
1626 struct FancyNum {
1627     num: u8,
1628 }
1629
1630 fn main() {
1631     let mut fancy_num = FancyNum { num: 5 };
1632     let fancy_ref = &fancy_num;
1633     fancy_num = FancyNum { num: 6 };
1634     // error: cannot assign to `fancy_num` because it is borrowed
1635
1636     println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1637 }
1638 ```
1639
1640 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1641 be assigned to a new value as it would invalidate the reference.
1642
1643 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1644
1645 ```
1646 struct FancyNum {
1647     num: u8,
1648 }
1649
1650 fn main() {
1651     let mut fancy_num = FancyNum { num: 5 };
1652     let moved_num = fancy_num;
1653     fancy_num = FancyNum { num: 6 };
1654
1655     println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1656 }
1657 ```
1658
1659 If the value has to be borrowed, try limiting the lifetime of the borrow using
1660 a scoped block:
1661
1662 ```
1663 struct FancyNum {
1664     num: u8,
1665 }
1666
1667 fn main() {
1668     let mut fancy_num = FancyNum { num: 5 };
1669
1670     {
1671         let fancy_ref = &fancy_num;
1672         println!("Ref: {}", fancy_ref.num);
1673     }
1674
1675     // Works because `fancy_ref` is no longer in scope
1676     fancy_num = FancyNum { num: 6 };
1677     println!("Num: {}", fancy_num.num);
1678 }
1679 ```
1680
1681 Or by moving the reference into a function:
1682
1683 ```
1684 struct FancyNum {
1685     num: u8,
1686 }
1687
1688 fn main() {
1689     let mut fancy_num = FancyNum { num: 5 };
1690
1691     print_fancy_ref(&fancy_num);
1692
1693     // Works because function borrow has ended
1694     fancy_num = FancyNum { num: 6 };
1695     println!("Num: {}", fancy_num.num);
1696 }
1697
1698 fn print_fancy_ref(fancy_ref: &FancyNum){
1699     println!("Ref: {}", fancy_ref.num);
1700 }
1701 ```
1702 "##,
1703
1704 E0507: r##"
1705 You tried to move out of a value which was borrowed. Erroneous code example:
1706
1707 ```compile_fail,E0507
1708 use std::cell::RefCell;
1709
1710 struct TheDarkKnight;
1711
1712 impl TheDarkKnight {
1713     fn nothing_is_true(self) {}
1714 }
1715
1716 fn main() {
1717     let x = RefCell::new(TheDarkKnight);
1718
1719     x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1720 }
1721 ```
1722
1723 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1724 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1725 which is a borrow of the content owned by the `RefCell`. To fix this error,
1726 you have three choices:
1727
1728 * Try to avoid moving the variable.
1729 * Somehow reclaim the ownership.
1730 * Implement the `Copy` trait on the type.
1731
1732 Examples:
1733
1734 ```
1735 use std::cell::RefCell;
1736
1737 struct TheDarkKnight;
1738
1739 impl TheDarkKnight {
1740     fn nothing_is_true(&self) {} // First case, we don't take ownership
1741 }
1742
1743 fn main() {
1744     let x = RefCell::new(TheDarkKnight);
1745
1746     x.borrow().nothing_is_true(); // ok!
1747 }
1748 ```
1749
1750 Or:
1751
1752 ```
1753 use std::cell::RefCell;
1754
1755 struct TheDarkKnight;
1756
1757 impl TheDarkKnight {
1758     fn nothing_is_true(self) {}
1759 }
1760
1761 fn main() {
1762     let x = RefCell::new(TheDarkKnight);
1763     let x = x.into_inner(); // we get back ownership
1764
1765     x.nothing_is_true(); // ok!
1766 }
1767 ```
1768
1769 Or:
1770
1771 ```
1772 use std::cell::RefCell;
1773
1774 #[derive(Clone, Copy)] // we implement the Copy trait
1775 struct TheDarkKnight;
1776
1777 impl TheDarkKnight {
1778     fn nothing_is_true(self) {}
1779 }
1780
1781 fn main() {
1782     let x = RefCell::new(TheDarkKnight);
1783
1784     x.borrow().nothing_is_true(); // ok!
1785 }
1786 ```
1787
1788 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1789
1790 ```compile_fail,E0507
1791 struct TheDarkKnight;
1792
1793 impl TheDarkKnight {
1794     fn nothing_is_true(self) {}
1795 }
1796
1797 struct Batcave {
1798     knight: TheDarkKnight
1799 }
1800
1801 fn main() {
1802     let mut cave = Batcave {
1803         knight: TheDarkKnight
1804     };
1805     let borrowed = &mut cave;
1806
1807     borrowed.knight.nothing_is_true(); // E0507
1808 }
1809 ```
1810
1811 It is fine only if you put something back. `mem::replace` can be used for that:
1812
1813 ```
1814 # struct TheDarkKnight;
1815 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1816 # struct Batcave { knight: TheDarkKnight }
1817 use std::mem;
1818
1819 let mut cave = Batcave {
1820     knight: TheDarkKnight
1821 };
1822 let borrowed = &mut cave;
1823
1824 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1825 ```
1826
1827 You can find more information about borrowing in the rust-book:
1828 http://doc.rust-lang.org/book/first-edition/references-and-borrowing.html
1829 "##,
1830
1831 E0508: r##"
1832 A value was moved out of a non-copy fixed-size array.
1833
1834 Example of erroneous code:
1835
1836 ```compile_fail,E0508
1837 struct NonCopy;
1838
1839 fn main() {
1840     let array = [NonCopy; 1];
1841     let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1842                            //        a non-copy fixed-size array
1843 }
1844 ```
1845
1846 The first element was moved out of the array, but this is not
1847 possible because `NonCopy` does not implement the `Copy` trait.
1848
1849 Consider borrowing the element instead of moving it:
1850
1851 ```
1852 struct NonCopy;
1853
1854 fn main() {
1855     let array = [NonCopy; 1];
1856     let _value = &array[0]; // Borrowing is allowed, unlike moving.
1857 }
1858 ```
1859
1860 Alternatively, if your type implements `Clone` and you need to own the value,
1861 consider borrowing and then cloning:
1862
1863 ```
1864 #[derive(Clone)]
1865 struct NonCopy;
1866
1867 fn main() {
1868     let array = [NonCopy; 1];
1869     // Now you can clone the array element.
1870     let _value = array[0].clone();
1871 }
1872 ```
1873 "##,
1874
1875 E0509: r##"
1876 This error occurs when an attempt is made to move out of a value whose type
1877 implements the `Drop` trait.
1878
1879 Example of erroneous code:
1880
1881 ```compile_fail,E0509
1882 struct FancyNum {
1883     num: usize
1884 }
1885
1886 struct DropStruct {
1887     fancy: FancyNum
1888 }
1889
1890 impl Drop for DropStruct {
1891     fn drop(&mut self) {
1892         // Destruct DropStruct, possibly using FancyNum
1893     }
1894 }
1895
1896 fn main() {
1897     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1898     let fancy_field = drop_struct.fancy; // Error E0509
1899     println!("Fancy: {}", fancy_field.num);
1900     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1901 }
1902 ```
1903
1904 Here, we tried to move a field out of a struct of type `DropStruct` which
1905 implements the `Drop` trait. However, a struct cannot be dropped if one or
1906 more of its fields have been moved.
1907
1908 Structs implementing the `Drop` trait have an implicit destructor that gets
1909 called when they go out of scope. This destructor may use the fields of the
1910 struct, so moving out of the struct could make it impossible to run the
1911 destructor. Therefore, we must think of all values whose type implements the
1912 `Drop` trait as single units whose fields cannot be moved.
1913
1914 This error can be fixed by creating a reference to the fields of a struct,
1915 enum, or tuple using the `ref` keyword:
1916
1917 ```
1918 struct FancyNum {
1919     num: usize
1920 }
1921
1922 struct DropStruct {
1923     fancy: FancyNum
1924 }
1925
1926 impl Drop for DropStruct {
1927     fn drop(&mut self) {
1928         // Destruct DropStruct, possibly using FancyNum
1929     }
1930 }
1931
1932 fn main() {
1933     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1934     let ref fancy_field = drop_struct.fancy; // No more errors!
1935     println!("Fancy: {}", fancy_field.num);
1936     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1937 }
1938 ```
1939
1940 Note that this technique can also be used in the arms of a match expression:
1941
1942 ```
1943 struct FancyNum {
1944     num: usize
1945 }
1946
1947 enum DropEnum {
1948     Fancy(FancyNum)
1949 }
1950
1951 impl Drop for DropEnum {
1952     fn drop(&mut self) {
1953         // Destruct DropEnum, possibly using FancyNum
1954     }
1955 }
1956
1957 fn main() {
1958     // Creates and enum of type `DropEnum`, which implements `Drop`
1959     let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1960     match drop_enum {
1961         // Creates a reference to the inside of `DropEnum::Fancy`
1962         DropEnum::Fancy(ref fancy_field) => // No error!
1963             println!("It was fancy-- {}!", fancy_field.num),
1964     }
1965     // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1966 }
1967 ```
1968 "##,
1969
1970 E0510: r##"
1971 Cannot mutate place in this match guard.
1972
1973 When matching on a variable it cannot be mutated in the match guards, as this
1974 could cause the match to be non-exhaustive:
1975
1976 ```compile_fail,E0510
1977 #![feature(nll, bind_by_move_pattern_guards)]
1978 let mut x = Some(0);
1979 match x {
1980     None => (),
1981     Some(v) if { x = None; false } => (),
1982     Some(_) => (), // No longer matches
1983 }
1984 ```
1985
1986 Here executing `x = None` would modify the value being matched and require us
1987 to go "back in time" to the `None` arm.
1988 "##,
1989
1990 E0579: r##"
1991 When matching against an exclusive range, the compiler verifies that the range
1992 is non-empty. Exclusive range patterns include the start point but not the end
1993 point, so this is equivalent to requiring the start of the range to be less
1994 than the end of the range.
1995
1996 For example:
1997
1998 ```compile_fail
1999 match 5u32 {
2000     // This range is ok, albeit pointless.
2001     1 .. 2 => {}
2002     // This range is empty, and the compiler can tell.
2003     5 .. 5 => {}
2004 }
2005 ```
2006 "##,
2007
2008 E0515: r##"
2009 Cannot return value that references local variable
2010
2011 Local variables, function parameters and temporaries are all dropped before the
2012 end of the function body. So a reference to them cannot be returned.
2013
2014 ```compile_fail,E0515
2015 #![feature(nll)]
2016 fn get_dangling_reference() -> &'static i32 {
2017     let x = 0;
2018     &x
2019 }
2020 ```
2021
2022 ```compile_fail,E0515
2023 #![feature(nll)]
2024 use std::slice::Iter;
2025 fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
2026     let v = vec![1, 2, 3];
2027     v.iter()
2028 }
2029 ```
2030
2031 Consider returning an owned value instead:
2032
2033 ```
2034 use std::vec::IntoIter;
2035
2036 fn get_integer() -> i32 {
2037     let x = 0;
2038     x
2039 }
2040
2041 fn get_owned_iterator() -> IntoIter<i32> {
2042     let v = vec![1, 2, 3];
2043     v.into_iter()
2044 }
2045 ```
2046 "##,
2047
2048 E0595: r##"
2049 Closures cannot mutate immutable captured variables.
2050
2051 Erroneous code example:
2052
2053 ```compile_fail,E0595
2054 let x = 3; // error: closure cannot assign to immutable local variable `x`
2055 let mut c = || { x += 1 };
2056 ```
2057
2058 Make the variable binding mutable:
2059
2060 ```
2061 let mut x = 3; // ok!
2062 let mut c = || { x += 1 };
2063 ```
2064 "##,
2065
2066 E0596: r##"
2067 This error occurs because you tried to mutably borrow a non-mutable variable.
2068
2069 Example of erroneous code:
2070
2071 ```compile_fail,E0596
2072 let x = 1;
2073 let y = &mut x; // error: cannot borrow mutably
2074 ```
2075
2076 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2077 fails. To fix this error, you need to make `x` mutable:
2078
2079 ```
2080 let mut x = 1;
2081 let y = &mut x; // ok!
2082 ```
2083 "##,
2084
2085 E0597: r##"
2086 This error occurs because a borrow was made inside a variable which has a
2087 greater lifetime than the borrowed one.
2088
2089 Example of erroneous code:
2090
2091 ```compile_fail,E0597
2092 struct Foo<'a> {
2093     x: Option<&'a u32>,
2094 }
2095
2096 let mut x = Foo { x: None };
2097 let y = 0;
2098 x.x = Some(&y); // error: `y` does not live long enough
2099 ```
2100
2101 In here, `x` is created before `y` and therefore has a greater lifetime. Always
2102 keep in mind that values in a scope are dropped in the opposite order they are
2103 created. So to fix the previous example, just make the `y` lifetime greater than
2104 the `x`'s one:
2105
2106 ```
2107 struct Foo<'a> {
2108     x: Option<&'a u32>,
2109 }
2110
2111 let y = 0;
2112 let mut x = Foo { x: None };
2113 x.x = Some(&y);
2114 ```
2115 "##,
2116
2117 E0626: r##"
2118 This error occurs because a borrow in a generator persists across a
2119 yield point.
2120
2121 ```compile_fail,E0626
2122 # #![feature(generators, generator_trait)]
2123 # use std::ops::Generator;
2124 let mut b = || {
2125     let a = &String::new(); // <-- This borrow...
2126     yield (); // ...is still in scope here, when the yield occurs.
2127     println!("{}", a);
2128 };
2129 unsafe { b.resume() };
2130 ```
2131
2132 At present, it is not permitted to have a yield that occurs while a
2133 borrow is still in scope. To resolve this error, the borrow must
2134 either be "contained" to a smaller scope that does not overlap the
2135 yield or else eliminated in another way. So, for example, we might
2136 resolve the previous example by removing the borrow and just storing
2137 the integer by value:
2138
2139 ```
2140 # #![feature(generators, generator_trait)]
2141 # use std::ops::Generator;
2142 let mut b = || {
2143     let a = 3;
2144     yield ();
2145     println!("{}", a);
2146 };
2147 unsafe { b.resume() };
2148 ```
2149
2150 This is a very simple case, of course. In more complex cases, we may
2151 wish to have more than one reference to the value that was borrowed --
2152 in those cases, something like the `Rc` or `Arc` types may be useful.
2153
2154 This error also frequently arises with iteration:
2155
2156 ```compile_fail,E0626
2157 # #![feature(generators, generator_trait)]
2158 # use std::ops::Generator;
2159 let mut b = || {
2160   let v = vec![1,2,3];
2161   for &x in &v { // <-- borrow of `v` is still in scope...
2162     yield x; // ...when this yield occurs.
2163   }
2164 };
2165 unsafe { b.resume() };
2166 ```
2167
2168 Such cases can sometimes be resolved by iterating "by value" (or using
2169 `into_iter()`) to avoid borrowing:
2170
2171 ```
2172 # #![feature(generators, generator_trait)]
2173 # use std::ops::Generator;
2174 let mut b = || {
2175   let v = vec![1,2,3];
2176   for x in v { // <-- Take ownership of the values instead!
2177     yield x; // <-- Now yield is OK.
2178   }
2179 };
2180 unsafe { b.resume() };
2181 ```
2182
2183 If taking ownership is not an option, using indices can work too:
2184
2185 ```
2186 # #![feature(generators, generator_trait)]
2187 # use std::ops::Generator;
2188 let mut b = || {
2189   let v = vec![1,2,3];
2190   let len = v.len(); // (*)
2191   for i in 0..len {
2192     let x = v[i]; // (*)
2193     yield x; // <-- Now yield is OK.
2194   }
2195 };
2196 unsafe { b.resume() };
2197
2198 // (*) -- Unfortunately, these temporaries are currently required.
2199 // See <https://github.com/rust-lang/rust/issues/43122>.
2200 ```
2201 "##,
2202
2203 E0712: r##"
2204 This error occurs because a borrow of a thread-local variable was made inside a
2205 function which outlived the lifetime of the function.
2206
2207 Example of erroneous code:
2208
2209 ```compile_fail,E0712
2210 #![feature(nll)]
2211 #![feature(thread_local)]
2212
2213 #[thread_local]
2214 static FOO: u8 = 3;
2215
2216 fn main() {
2217     let a = &FOO; // error: thread-local variable borrowed past end of function
2218
2219     std::thread::spawn(move || {
2220         println!("{}", a);
2221     });
2222 }
2223 ```
2224 "##,
2225
2226 E0713: r##"
2227 This error occurs when an attempt is made to borrow state past the end of the
2228 lifetime of a type that implements the `Drop` trait.
2229
2230 Example of erroneous code:
2231
2232 ```compile_fail,E0713
2233 #![feature(nll)]
2234
2235 pub struct S<'a> { data: &'a mut String }
2236
2237 impl<'a> Drop for S<'a> {
2238     fn drop(&mut self) { self.data.push_str("being dropped"); }
2239 }
2240
2241 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2242 ```
2243
2244 Here, `demo` tries to borrow the string data held within its
2245 argument `s` and then return that borrow. However, `S` is
2246 declared as implementing `Drop`.
2247
2248 Structs implementing the `Drop` trait have an implicit destructor that
2249 gets called when they go out of scope. This destructor gets exclusive
2250 access to the fields of the struct when it runs.
2251
2252 This means that when `s` reaches the end of `demo`, its destructor
2253 gets exclusive access to its `&mut`-borrowed string data.  allowing
2254 another borrow of that string data (`p`), to exist across the drop of
2255 `s` would be a violation of the principle that `&mut`-borrows have
2256 exclusive, unaliased access to their referenced data.
2257
2258 This error can be fixed by changing `demo` so that the destructor does
2259 not run while the string-data is borrowed; for example by taking `S`
2260 by reference:
2261
2262 ```
2263 #![feature(nll)]
2264
2265 pub struct S<'a> { data: &'a mut String }
2266
2267 impl<'a> Drop for S<'a> {
2268     fn drop(&mut self) { self.data.push_str("being dropped"); }
2269 }
2270
2271 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2272 ```
2273
2274 Note that this approach needs a reference to S with lifetime `'a`.
2275 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2276 that after `demo` finishes executing, something else (such as the
2277 destructor!) could access `s.data` after the end of that shorter
2278 lifetime, which would again violate the `&mut`-borrow's exclusive
2279 access.
2280 "##,
2281
2282 E0716: r##"
2283 This error indicates that a temporary value is being dropped
2284 while a borrow is still in active use.
2285
2286 Erroneous code example:
2287
2288 ```compile_fail,E0716
2289 # #![feature(nll)]
2290 fn foo() -> i32 { 22 }
2291 fn bar(x: &i32) -> &i32 { x }
2292 let p = bar(&foo());
2293          // ------ creates a temporary
2294 let q = *p;
2295 ```
2296
2297 Here, the expression `&foo()` is borrowing the expression
2298 `foo()`. As `foo()` is call to a function, and not the name of
2299 a variable, this creates a **temporary** -- that temporary stores
2300 the return value from `foo()` so that it can be borrowed.
2301 So you might imagine that `let p = bar(&foo())` is equivalent
2302 to this:
2303
2304 ```compile_fail,E0597
2305 # fn foo() -> i32 { 22 }
2306 # fn bar(x: &i32) -> &i32 { x }
2307 let p = {
2308   let tmp = foo(); // the temporary
2309   bar(&tmp)
2310 }; // <-- tmp is freed as we exit this block
2311 let q = p;
2312 ```
2313
2314 Whenever a temporary is created, it is automatically dropped (freed)
2315 according to fixed rules. Ordinarily, the temporary is dropped
2316 at the end of the enclosing statement -- in this case, after the `let`.
2317 This is illustrated in the example above by showing that `tmp` would
2318 be freed as we exit the block.
2319
2320 To fix this problem, you need to create a local variable
2321 to store the value in rather than relying on a temporary.
2322 For example, you might change the original program to
2323 the following:
2324
2325 ```
2326 fn foo() -> i32 { 22 }
2327 fn bar(x: &i32) -> &i32 { x }
2328 let value = foo(); // dropped at the end of the enclosing block
2329 let p = bar(&value);
2330 let q = *p;
2331 ```
2332
2333 By introducing the explicit `let value`, we allocate storage
2334 that will last until the end of the enclosing block (when `value`
2335 goes out of scope). When we borrow `&value`, we are borrowing a
2336 local variable that already exists, and hence no temporary is created.
2337
2338 Temporaries are not always dropped at the end of the enclosing
2339 statement. In simple cases where the `&` expression is immediately
2340 stored into a variable, the compiler will automatically extend
2341 the lifetime of the temporary until the end of the enclosing
2342 block. Therefore, an alternative way to fix the original
2343 program is to write `let tmp = &foo()` and not `let tmp = foo()`:
2344
2345 ```
2346 fn foo() -> i32 { 22 }
2347 fn bar(x: &i32) -> &i32 { x }
2348 let value = &foo();
2349 let p = bar(value);
2350 let q = *p;
2351 ```
2352
2353 Here, we are still borrowing `foo()`, but as the borrow is assigned
2354 directly into a variable, the temporary will not be dropped until
2355 the end of the enclosing block. Similar rules apply when temporaries
2356 are stored into aggregate structures like a tuple or struct:
2357
2358 ```
2359 // Here, two temporaries are created, but
2360 // as they are stored directly into `value`,
2361 // they are not dropped until the end of the
2362 // enclosing block.
2363 fn foo() -> i32 { 22 }
2364 let value = (&foo(), &foo());
2365 ```
2366 "##,
2367
2368 }
2369
2370 register_diagnostics! {
2371 //  E0298, // cannot compare constants
2372 //  E0299, // mismatched types between arms
2373 //  E0471, // constant evaluation error (in pattern)
2374 //    E0385, // {} in an aliasable location
2375     E0493, // destructors cannot be evaluated at compile-time
2376     E0521,  // borrowed data escapes outside of closure
2377     E0524, // two closures require unique access to `..` at the same time
2378     E0526, // shuffle indices are not constant
2379     E0594, // cannot assign to {}
2380     E0598, // lifetime of {} is too short to guarantee its contents can be...
2381     E0625, // thread-local statics cannot be accessed at compile-time
2382 }