]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/error_reporting.rs
Auto merge of #53830 - davidtwco:issue-53228, r=nikomatsakis
[rust.git] / src / librustc_mir / borrow_check / error_reporting.rs
1 // Copyright 2017 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 use borrow_check::WriteKind;
12 use rustc::middle::region::ScopeTree;
13 use rustc::mir::VarBindingForm;
14 use rustc::mir::{BindingForm, BorrowKind, ClearCrossCrate, Field, Local};
15 use rustc::mir::{LocalDecl, LocalKind, Location, Operand, Place};
16 use rustc::mir::{ProjectionElem, Rvalue, Statement, StatementKind};
17 use rustc::ty;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::indexed_vec::Idx;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_errors::DiagnosticBuilder;
22 use syntax_pos::Span;
23
24 use super::borrow_set::BorrowData;
25 use super::{Context, MirBorrowckCtxt};
26 use super::{InitializationRequiringAction, PrefixSet};
27
28 use dataflow::drop_flag_effects;
29 use dataflow::move_paths::indexes::MoveOutIndex;
30 use dataflow::move_paths::MovePathIndex;
31 use util::borrowck_errors::{BorrowckErrors, Origin};
32
33 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
34     pub(super) fn report_use_of_moved_or_uninitialized(
35         &mut self,
36         context: Context,
37         desired_action: InitializationRequiringAction,
38         (place, span): (&Place<'tcx>, Span),
39         mpi: MovePathIndex,
40     ) {
41         let use_spans = self
42             .move_spans(place, context.loc)
43             .or_else(|| self.borrow_spans(span, context.loc));
44         let span = use_spans.args_or_use();
45
46         let mois = self.get_moved_indexes(context, mpi);
47         debug!("report_use_of_moved_or_uninitialized: mois={:?}", mois);
48
49         if mois.is_empty() {
50             let root_place = self.prefixes(&place, PrefixSet::All).last().unwrap();
51
52             if self.moved_error_reported.contains(&root_place.clone()) {
53                 debug!(
54                     "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
55                     root_place
56                 );
57                 return;
58             }
59
60             self.moved_error_reported.insert(root_place.clone());
61
62             let item_msg = match self.describe_place_with_options(place, IncludingDowncast(true)) {
63                 Some(name) => format!("`{}`", name),
64                 None => "value".to_owned(),
65             };
66             let mut err = self.tcx.cannot_act_on_uninitialized_variable(
67                 span,
68                 desired_action.as_noun(),
69                 &self
70                     .describe_place_with_options(place, IncludingDowncast(true))
71                     .unwrap_or("_".to_owned()),
72                 Origin::Mir,
73             );
74             err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
75
76             use_spans.var_span_label(
77                 &mut err,
78                 format!("{} occurs due to use in closure", desired_action.as_noun()),
79             );
80
81             err.buffer(&mut self.errors_buffer);
82         } else {
83             let msg = ""; //FIXME: add "partially " or "collaterally "
84
85             let mut err = self.tcx.cannot_act_on_moved_value(
86                 span,
87                 desired_action.as_noun(),
88                 msg,
89                 self.describe_place_with_options(&place, IncludingDowncast(true)),
90                 Origin::Mir,
91             );
92
93             let mut is_loop_move = false;
94             for moi in &mois {
95                 let move_out = self.move_data.moves[*moi];
96                 let moved_place = &self.move_data.move_paths[move_out.path].place;
97
98                 let move_spans = self.move_spans(moved_place, move_out.source);
99                 let move_span = move_spans.args_or_use();
100
101                 let move_msg = if move_spans.for_closure() {
102                     " into closure"
103                 } else {
104                     ""
105                 };
106
107                 if span == move_span {
108                     err.span_label(
109                         span,
110                         format!("value moved{} here in previous iteration of loop", move_msg),
111                     );
112                     is_loop_move = true;
113                 } else {
114                     err.span_label(move_span, format!("value moved{} here", move_msg));
115                     move_spans.var_span_label(&mut err, "variable moved due to use in closure");
116                 };
117             }
118
119             use_spans.var_span_label(
120                 &mut err,
121                 format!("{} occurs due to use in closure", desired_action.as_noun()),
122             );
123
124             if !is_loop_move {
125                 err.span_label(
126                     span,
127                     format!(
128                         "value {} here after move",
129                         desired_action.as_verb_in_past_tense()
130                     ),
131                 );
132             }
133
134             if let Some(ty) = self.retrieve_type_for_place(place) {
135                 let needs_note = match ty.sty {
136                     ty::Closure(id, _) => {
137                         let tables = self.tcx.typeck_tables_of(id);
138                         let node_id = self.tcx.hir.as_local_node_id(id).unwrap();
139                         let hir_id = self.tcx.hir.node_to_hir_id(node_id);
140                         if tables.closure_kind_origins().get(hir_id).is_some() {
141                             false
142                         } else {
143                             true
144                         }
145                     }
146                     _ => true,
147                 };
148
149                 if needs_note {
150                     let mpi = self.move_data.moves[mois[0]].path;
151                     let place = &self.move_data.move_paths[mpi].place;
152
153                     if let Some(ty) = self.retrieve_type_for_place(place) {
154                         let note_msg = match self
155                             .describe_place_with_options(place, IncludingDowncast(true))
156                         {
157                             Some(name) => format!("`{}`", name),
158                             None => "value".to_owned(),
159                         };
160
161                         err.note(&format!(
162                             "move occurs because {} has type `{}`, \
163                              which does not implement the `Copy` trait",
164                             note_msg, ty
165                         ));
166                     }
167                 }
168             }
169
170             err.buffer(&mut self.errors_buffer);
171         }
172     }
173
174     pub(super) fn report_move_out_while_borrowed(
175         &mut self,
176         context: Context,
177         (place, _span): (&Place<'tcx>, Span),
178         borrow: &BorrowData<'tcx>,
179     ) {
180         let tcx = self.tcx;
181         let value_msg = match self.describe_place(place) {
182             Some(name) => format!("`{}`", name),
183             None => "value".to_owned(),
184         };
185         let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
186             Some(name) => format!("`{}`", name),
187             None => "value".to_owned(),
188         };
189
190         let borrow_spans = self.retrieve_borrow_spans(borrow);
191         let borrow_span = borrow_spans.args_or_use();
192
193         let move_spans = self.move_spans(place, context.loc);
194         let span = move_spans.args_or_use();
195
196         let mut err = tcx.cannot_move_when_borrowed(
197             span,
198             &self.describe_place(place).unwrap_or("_".to_owned()),
199             Origin::Mir,
200         );
201         err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
202         err.span_label(span, format!("move out of {} occurs here", value_msg));
203
204         borrow_spans.var_span_label(&mut err, "borrow occurs due to use in closure");
205
206         move_spans.var_span_label(&mut err, "move occurs due to use in closure");
207
208         self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
209         err.buffer(&mut self.errors_buffer);
210     }
211
212     pub(super) fn report_use_while_mutably_borrowed(
213         &mut self,
214         context: Context,
215         (place, _span): (&Place<'tcx>, Span),
216         borrow: &BorrowData<'tcx>,
217     ) {
218         let tcx = self.tcx;
219
220         let borrow_spans = self.retrieve_borrow_spans(borrow);
221         let borrow_span = borrow_spans.args_or_use();
222
223         // Conflicting borrows are reported separately, so only check for move
224         // captures.
225         let use_spans = self.move_spans(place, context.loc);
226         let span = use_spans.var_or_use();
227
228         let mut err = tcx.cannot_use_when_mutably_borrowed(
229             span,
230             &self.describe_place(place).unwrap_or("_".to_owned()),
231             borrow_span,
232             &self
233                 .describe_place(&borrow.borrowed_place)
234                 .unwrap_or("_".to_owned()),
235             Origin::Mir,
236         );
237
238         borrow_spans.var_span_label(&mut err, {
239             let place = &borrow.borrowed_place;
240             let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
241
242             format!("borrow occurs due to use of `{}` in closure", desc_place)
243         });
244
245         self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
246         err.buffer(&mut self.errors_buffer);
247     }
248
249     pub(super) fn report_conflicting_borrow(
250         &mut self,
251         context: Context,
252         (place, span): (&Place<'tcx>, Span),
253         gen_borrow_kind: BorrowKind,
254         issued_borrow: &BorrowData<'tcx>,
255     ) {
256         let issued_spans = self.retrieve_borrow_spans(issued_borrow);
257         let issued_span = issued_spans.args_or_use();
258
259         let borrow_spans = self.borrow_spans(span, context.loc);
260         let span = borrow_spans.args_or_use();
261
262         let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
263         let tcx = self.tcx;
264
265         // FIXME: supply non-"" `opt_via` when appropriate
266         let mut err = match (
267             gen_borrow_kind,
268             "immutable",
269             "mutable",
270             issued_borrow.kind,
271             "immutable",
272             "mutable",
273         ) {
274             (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt)
275             | (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => tcx
276                 .cannot_reborrow_already_borrowed(
277                     span,
278                     &desc_place,
279                     "",
280                     lft,
281                     issued_span,
282                     "it",
283                     rgt,
284                     "",
285                     None,
286                     Origin::Mir,
287                 ),
288
289             (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => tcx
290                 .cannot_mutably_borrow_multiply(
291                     span,
292                     &desc_place,
293                     "",
294                     issued_span,
295                     "",
296                     None,
297                     Origin::Mir,
298                 ),
299
300             (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => tcx
301                 .cannot_uniquely_borrow_by_two_closures(
302                     span,
303                     &desc_place,
304                     issued_span,
305                     None,
306                     Origin::Mir,
307                 ),
308
309             (BorrowKind::Unique, _, _, _, _, _) => tcx.cannot_uniquely_borrow_by_one_closure(
310                 span,
311                 &desc_place,
312                 "",
313                 issued_span,
314                 "it",
315                 "",
316                 None,
317                 Origin::Mir,
318             ),
319
320             (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => tcx
321                 .cannot_reborrow_already_uniquely_borrowed(
322                     span,
323                     &desc_place,
324                     "",
325                     lft,
326                     issued_span,
327                     "",
328                     None,
329                     Origin::Mir,
330                 ),
331
332             (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => tcx
333                 .cannot_reborrow_already_uniquely_borrowed(
334                     span,
335                     &desc_place,
336                     "",
337                     lft,
338                     issued_span,
339                     "",
340                     None,
341                     Origin::Mir,
342                 ),
343
344             (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _) => unreachable!(),
345         };
346
347         if issued_spans == borrow_spans {
348             borrow_spans.var_span_label(
349                 &mut err,
350                 format!("borrows occur due to use of `{}` in closure", desc_place),
351             );
352         } else {
353             let borrow_place = &issued_borrow.borrowed_place;
354             let borrow_place_desc = self.describe_place(borrow_place).unwrap_or("_".to_owned());
355             issued_spans.var_span_label(
356                 &mut err,
357                 format!(
358                     "first borrow occurs due to use of `{}` in closure",
359                     borrow_place_desc
360                 ),
361             );
362
363             borrow_spans.var_span_label(
364                 &mut err,
365                 format!(
366                     "second borrow occurs due to use of `{}` in closure",
367                     desc_place
368                 ),
369             );
370         }
371
372         self.explain_why_borrow_contains_point(context, issued_borrow, None, &mut err);
373
374         err.buffer(&mut self.errors_buffer);
375     }
376
377     pub(super) fn report_borrowed_value_does_not_live_long_enough(
378         &mut self,
379         context: Context,
380         borrow: &BorrowData<'tcx>,
381         place_span: (&Place<'tcx>, Span),
382         kind: Option<WriteKind>,
383     ) {
384         let drop_span = place_span.1;
385         let scope_tree = self.tcx.region_scope_tree(self.mir_def_id);
386         let root_place = self
387             .prefixes(&borrow.borrowed_place, PrefixSet::All)
388             .last()
389             .unwrap();
390
391         let borrow_spans = self.retrieve_borrow_spans(borrow);
392         let borrow_span = borrow_spans.var_or_use();
393
394         let proper_span = match *root_place {
395             Place::Local(local) => self.mir.local_decls[local].source_info.span,
396             _ => drop_span,
397         };
398
399         if self
400             .access_place_error_reported
401             .contains(&(root_place.clone(), borrow_span))
402         {
403             debug!(
404                 "suppressing access_place error when borrow doesn't live long enough for {:?}",
405                 borrow_span
406             );
407             return;
408         }
409
410         self.access_place_error_reported
411             .insert((root_place.clone(), borrow_span));
412
413         let mut err = match &self.describe_place(&borrow.borrowed_place) {
414             Some(_) if self.is_place_thread_local(root_place) => {
415                 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
416             }
417             Some(name) => self.report_local_value_does_not_live_long_enough(
418                 context,
419                 name,
420                 &scope_tree,
421                 &borrow,
422                 drop_span,
423                 borrow_span,
424                 proper_span,
425                 kind.map(|k| (k, place_span.0)),
426             ),
427             None => self.report_temporary_value_does_not_live_long_enough(
428                 context,
429                 &scope_tree,
430                 &borrow,
431                 drop_span,
432                 borrow_span,
433                 proper_span,
434             ),
435         };
436
437         borrow_spans.args_span_label(&mut err, "value captured here");
438
439         err.buffer(&mut self.errors_buffer);
440     }
441
442     fn report_local_value_does_not_live_long_enough(
443         &mut self,
444         context: Context,
445         name: &String,
446         scope_tree: &Lrc<ScopeTree>,
447         borrow: &BorrowData<'tcx>,
448         drop_span: Span,
449         borrow_span: Span,
450         _proper_span: Span,
451         kind_place: Option<(WriteKind, &Place<'tcx>)>,
452     ) -> DiagnosticBuilder<'cx> {
453         debug!(
454             "report_local_value_does_not_live_long_enough(\
455              {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
456              )",
457             context, name, scope_tree, borrow, drop_span, borrow_span
458         );
459
460         let mut err = self.tcx.path_does_not_live_long_enough(
461             borrow_span,
462             &format!("`{}`", name),
463             Origin::Mir,
464         );
465
466         err.span_label(borrow_span, "borrowed value does not live long enough");
467         err.span_label(
468             drop_span,
469             format!("`{}` dropped here while still borrowed", name),
470         );
471
472         self.explain_why_borrow_contains_point(context, borrow, kind_place, &mut err);
473         err
474     }
475
476     fn report_thread_local_value_does_not_live_long_enough(
477         &mut self,
478         drop_span: Span,
479         borrow_span: Span,
480     ) -> DiagnosticBuilder<'cx> {
481         debug!(
482             "report_thread_local_value_does_not_live_long_enough(\
483              {:?}, {:?}\
484              )",
485             drop_span, borrow_span
486         );
487
488         let mut err = self
489             .tcx
490             .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
491
492         err.span_label(
493             borrow_span,
494             "thread-local variables cannot be borrowed beyond the end of the function",
495         );
496         err.span_label(drop_span, "end of enclosing function is here");
497         err
498     }
499
500     fn report_temporary_value_does_not_live_long_enough(
501         &mut self,
502         context: Context,
503         scope_tree: &Lrc<ScopeTree>,
504         borrow: &BorrowData<'tcx>,
505         drop_span: Span,
506         _borrow_span: Span,
507         proper_span: Span,
508     ) -> DiagnosticBuilder<'cx> {
509         debug!(
510             "report_temporary_value_does_not_live_long_enough(\
511              {:?}, {:?}, {:?}, {:?}, {:?}\
512              )",
513             context, scope_tree, borrow, drop_span, proper_span
514         );
515
516         let tcx = self.tcx;
517         let mut err =
518             tcx.path_does_not_live_long_enough(proper_span, "borrowed value", Origin::Mir);
519         err.span_label(proper_span, "temporary value does not live long enough");
520         err.span_label(drop_span, "temporary value only lives until here");
521
522         self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
523         err
524     }
525
526     fn get_moved_indexes(&mut self, context: Context, mpi: MovePathIndex) -> Vec<MoveOutIndex> {
527         let mir = self.mir;
528
529         let mut stack = Vec::new();
530         stack.extend(mir.predecessor_locations(context.loc));
531
532         let mut visited = FxHashSet();
533         let mut result = vec![];
534
535         'dfs: while let Some(l) = stack.pop() {
536             debug!(
537                 "report_use_of_moved_or_uninitialized: current_location={:?}",
538                 l
539             );
540
541             if !visited.insert(l) {
542                 continue;
543             }
544
545             // check for moves
546             let stmt_kind = mir[l.block]
547                 .statements
548                 .get(l.statement_index)
549                 .map(|s| &s.kind);
550             if let Some(StatementKind::StorageDead(..)) = stmt_kind {
551                 // this analysis only tries to find moves explicitly
552                 // written by the user, so we ignore the move-outs
553                 // created by `StorageDead` and at the beginning
554                 // of a function.
555             } else {
556                 for moi in &self.move_data.loc_map[l] {
557                     debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
558                     if self.move_data.moves[*moi].path == mpi {
559                         debug!("report_use_of_moved_or_uninitialized: found");
560                         result.push(*moi);
561
562                         // Strictly speaking, we could continue our DFS here. There may be
563                         // other moves that can reach the point of error. But it is kind of
564                         // confusing to highlight them.
565                         //
566                         // Example:
567                         //
568                         // ```
569                         // let a = vec![];
570                         // let b = a;
571                         // let c = a;
572                         // drop(a); // <-- current point of error
573                         // ```
574                         //
575                         // Because we stop the DFS here, we only highlight `let c = a`,
576                         // and not `let b = a`. We will of course also report an error at
577                         // `let c = a` which highlights `let b = a` as the move.
578                         continue 'dfs;
579                     }
580                 }
581             }
582
583             // check for inits
584             let mut any_match = false;
585             drop_flag_effects::for_location_inits(self.tcx, self.mir, self.move_data, l, |m| {
586                 if m == mpi {
587                     any_match = true;
588                 }
589             });
590             if any_match {
591                 continue 'dfs;
592             }
593
594             stack.extend(mir.predecessor_locations(l));
595         }
596
597         result
598     }
599
600     pub(super) fn report_illegal_mutation_of_borrowed(
601         &mut self,
602         context: Context,
603         (place, span): (&Place<'tcx>, Span),
604         loan: &BorrowData<'tcx>,
605     ) {
606         let loan_spans = self.retrieve_borrow_spans(loan);
607         let loan_span = loan_spans.args_or_use();
608
609         let tcx = self.tcx;
610         let mut err = tcx.cannot_assign_to_borrowed(
611             span,
612             loan_span,
613             &self.describe_place(place).unwrap_or("_".to_owned()),
614             Origin::Mir,
615         );
616
617         loan_spans.var_span_label(&mut err, "borrow occurs due to use in closure");
618
619         self.explain_why_borrow_contains_point(context, loan, None, &mut err);
620
621         err.buffer(&mut self.errors_buffer);
622     }
623
624     /// Reports an illegal reassignment; for example, an assignment to
625     /// (part of) a non-`mut` local that occurs potentially after that
626     /// local has already been initialized. `place` is the path being
627     /// assigned; `err_place` is a place providing a reason why
628     /// `place` is not mutable (e.g. the non-`mut` local `x` in an
629     /// assignment to `x.f`).
630     pub(super) fn report_illegal_reassignment(
631         &mut self,
632         _context: Context,
633         (place, span): (&Place<'tcx>, Span),
634         assigned_span: Span,
635         err_place: &Place<'tcx>,
636     ) {
637         let (from_arg, local_decl) = if let Place::Local(local) = *err_place {
638             if let LocalKind::Arg = self.mir.local_kind(local) {
639                 (true, Some(&self.mir.local_decls[local]))
640             } else {
641                 (false, Some(&self.mir.local_decls[local]))
642             }
643         } else {
644             (false, None)
645         };
646
647         // If root local is initialized immediately (everything apart from let
648         // PATTERN;) then make the error refer to that local, rather than the
649         // place being assigned later.
650         let (place_description, assigned_span) = match local_decl {
651             Some(LocalDecl {
652                 is_user_variable: Some(ClearCrossCrate::Clear),
653                 ..
654             })
655             | Some(LocalDecl {
656                 is_user_variable:
657                     Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
658                         opt_match_place: None,
659                         ..
660                     }))),
661                 ..
662             })
663             | Some(LocalDecl {
664                 is_user_variable: None,
665                 ..
666             })
667             | None => (self.describe_place(place), assigned_span),
668             Some(decl) => (self.describe_place(err_place), decl.source_info.span),
669         };
670
671         let mut err = self.tcx.cannot_reassign_immutable(
672             span,
673             place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
674             from_arg,
675             Origin::Mir,
676         );
677         let msg = if from_arg {
678             "cannot assign to immutable argument"
679         } else {
680             "cannot assign twice to immutable variable"
681         };
682         if span != assigned_span {
683             if !from_arg {
684                 let value_msg = match place_description {
685                     Some(name) => format!("`{}`", name),
686                     None => "value".to_owned(),
687                 };
688                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
689             }
690         }
691         if let Some(decl) = local_decl {
692             if let Some(name) = decl.name {
693                 if decl.can_be_made_mutable() {
694                     err.span_label(
695                         decl.source_info.span,
696                         format!("consider changing this to `mut {}`", name),
697                     );
698                 }
699             }
700         }
701         err.span_label(span, msg);
702         err.buffer(&mut self.errors_buffer);
703     }
704 }
705
706 pub(super) struct IncludingDowncast(bool);
707
708 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
709     // End-user visible description of `place` if one can be found. If the
710     // place is a temporary for instance, None will be returned.
711     pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
712         self.describe_place_with_options(place, IncludingDowncast(false))
713     }
714
715     // End-user visible description of `place` if one can be found. If the
716     // place is a temporary for instance, None will be returned.
717     // `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
718     // `Downcast` and `IncludingDowncast` is true
719     pub(super) fn describe_place_with_options(
720         &self,
721         place: &Place<'tcx>,
722         including_downcast: IncludingDowncast,
723     ) -> Option<String> {
724         let mut buf = String::new();
725         match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
726             Ok(()) => Some(buf),
727             Err(()) => None,
728         }
729     }
730
731     // Appends end-user visible description of `place` to `buf`.
732     fn append_place_to_string(
733         &self,
734         place: &Place<'tcx>,
735         buf: &mut String,
736         mut autoderef: bool,
737         including_downcast: &IncludingDowncast,
738     ) -> Result<(), ()> {
739         match *place {
740             Place::Promoted(_) => {
741                 buf.push_str("promoted");
742             }
743             Place::Local(local) => {
744                 self.append_local_to_string(local, buf)?;
745             }
746             Place::Static(ref static_) => {
747                 buf.push_str(&self.tcx.item_name(static_.def_id).to_string());
748             }
749             Place::Projection(ref proj) => {
750                 match proj.elem {
751                     ProjectionElem::Deref => {
752                         let upvar_field_projection =
753                             place.is_upvar_field_projection(self.mir, &self.tcx);
754                         if let Some(field) = upvar_field_projection {
755                             let var_index = field.index();
756                             let name = self.mir.upvar_decls[var_index].debug_name.to_string();
757                             if self.mir.upvar_decls[var_index].by_ref {
758                                 buf.push_str(&name);
759                             } else {
760                                 buf.push_str(&format!("*{}", &name));
761                             }
762                         } else {
763                             if autoderef {
764                                 self.append_place_to_string(
765                                     &proj.base,
766                                     buf,
767                                     autoderef,
768                                     &including_downcast,
769                                 )?;
770                             } else if let Place::Local(local) = proj.base {
771                                 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
772                                     self.mir.local_decls[local].is_user_variable
773                                 {
774                                     self.append_place_to_string(
775                                         &proj.base,
776                                         buf,
777                                         autoderef,
778                                         &including_downcast,
779                                     )?;
780                                 } else {
781                                     buf.push_str(&"*");
782                                     self.append_place_to_string(
783                                         &proj.base,
784                                         buf,
785                                         autoderef,
786                                         &including_downcast,
787                                     )?;
788                                 }
789                             } else {
790                                 buf.push_str(&"*");
791                                 self.append_place_to_string(
792                                     &proj.base,
793                                     buf,
794                                     autoderef,
795                                     &including_downcast,
796                                 )?;
797                             }
798                         }
799                     }
800                     ProjectionElem::Downcast(..) => {
801                         self.append_place_to_string(
802                             &proj.base,
803                             buf,
804                             autoderef,
805                             &including_downcast,
806                         )?;
807                         if including_downcast.0 {
808                             return Err(());
809                         }
810                     }
811                     ProjectionElem::Field(field, _ty) => {
812                         autoderef = true;
813
814                         let upvar_field_projection =
815                             place.is_upvar_field_projection(self.mir, &self.tcx);
816                         if let Some(field) = upvar_field_projection {
817                             let var_index = field.index();
818                             let name = self.mir.upvar_decls[var_index].debug_name.to_string();
819                             buf.push_str(&name);
820                         } else {
821                             let field_name = self.describe_field(&proj.base, field);
822                             self.append_place_to_string(
823                                 &proj.base,
824                                 buf,
825                                 autoderef,
826                                 &including_downcast,
827                             )?;
828                             buf.push_str(&format!(".{}", field_name));
829                         }
830                     }
831                     ProjectionElem::Index(index) => {
832                         autoderef = true;
833
834                         self.append_place_to_string(
835                             &proj.base,
836                             buf,
837                             autoderef,
838                             &including_downcast,
839                         )?;
840                         buf.push_str("[");
841                         if self.append_local_to_string(index, buf).is_err() {
842                             buf.push_str("..");
843                         }
844                         buf.push_str("]");
845                     }
846                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
847                         autoderef = true;
848                         // Since it isn't possible to borrow an element on a particular index and
849                         // then use another while the borrow is held, don't output indices details
850                         // to avoid confusing the end-user
851                         self.append_place_to_string(
852                             &proj.base,
853                             buf,
854                             autoderef,
855                             &including_downcast,
856                         )?;
857                         buf.push_str(&"[..]");
858                     }
859                 };
860             }
861         }
862
863         Ok(())
864     }
865
866     // Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
867     // a name, then `Err` is returned
868     fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
869         let local = &self.mir.local_decls[local_index];
870         match local.name {
871             Some(name) => {
872                 buf.push_str(&name.to_string());
873                 Ok(())
874             }
875             None => Err(()),
876         }
877     }
878
879     // End-user visible description of the `field`nth field of `base`
880     fn describe_field(&self, base: &Place, field: Field) -> String {
881         match *base {
882             Place::Local(local) => {
883                 let local = &self.mir.local_decls[local];
884                 self.describe_field_from_ty(&local.ty, field)
885             }
886             Place::Promoted(ref prom) => self.describe_field_from_ty(&prom.1, field),
887             Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
888             Place::Projection(ref proj) => match proj.elem {
889                 ProjectionElem::Deref => self.describe_field(&proj.base, field),
890                 ProjectionElem::Downcast(def, variant_index) => format!(
891                     "{}",
892                     def.variants[variant_index].fields[field.index()].ident
893                 ),
894                 ProjectionElem::Field(_, field_type) => {
895                     self.describe_field_from_ty(&field_type, field)
896                 }
897                 ProjectionElem::Index(..)
898                 | ProjectionElem::ConstantIndex { .. }
899                 | ProjectionElem::Subslice { .. } => {
900                     self.describe_field(&proj.base, field).to_string()
901                 }
902             },
903         }
904     }
905
906     // End-user visible description of the `field_index`nth field of `ty`
907     fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
908         if ty.is_box() {
909             // If the type is a box, the field is described from the boxed type
910             self.describe_field_from_ty(&ty.boxed_ty(), field)
911         } else {
912             match ty.sty {
913                 ty::Adt(def, _) => if def.is_enum() {
914                     field.index().to_string()
915                 } else {
916                     def.non_enum_variant().fields[field.index()]
917                         .ident
918                         .to_string()
919                 },
920                 ty::Tuple(_) => field.index().to_string(),
921                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
922                     self.describe_field_from_ty(&ty, field)
923                 }
924                 ty::Array(ty, _) | ty::Slice(ty) => self.describe_field_from_ty(&ty, field),
925                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
926                     // Convert the def-id into a node-id. node-ids are only valid for
927                     // the local code in the current crate, so this returns an `Option` in case
928                     // the closure comes from another crate. But in that case we wouldn't
929                     // be borrowck'ing it, so we can just unwrap:
930                     let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
931                     let freevar = self.tcx.with_freevars(node_id, |fv| fv[field.index()]);
932
933                     self.tcx.hir.name(freevar.var_id()).to_string()
934                 }
935                 _ => {
936                     // Might need a revision when the fields in trait RFC is implemented
937                     // (https://github.com/rust-lang/rfcs/pull/1546)
938                     bug!(
939                         "End-user description not implemented for field access on `{:?}`",
940                         ty.sty
941                     );
942                 }
943             }
944         }
945     }
946
947     // Retrieve type of a place for the current MIR representation
948     fn retrieve_type_for_place(&self, place: &Place<'tcx>) -> Option<ty::Ty> {
949         match place {
950             Place::Local(local) => {
951                 let local = &self.mir.local_decls[*local];
952                 Some(local.ty)
953             }
954             Place::Promoted(ref prom) => Some(prom.1),
955             Place::Static(ref st) => Some(st.ty),
956             Place::Projection(ref proj) => match proj.elem {
957                 ProjectionElem::Field(_, ty) => Some(ty),
958                 _ => None,
959             },
960         }
961     }
962
963     /// Check if a place is a thread-local static.
964     pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
965         if let Place::Static(statik) = place {
966             let attrs = self.tcx.get_attrs(statik.def_id);
967             let is_thread_local = attrs.iter().any(|attr| attr.check_name("thread_local"));
968
969             debug!(
970                 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
971                 attrs, is_thread_local
972             );
973             is_thread_local
974         } else {
975             debug!("is_place_thread_local: no");
976             false
977         }
978     }
979 }
980
981 // The span(s) associated to a use of a place.
982 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
983 pub(super) enum UseSpans {
984     // The access is caused by capturing a variable for a closure.
985     ClosureUse {
986         // The span of the args of the closure, including the `move` keyword if
987         // it's present.
988         args_span: Span,
989         // The span of the first use of the captured variable inside the closure.
990         var_span: Span,
991     },
992     // This access has a single span associated to it: common case.
993     OtherUse(Span),
994 }
995
996 impl UseSpans {
997     pub(super) fn args_or_use(self) -> Span {
998         match self {
999             UseSpans::ClosureUse {
1000                 args_span: span, ..
1001             }
1002             | UseSpans::OtherUse(span) => span,
1003         }
1004     }
1005
1006     pub(super) fn var_or_use(self) -> Span {
1007         match self {
1008             UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
1009         }
1010     }
1011
1012     // Add a span label to the arguments of the closure, if it exists.
1013     pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1014         if let UseSpans::ClosureUse { args_span, .. } = self {
1015             err.span_label(args_span, message);
1016         }
1017     }
1018
1019     // Add a span label to the use of the captured variable, if it exists.
1020     pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1021         if let UseSpans::ClosureUse { var_span, .. } = self {
1022             err.span_label(var_span, message);
1023         }
1024     }
1025
1026     pub(super) fn for_closure(self) -> bool {
1027         match self {
1028             UseSpans::ClosureUse { .. } => true,
1029             UseSpans::OtherUse(_) => false,
1030         }
1031     }
1032
1033     pub(super) fn or_else<F>(self, if_other: F) -> Self
1034     where
1035         F: FnOnce() -> Self,
1036     {
1037         match self {
1038             closure @ UseSpans::ClosureUse { .. } => closure,
1039             UseSpans::OtherUse(_) => if_other(),
1040         }
1041     }
1042 }
1043
1044 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1045     /// Finds the spans associated to a move or copy of move_place at location.
1046     pub(super) fn move_spans(
1047         &self,
1048         moved_place: &Place<'tcx>, // Could also be an upvar.
1049         location: Location,
1050     ) -> UseSpans {
1051         use self::UseSpans::*;
1052         use rustc::hir::ExprKind::Closure;
1053         use rustc::mir::AggregateKind;
1054
1055         let stmt = match self.mir[location.block]
1056             .statements
1057             .get(location.statement_index)
1058         {
1059             Some(stmt) => stmt,
1060             None => return OtherUse(self.mir.source_info(location).span),
1061         };
1062
1063         if let StatementKind::Assign(_, Rvalue::Aggregate(ref kind, ref places)) = stmt.kind {
1064             if let AggregateKind::Closure(def_id, _) = **kind {
1065                 debug!("find_closure_move_span: found closure {:?}", places);
1066
1067                 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1068                     if let Closure(_, _, _, args_span, _) = self.tcx.hir.expect_expr(node_id).node {
1069                         if let Some(var_span) = self.tcx.with_freevars(node_id, |freevars| {
1070                             for (v, place) in freevars.iter().zip(places) {
1071                                 match place {
1072                                     Operand::Copy(place) | Operand::Move(place)
1073                                         if moved_place == place =>
1074                                     {
1075                                         debug!(
1076                                             "find_closure_move_span: found captured local {:?}",
1077                                             place
1078                                         );
1079                                         return Some(v.span);
1080                                     }
1081                                     _ => {}
1082                                 }
1083                             }
1084                             None
1085                         }) {
1086                             return ClosureUse {
1087                                 args_span,
1088                                 var_span,
1089                             };
1090                         }
1091                     }
1092                 }
1093             }
1094         }
1095
1096         return OtherUse(stmt.source_info.span);
1097     }
1098
1099     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
1100     /// and its usage of the local assigned at `location`.
1101     /// This is done by searching in statements succeeding `location`
1102     /// and originating from `maybe_closure_span`.
1103     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
1104         use self::UseSpans::*;
1105         use rustc::hir::ExprKind::Closure;
1106         use rustc::mir::AggregateKind;
1107
1108         let local = match self.mir[location.block]
1109             .statements
1110             .get(location.statement_index)
1111         {
1112             Some(&Statement {
1113                 kind: StatementKind::Assign(Place::Local(local), _),
1114                 ..
1115             }) => local,
1116             _ => return OtherUse(use_span),
1117         };
1118
1119         if self.mir.local_kind(local) != LocalKind::Temp {
1120             // operands are always temporaries.
1121             return OtherUse(use_span);
1122         }
1123
1124         for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1125             if let StatementKind::Assign(_, Rvalue::Aggregate(ref kind, ref places)) = stmt.kind {
1126                 if let AggregateKind::Closure(def_id, _) = **kind {
1127                     debug!("find_closure_borrow_span: found closure {:?}", places);
1128
1129                     return if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1130                         let args_span = if let Closure(_, _, _, span, _) =
1131                             self.tcx.hir.expect_expr(node_id).node
1132                         {
1133                             span
1134                         } else {
1135                             return OtherUse(use_span);
1136                         };
1137
1138                         self.tcx
1139                             .with_freevars(node_id, |freevars| {
1140                                 for (v, place) in freevars.iter().zip(places) {
1141                                     match *place {
1142                                         Operand::Copy(Place::Local(l))
1143                                         | Operand::Move(Place::Local(l))
1144                                             if local == l =>
1145                                         {
1146                                             debug!(
1147                                                 "find_closure_borrow_span: found captured local \
1148                                                  {:?}",
1149                                                 l
1150                                             );
1151                                             return Some(v.span);
1152                                         }
1153                                         _ => {}
1154                                     }
1155                                 }
1156                                 None
1157                             }).map(|var_span| ClosureUse {
1158                                 args_span,
1159                                 var_span,
1160                             }).unwrap_or(OtherUse(use_span))
1161                     } else {
1162                         OtherUse(use_span)
1163                     };
1164                 }
1165             }
1166
1167             if use_span != stmt.source_info.span {
1168                 break;
1169             }
1170         }
1171
1172         OtherUse(use_span)
1173     }
1174
1175     /// Helper to retrieve span(s) of given borrow from the current MIR
1176     /// representation
1177     pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
1178         let span = self.mir.source_info(borrow.reserve_location).span;
1179         self.borrow_spans(span, borrow.reserve_location)
1180     }
1181 }