]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/borrowck/check_loans.rs
Doc says to avoid mixing allocator instead of forbiding it
[rust.git] / src / librustc / middle / borrowck / check_loans.rs
1 // Copyright 2012-2013 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 // ----------------------------------------------------------------------
12 // Checking loans
13 //
14 // Phase 2 of check: we walk down the tree and check that:
15 // 1. assignments are always made to mutable locations;
16 // 2. loans made in overlapping scopes do not conflict
17 // 3. assignments do not affect things loaned out as immutable
18 // 4. moves do not affect things loaned out in any way
19
20
21 use middle::borrowck::*;
22 use middle::expr_use_visitor as euv;
23 use middle::mem_categorization as mc;
24 use middle::ty;
25 use syntax::ast;
26 use syntax::codemap::Span;
27 use util::ppaux::Repr;
28
29 use std::rc::Rc;
30
31 // FIXME (#16118): These functions are intended to allow the borrow checker to
32 // be less precise in its handling of Box while still allowing moves out of a
33 // Box. They should be removed when OwnedPtr is removed from LoanPath.
34
35 fn owned_ptr_base_path<'a>(loan_path: &'a LoanPath) -> &'a LoanPath {
36     //! Returns the base of the leftmost dereference of an OwnedPtr in
37     //! `loan_path`. If there is no dereference of an OwnedPtr in `loan_path`,
38     //! then it just returns `loan_path` itself.
39
40     return match owned_ptr_base_path_helper(loan_path) {
41         Some(new_loan_path) => new_loan_path,
42         None => loan_path.clone()
43     };
44
45     fn owned_ptr_base_path_helper<'a>(loan_path: &'a LoanPath) -> Option<&'a LoanPath> {
46         match *loan_path {
47             LpVar(_) | LpUpvar(_) => None,
48             LpExtend(ref lp_base, _, LpDeref(mc::OwnedPtr)) => {
49                 match owned_ptr_base_path_helper(&**lp_base) {
50                     v @ Some(_) => v,
51                     None => Some(&**lp_base)
52                 }
53             }
54             LpExtend(ref lp_base, _, _) => owned_ptr_base_path_helper(&**lp_base)
55         }
56     }
57 }
58
59 fn owned_ptr_base_path_rc(loan_path: &Rc<LoanPath>) -> Rc<LoanPath> {
60     //! The equivalent of `owned_ptr_base_path` for an &Rc<LoanPath> rather than
61     //! a &LoanPath.
62
63     return match owned_ptr_base_path_helper(loan_path) {
64         Some(new_loan_path) => new_loan_path,
65         None => loan_path.clone()
66     };
67
68     fn owned_ptr_base_path_helper(loan_path: &Rc<LoanPath>) -> Option<Rc<LoanPath>> {
69         match **loan_path {
70             LpVar(_) | LpUpvar(_) => None,
71             LpExtend(ref lp_base, _, LpDeref(mc::OwnedPtr)) => {
72                 match owned_ptr_base_path_helper(lp_base) {
73                     v @ Some(_) => v,
74                     None => Some(lp_base.clone())
75                 }
76             }
77             LpExtend(ref lp_base, _, _) => owned_ptr_base_path_helper(lp_base)
78         }
79     }
80 }
81
82 struct CheckLoanCtxt<'a, 'tcx: 'a> {
83     bccx: &'a BorrowckCtxt<'a, 'tcx>,
84     dfcx_loans: &'a LoanDataFlow<'a, 'tcx>,
85     move_data: move_data::FlowedMoveData<'a, 'tcx>,
86     all_loans: &'a [Loan],
87 }
88
89 impl<'a, 'tcx> euv::Delegate for CheckLoanCtxt<'a, 'tcx> {
90     fn consume(&mut self,
91                consume_id: ast::NodeId,
92                consume_span: Span,
93                cmt: mc::cmt,
94                mode: euv::ConsumeMode) {
95         debug!("consume(consume_id={}, cmt={}, mode={})",
96                consume_id, cmt.repr(self.tcx()), mode);
97
98         self.consume_common(consume_id, consume_span, cmt, mode);
99     }
100
101     fn consume_pat(&mut self,
102                    consume_pat: &ast::Pat,
103                    cmt: mc::cmt,
104                    mode: euv::ConsumeMode) {
105         debug!("consume_pat(consume_pat={}, cmt={}, mode={})",
106                consume_pat.repr(self.tcx()),
107                cmt.repr(self.tcx()),
108                mode);
109
110         self.consume_common(consume_pat.id, consume_pat.span, cmt, mode);
111     }
112
113     fn borrow(&mut self,
114               borrow_id: ast::NodeId,
115               borrow_span: Span,
116               cmt: mc::cmt,
117               loan_region: ty::Region,
118               bk: ty::BorrowKind,
119               loan_cause: euv::LoanCause)
120     {
121         debug!("borrow(borrow_id={}, cmt={}, loan_region={}, \
122                bk={}, loan_cause={:?})",
123                borrow_id, cmt.repr(self.tcx()), loan_region,
124                bk, loan_cause);
125
126         match opt_loan_path(&cmt) {
127             Some(lp) => {
128                 let moved_value_use_kind = match loan_cause {
129                     euv::ClosureCapture(_) => MovedInCapture,
130                     _ => MovedInUse,
131                 };
132                 self.check_if_path_is_moved(borrow_id, borrow_span, moved_value_use_kind, &lp);
133             }
134             None => { }
135         }
136
137         self.check_for_conflicting_loans(borrow_id);
138     }
139
140     fn mutate(&mut self,
141               assignment_id: ast::NodeId,
142               assignment_span: Span,
143               assignee_cmt: mc::cmt,
144               mode: euv::MutateMode)
145     {
146         debug!("mutate(assignment_id={}, assignee_cmt={})",
147                assignment_id, assignee_cmt.repr(self.tcx()));
148
149         match opt_loan_path(&assignee_cmt) {
150             Some(lp) => {
151                 match mode {
152                     euv::Init | euv::JustWrite => {
153                         // In a case like `path = 1`, then path does not
154                         // have to be *FULLY* initialized, but we still
155                         // must be careful lest it contains derefs of
156                         // pointers.
157                         self.check_if_assigned_path_is_moved(assignee_cmt.id,
158                                                              assignment_span,
159                                                              MovedInUse,
160                                                              &lp);
161                     }
162                     euv::WriteAndRead => {
163                         // In a case like `path += 1`, then path must be
164                         // fully initialized, since we will read it before
165                         // we write it.
166                         self.check_if_path_is_moved(assignee_cmt.id,
167                                                     assignment_span,
168                                                     MovedInUse,
169                                                     &lp);
170                     }
171                 }
172             }
173             None => { }
174         }
175
176         self.check_assignment(assignment_id, assignment_span, assignee_cmt, mode);
177     }
178
179     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) { }
180 }
181
182 pub fn check_loans<'a, 'b, 'c, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
183                                      dfcx_loans: &LoanDataFlow<'b, 'tcx>,
184                                      move_data: move_data::FlowedMoveData<'c, 'tcx>,
185                                      all_loans: &[Loan],
186                                      decl: &ast::FnDecl,
187                                      body: &ast::Block) {
188     debug!("check_loans(body id={:?})", body.id);
189
190     let mut clcx = CheckLoanCtxt {
191         bccx: bccx,
192         dfcx_loans: dfcx_loans,
193         move_data: move_data,
194         all_loans: all_loans,
195     };
196
197     {
198         let mut euv = euv::ExprUseVisitor::new(&mut clcx, bccx.tcx);
199         euv.walk_fn(decl, body);
200     }
201 }
202
203 #[deriving(PartialEq)]
204 enum UseError {
205     UseOk,
206     UseWhileBorrowed(/*loan*/Rc<LoanPath>, /*loan*/Span)
207 }
208
209 fn compatible_borrow_kinds(borrow_kind1: ty::BorrowKind,
210                            borrow_kind2: ty::BorrowKind)
211                            -> bool {
212     borrow_kind1 == ty::ImmBorrow && borrow_kind2 == ty::ImmBorrow
213 }
214
215 impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> {
216     pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.bccx.tcx }
217
218     pub fn each_issued_loan(&self, scope_id: ast::NodeId, op: |&Loan| -> bool)
219                             -> bool {
220         //! Iterates over each loan that has been issued
221         //! on entrance to `scope_id`, regardless of whether it is
222         //! actually *in scope* at that point.  Sometimes loans
223         //! are issued for future scopes and thus they may have been
224         //! *issued* but not yet be in effect.
225
226         self.dfcx_loans.each_bit_on_entry(scope_id, |loan_index| {
227             let loan = &self.all_loans[loan_index];
228             op(loan)
229         })
230     }
231
232     pub fn each_in_scope_loan(&self,
233                               scope_id: ast::NodeId,
234                               op: |&Loan| -> bool)
235                               -> bool {
236         //! Like `each_issued_loan()`, but only considers loans that are
237         //! currently in scope.
238
239         let tcx = self.tcx();
240         self.each_issued_loan(scope_id, |loan| {
241             if tcx.region_maps.is_subscope_of(scope_id, loan.kill_scope) {
242                 op(loan)
243             } else {
244                 true
245             }
246         })
247     }
248
249     fn each_in_scope_loan_affecting_path(&self,
250                                          scope_id: ast::NodeId,
251                                          loan_path: &LoanPath,
252                                          op: |&Loan| -> bool)
253                                          -> bool {
254         //! Iterates through all of the in-scope loans affecting `loan_path`,
255         //! calling `op`, and ceasing iteration if `false` is returned.
256
257         // First, we check for a loan restricting the path P being used. This
258         // accounts for borrows of P but also borrows of subpaths, like P.a.b.
259         // Consider the following example:
260         //
261         //     let x = &mut a.b.c; // Restricts a, a.b, and a.b.c
262         //     let y = a;          // Conflicts with restriction
263
264         let loan_path = owned_ptr_base_path(loan_path);
265         let cont = self.each_in_scope_loan(scope_id, |loan| {
266             let mut ret = true;
267             for restr_path in loan.restricted_paths.iter() {
268                 if **restr_path == *loan_path {
269                     if !op(loan) {
270                         ret = false;
271                         break;
272                     }
273                 }
274             }
275             ret
276         });
277
278         if !cont {
279             return false;
280         }
281
282         // Next, we must check for *loans* (not restrictions) on the path P or
283         // any base path. This rejects examples like the following:
284         //
285         //     let x = &mut a.b;
286         //     let y = a.b.c;
287         //
288         // Limiting this search to *loans* and not *restrictions* means that
289         // examples like the following continue to work:
290         //
291         //     let x = &mut a.b;
292         //     let y = a.c;
293
294         let mut loan_path = loan_path;
295         loop {
296             match *loan_path {
297                 LpVar(_) | LpUpvar(_) => {
298                     break;
299                 }
300                 LpExtend(ref lp_base, _, _) => {
301                     loan_path = &**lp_base;
302                 }
303             }
304
305             let cont = self.each_in_scope_loan(scope_id, |loan| {
306                 if *loan.loan_path == *loan_path {
307                     op(loan)
308                 } else {
309                     true
310                 }
311             });
312
313             if !cont {
314                 return false;
315             }
316         }
317
318         return true;
319     }
320
321     pub fn loans_generated_by(&self, scope_id: ast::NodeId) -> Vec<uint> {
322         //! Returns a vector of the loans that are generated as
323         //! we encounter `scope_id`.
324
325         let mut result = Vec::new();
326         self.dfcx_loans.each_gen_bit(scope_id, |loan_index| {
327             result.push(loan_index);
328             true
329         });
330         return result;
331     }
332
333     pub fn check_for_conflicting_loans(&self, scope_id: ast::NodeId) {
334         //! Checks to see whether any of the loans that are issued
335         //! by `scope_id` conflict with loans that have already been
336         //! issued when we enter `scope_id` (for example, we do not
337         //! permit two `&mut` borrows of the same variable).
338
339         debug!("check_for_conflicting_loans(scope_id={:?})", scope_id);
340
341         let new_loan_indices = self.loans_generated_by(scope_id);
342         debug!("new_loan_indices = {:?}", new_loan_indices);
343
344         self.each_issued_loan(scope_id, |issued_loan| {
345             for &new_loan_index in new_loan_indices.iter() {
346                 let new_loan = &self.all_loans[new_loan_index];
347                 self.report_error_if_loans_conflict(issued_loan, new_loan);
348             }
349             true
350         });
351
352         for (i, &x) in new_loan_indices.iter().enumerate() {
353             let old_loan = &self.all_loans[x];
354             for &y in new_loan_indices.slice_from(i+1).iter() {
355                 let new_loan = &self.all_loans[y];
356                 self.report_error_if_loans_conflict(old_loan, new_loan);
357             }
358         }
359     }
360
361     pub fn report_error_if_loans_conflict(&self,
362                                           old_loan: &Loan,
363                                           new_loan: &Loan) {
364         //! Checks whether `old_loan` and `new_loan` can safely be issued
365         //! simultaneously.
366
367         debug!("report_error_if_loans_conflict(old_loan={}, new_loan={})",
368                old_loan.repr(self.tcx()),
369                new_loan.repr(self.tcx()));
370
371         // Should only be called for loans that are in scope at the same time.
372         assert!(self.tcx().region_maps.scopes_intersect(old_loan.kill_scope,
373                                                         new_loan.kill_scope));
374
375         self.report_error_if_loan_conflicts_with_restriction(
376             old_loan, new_loan, old_loan, new_loan) &&
377         self.report_error_if_loan_conflicts_with_restriction(
378             new_loan, old_loan, old_loan, new_loan);
379     }
380
381     pub fn report_error_if_loan_conflicts_with_restriction(&self,
382                                                            loan1: &Loan,
383                                                            loan2: &Loan,
384                                                            old_loan: &Loan,
385                                                            new_loan: &Loan)
386                                                            -> bool {
387         //! Checks whether the restrictions introduced by `loan1` would
388         //! prohibit `loan2`. Returns false if an error is reported.
389
390         debug!("report_error_if_loan_conflicts_with_restriction(\
391                 loan1={}, loan2={})",
392                loan1.repr(self.tcx()),
393                loan2.repr(self.tcx()));
394
395         if compatible_borrow_kinds(loan1.kind, loan2.kind) {
396             return true;
397         }
398
399         let loan2_base_path = owned_ptr_base_path_rc(&loan2.loan_path);
400         for restr_path in loan1.restricted_paths.iter() {
401             if *restr_path != loan2_base_path { continue; }
402
403             let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
404                 "it".to_string()
405             } else {
406                 format!("`{}`",
407                         self.bccx.loan_path_to_string(&*old_loan.loan_path))
408             };
409
410             match (new_loan.kind, old_loan.kind) {
411                 (ty::MutBorrow, ty::MutBorrow) => {
412                     self.bccx.span_err(
413                         new_loan.span,
414                         format!("cannot borrow `{}` as mutable \
415                                 more than once at a time",
416                                 self.bccx.loan_path_to_string(
417                                     &*new_loan.loan_path)).as_slice());
418                 }
419
420                 (ty::UniqueImmBorrow, _) => {
421                     self.bccx.span_err(
422                         new_loan.span,
423                         format!("closure requires unique access to `{}` \
424                                 but {} is already borrowed",
425                                 self.bccx.loan_path_to_string(&*new_loan.loan_path),
426                                 old_pronoun).as_slice());
427                 }
428
429                 (_, ty::UniqueImmBorrow) => {
430                     self.bccx.span_err(
431                         new_loan.span,
432                         format!("cannot borrow `{}` as {} because \
433                                 previous closure requires unique access",
434                                 self.bccx.loan_path_to_string(&*new_loan.loan_path),
435                                 new_loan.kind.to_user_str()).as_slice());
436                 }
437
438                 (_, _) => {
439                     self.bccx.span_err(
440                         new_loan.span,
441                         format!("cannot borrow `{}` as {} because \
442                                 {} is also borrowed as {}",
443                                 self.bccx.loan_path_to_string(&*new_loan.loan_path),
444                                 new_loan.kind.to_user_str(),
445                                 old_pronoun,
446                                 old_loan.kind.to_user_str()).as_slice());
447                 }
448             }
449
450             match new_loan.cause {
451                 euv::ClosureCapture(span) => {
452                     self.bccx.span_note(
453                         span,
454                         format!("borrow occurs due to use of `{}` in closure",
455                                 self.bccx.loan_path_to_string(
456                                     &*new_loan.loan_path)).as_slice());
457                 }
458                 _ => { }
459             }
460
461             let rule_summary = match old_loan.kind {
462                 ty::MutBorrow => {
463                     format!("the mutable borrow prevents subsequent \
464                             moves, borrows, or modification of `{0}` \
465                             until the borrow ends",
466                             self.bccx.loan_path_to_string(
467                                 &*old_loan.loan_path))
468                 }
469
470                 ty::ImmBorrow => {
471                     format!("the immutable borrow prevents subsequent \
472                             moves or mutable borrows of `{0}` \
473                             until the borrow ends",
474                             self.bccx.loan_path_to_string(&*old_loan.loan_path))
475                 }
476
477                 ty::UniqueImmBorrow => {
478                     format!("the unique capture prevents subsequent \
479                             moves or borrows of `{0}` \
480                             until the borrow ends",
481                             self.bccx.loan_path_to_string(&*old_loan.loan_path))
482                 }
483             };
484
485             let borrow_summary = match old_loan.cause {
486                 euv::ClosureCapture(_) => {
487                     format!("previous borrow of `{}` occurs here due to \
488                             use in closure",
489                             self.bccx.loan_path_to_string(&*old_loan.loan_path))
490                 }
491
492                 euv::OverloadedOperator(..) |
493                 euv::AddrOf(..) |
494                 euv::AutoRef(..) |
495                 euv::ClosureInvocation(..) |
496                 euv::ForLoop(..) |
497                 euv::RefBinding(..) => {
498                     format!("previous borrow of `{}` occurs here",
499                             self.bccx.loan_path_to_string(&*old_loan.loan_path))
500                 }
501             };
502
503             self.bccx.span_note(
504                 old_loan.span,
505                 format!("{}; {}", borrow_summary, rule_summary).as_slice());
506
507             let old_loan_span = self.tcx().map.span(old_loan.kill_scope);
508             self.bccx.span_end_note(old_loan_span,
509                                     "previous borrow ends here");
510
511             return false;
512         }
513
514         true
515     }
516
517     pub fn is_local_variable_or_arg(&self, cmt: mc::cmt) -> bool {
518         match cmt.cat {
519           mc::cat_local(_) | mc::cat_arg(_) => true,
520           _ => false
521         }
522     }
523
524     fn consume_common(&self,
525                       id: ast::NodeId,
526                       span: Span,
527                       cmt: mc::cmt,
528                       mode: euv::ConsumeMode) {
529         match opt_loan_path(&cmt) {
530             Some(lp) => {
531                 let moved_value_use_kind = match mode {
532                     euv::Copy => {
533                         self.check_for_copy_of_frozen_path(id, span, &*lp);
534                         MovedInUse
535                     }
536                     euv::Move(_) => {
537                         match self.move_data.kind_of_move_of_path(id, &lp) {
538                             None => {
539                                 // Sometimes moves don't have a move kind;
540                                 // this either means that the original move
541                                 // was from something illegal to move,
542                                 // or was moved from referent of an unsafe
543                                 // pointer or something like that.
544                                 MovedInUse
545                             }
546                             Some(move_kind) => {
547                                 self.check_for_move_of_borrowed_path(id, span,
548                                                                      &*lp, move_kind);
549                                 if move_kind == move_data::Captured {
550                                     MovedInCapture
551                                 } else {
552                                     MovedInUse
553                                 }
554                             }
555                         }
556                     }
557                 };
558
559                 self.check_if_path_is_moved(id, span, moved_value_use_kind, &lp);
560             }
561             None => { }
562         }
563     }
564
565     fn check_for_copy_of_frozen_path(&self,
566                                      id: ast::NodeId,
567                                      span: Span,
568                                      copy_path: &LoanPath) {
569         match self.analyze_restrictions_on_use(id, copy_path, ty::ImmBorrow) {
570             UseOk => { }
571             UseWhileBorrowed(loan_path, loan_span) => {
572                 self.bccx.span_err(
573                     span,
574                     format!("cannot use `{}` because it was mutably borrowed",
575                             self.bccx.loan_path_to_string(copy_path).as_slice())
576                     .as_slice());
577                 self.bccx.span_note(
578                     loan_span,
579                     format!("borrow of `{}` occurs here",
580                             self.bccx.loan_path_to_string(&*loan_path).as_slice())
581                     .as_slice());
582             }
583         }
584     }
585
586     fn check_for_move_of_borrowed_path(&self,
587                                        id: ast::NodeId,
588                                        span: Span,
589                                        move_path: &LoanPath,
590                                        move_kind: move_data::MoveKind) {
591         // We want to detect if there are any loans at all, so we search for
592         // any loans incompatible with MutBorrrow, since all other kinds of
593         // loans are incompatible with that.
594         match self.analyze_restrictions_on_use(id, move_path, ty::MutBorrow) {
595             UseOk => { }
596             UseWhileBorrowed(loan_path, loan_span) => {
597                 let err_message = match move_kind {
598                     move_data::Captured =>
599                         format!("cannot move `{}` into closure because it is borrowed",
600                                 self.bccx.loan_path_to_string(move_path).as_slice()),
601                     move_data::Declared |
602                     move_data::MoveExpr |
603                     move_data::MovePat =>
604                         format!("cannot move out of `{}` because it is borrowed",
605                                 self.bccx.loan_path_to_string(move_path).as_slice())
606                 };
607
608                 self.bccx.span_err(span, err_message.as_slice());
609                 self.bccx.span_note(
610                     loan_span,
611                     format!("borrow of `{}` occurs here",
612                             self.bccx.loan_path_to_string(&*loan_path).as_slice())
613                     .as_slice());
614             }
615         }
616     }
617
618     pub fn analyze_restrictions_on_use(&self,
619                                        expr_id: ast::NodeId,
620                                        use_path: &LoanPath,
621                                        borrow_kind: ty::BorrowKind)
622                                        -> UseError {
623         debug!("analyze_restrictions_on_use(expr_id={:?}, use_path={})",
624                self.tcx().map.node_to_string(expr_id),
625                use_path.repr(self.tcx()));
626
627         let mut ret = UseOk;
628
629         self.each_in_scope_loan_affecting_path(expr_id, use_path, |loan| {
630             if !compatible_borrow_kinds(loan.kind, borrow_kind) {
631                 ret = UseWhileBorrowed(loan.loan_path.clone(), loan.span);
632                 false
633             } else {
634                 true
635             }
636         });
637
638         return ret;
639     }
640
641     fn check_if_path_is_moved(&self,
642                               id: ast::NodeId,
643                               span: Span,
644                               use_kind: MovedValueUseKind,
645                               lp: &Rc<LoanPath>) {
646         /*!
647          * Reports an error if `expr` (which should be a path)
648          * is using a moved/uninitialized value
649          */
650
651         debug!("check_if_path_is_moved(id={:?}, use_kind={:?}, lp={})",
652                id, use_kind, lp.repr(self.bccx.tcx));
653         let base_lp = owned_ptr_base_path_rc(lp);
654         self.move_data.each_move_of(id, &base_lp, |move, moved_lp| {
655             self.bccx.report_use_of_moved_value(
656                 span,
657                 use_kind,
658                 &**lp,
659                 move,
660                 moved_lp);
661             false
662         });
663     }
664
665     fn check_if_assigned_path_is_moved(&self,
666                                        id: ast::NodeId,
667                                        span: Span,
668                                        use_kind: MovedValueUseKind,
669                                        lp: &Rc<LoanPath>)
670     {
671         /*!
672          * Reports an error if assigning to `lp` will use a
673          * moved/uninitialized value. Mainly this is concerned with
674          * detecting derefs of uninitialized pointers.
675          *
676          * For example:
677          *
678          *     let a: int;
679          *     a = 10; // ok, even though a is uninitialized
680          *
681          *     struct Point { x: uint, y: uint }
682          *     let p: Point;
683          *     p.x = 22; // ok, even though `p` is uninitialized
684          *
685          *     let p: ~Point;
686          *     (*p).x = 22; // not ok, p is uninitialized, can't deref
687          */
688
689         match **lp {
690             LpVar(_) | LpUpvar(_) => {
691                 // assigning to `x` does not require that `x` is initialized
692             }
693             LpExtend(ref lp_base, _, LpInterior(_)) => {
694                 // assigning to `P.f` is ok if assigning to `P` is ok
695                 self.check_if_assigned_path_is_moved(id, span,
696                                                      use_kind, lp_base);
697             }
698             LpExtend(ref lp_base, _, LpDeref(_)) => {
699                 // assigning to `(*P)` requires that `P` be initialized
700                 self.check_if_path_is_moved(id, span,
701                                             use_kind, lp_base);
702             }
703         }
704     }
705
706     fn check_assignment(&self,
707                         assignment_id: ast::NodeId,
708                         assignment_span: Span,
709                         assignee_cmt: mc::cmt,
710                         mode: euv::MutateMode) {
711         debug!("check_assignment(assignee_cmt={})", assignee_cmt.repr(self.tcx()));
712
713         // Mutable values can be assigned, as long as they obey loans
714         // and aliasing restrictions:
715         if assignee_cmt.mutbl.is_mutable() {
716             if check_for_aliasable_mutable_writes(self, assignment_span, assignee_cmt.clone()) {
717                 if mode != euv::Init {
718                     check_for_assignment_to_borrowed_path(
719                         self, assignment_id, assignment_span, assignee_cmt.clone());
720                     mark_variable_as_used_mut(self, assignee_cmt);
721                 }
722             }
723             return;
724         }
725
726         // Initializations are OK.
727         if mode == euv::Init {
728             return
729         }
730
731         // For immutable local variables, assignments are legal
732         // if they cannot already have been assigned
733         if self.is_local_variable_or_arg(assignee_cmt.clone()) {
734             assert!(assignee_cmt.mutbl.is_immutable()); // no "const" locals
735             let lp = opt_loan_path(&assignee_cmt).unwrap();
736             self.move_data.each_assignment_of(assignment_id, &lp, |assign| {
737                 self.bccx.report_reassigned_immutable_variable(
738                     assignment_span,
739                     &*lp,
740                     assign);
741                 false
742             });
743             return;
744         }
745
746         // Otherwise, just a plain error.
747         match opt_loan_path(&assignee_cmt) {
748             Some(lp) => {
749                 self.bccx.span_err(
750                     assignment_span,
751                     format!("cannot assign to {} {} `{}`",
752                             assignee_cmt.mutbl.to_user_str(),
753                             self.bccx.cmt_to_string(&*assignee_cmt),
754                             self.bccx.loan_path_to_string(&*lp)).as_slice());
755             }
756             None => {
757                 self.bccx.span_err(
758                     assignment_span,
759                     format!("cannot assign to {} {}",
760                             assignee_cmt.mutbl.to_user_str(),
761                             self.bccx.cmt_to_string(&*assignee_cmt)).as_slice());
762             }
763         }
764         return;
765
766         fn mark_variable_as_used_mut(this: &CheckLoanCtxt,
767                                      mut cmt: mc::cmt) {
768             //! If the mutability of the `cmt` being written is inherited
769             //! from a local variable, liveness will
770             //! not have been able to detect that this variable's mutability
771             //! is important, so we must add the variable to the
772             //! `used_mut_nodes` table here.
773
774             loop {
775                 debug!("mark_variable_as_used_mut(cmt={})", cmt.repr(this.tcx()));
776                 match cmt.cat.clone() {
777                     mc::cat_copied_upvar(mc::CopiedUpvar { upvar_id: id, .. }) |
778                     mc::cat_local(id) | mc::cat_arg(id) => {
779                         this.tcx().used_mut_nodes.borrow_mut().insert(id);
780                         return;
781                     }
782
783                     mc::cat_upvar(..) => {
784                         return;
785                     }
786
787                     mc::cat_deref(_, _, mc::GcPtr) => {
788                         assert_eq!(cmt.mutbl, mc::McImmutable);
789                         return;
790                     }
791
792                     mc::cat_rvalue(..) |
793                     mc::cat_static_item |
794                     mc::cat_deref(_, _, mc::UnsafePtr(..)) |
795                     mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
796                     mc::cat_deref(_, _, mc::Implicit(..)) => {
797                         assert_eq!(cmt.mutbl, mc::McDeclared);
798                         return;
799                     }
800
801                     mc::cat_discr(b, _) |
802                     mc::cat_deref(b, _, mc::OwnedPtr) => {
803                         assert_eq!(cmt.mutbl, mc::McInherited);
804                         cmt = b;
805                     }
806
807                     mc::cat_downcast(b) |
808                     mc::cat_interior(b, _) => {
809                         assert_eq!(cmt.mutbl, mc::McInherited);
810                         cmt = b;
811                     }
812                 }
813             }
814         }
815
816         fn check_for_aliasable_mutable_writes(this: &CheckLoanCtxt,
817                                               span: Span,
818                                               cmt: mc::cmt) -> bool {
819             //! Safety checks related to writes to aliasable, mutable locations
820
821             let guarantor = cmt.guarantor();
822             debug!("check_for_aliasable_mutable_writes(cmt={}, guarantor={})",
823                    cmt.repr(this.tcx()), guarantor.repr(this.tcx()));
824             match guarantor.cat {
825                 mc::cat_deref(ref b, _, mc::BorrowedPtr(ty::MutBorrow, _)) => {
826                     // Statically prohibit writes to `&mut` when aliasable
827
828                     check_for_aliasability_violation(this, span, b.clone());
829                 }
830
831                 _ => {}
832             }
833
834             return true; // no errors reported
835         }
836
837         fn check_for_aliasability_violation(this: &CheckLoanCtxt,
838                                             span: Span,
839                                             cmt: mc::cmt)
840                                             -> bool {
841             match cmt.freely_aliasable(this.tcx()) {
842                 None => {
843                     return true;
844                 }
845                 Some(mc::AliasableStaticMut(..)) => {
846                     return true;
847                 }
848                 Some(cause) => {
849                     this.bccx.report_aliasability_violation(
850                         span,
851                         MutabilityViolation,
852                         cause);
853                     return false;
854                 }
855             }
856         }
857
858         fn check_for_assignment_to_borrowed_path(
859             this: &CheckLoanCtxt,
860             assignment_id: ast::NodeId,
861             assignment_span: Span,
862             assignee_cmt: mc::cmt)
863         {
864             //! Check for assignments that violate the terms of an
865             //! outstanding loan.
866
867             let loan_path = match opt_loan_path(&assignee_cmt) {
868                 Some(lp) => lp,
869                 None => { return; /* no loan path, can't be any loans */ }
870             };
871
872             this.each_in_scope_loan_affecting_path(assignment_id, &*loan_path, |loan| {
873                 this.report_illegal_mutation(assignment_span, &*loan_path, loan);
874                 false
875             });
876         }
877     }
878
879     pub fn report_illegal_mutation(&self,
880                                    span: Span,
881                                    loan_path: &LoanPath,
882                                    loan: &Loan) {
883         self.bccx.span_err(
884             span,
885             format!("cannot assign to `{}` because it is borrowed",
886                     self.bccx.loan_path_to_string(loan_path)).as_slice());
887         self.bccx.span_note(
888             loan.span,
889             format!("borrow of `{}` occurs here",
890                     self.bccx.loan_path_to_string(loan_path)).as_slice());
891     }
892 }
893