2 use rustc::hir::def::Namespace;
3 use rustc::hir::def_id::DefId;
4 use rustc::hir::GeneratorKind;
6 AggregateKind, Constant, Field, Local, LocalInfo, LocalKind, Location, Operand,
7 Place, PlaceBase, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind,
8 Static, StaticKind, Terminator, TerminatorKind,
10 use rustc::ty::{self, DefIdTree, Ty, TyCtxt};
11 use rustc::ty::layout::VariantIdx;
12 use rustc::ty::print::Print;
13 use rustc_errors::DiagnosticBuilder;
16 use super::borrow_set::BorrowData;
17 use super::MirBorrowckCtxt;
18 use crate::dataflow::move_paths::{InitLocation, LookupResult};
20 pub(super) struct IncludingDowncast(pub(super) bool);
22 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
23 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
24 /// is moved after being invoked.
27 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
29 /// --> $DIR/issue-42065.rs:16:29
31 /// LL | for (key, value) in dict {
34 pub(super) fn add_moved_or_invoked_closure_note(
37 place: PlaceRef<'cx, 'tcx>,
38 diag: &mut DiagnosticBuilder<'_>,
40 debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
41 let mut target = place.local_or_deref_local();
42 for stmt in &self.body_cache[location.block].statements[location.statement_index..] {
43 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
44 if let StatementKind::Assign(box(into, Rvalue::Use(from))) = &stmt.kind {
45 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
47 Operand::Copy(ref place) |
48 Operand::Move(ref place) if target == place.local_or_deref_local() =>
49 target = into.local_or_deref_local(),
55 // Check if we are attempting to call a closure after it has been invoked.
56 let terminator = self.body_cache[location.block].terminator();
57 debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
58 if let TerminatorKind::Call {
59 func: Operand::Constant(box Constant {
61 ty: &ty::TyS { kind: ty::FnDef(id, _), .. },
68 } = &terminator.kind {
69 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
70 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
71 let closure = match args.first() {
72 Some(Operand::Copy(ref place)) |
73 Some(Operand::Move(ref place)) if target == place.local_or_deref_local() =>
74 place.local_or_deref_local().unwrap(),
78 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
79 if let ty::Closure(did, _) = self.body_cache.local_decls[closure].ty.kind {
80 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
82 if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
83 .closure_kind_origins()
89 "closure cannot be invoked more than once because it moves the \
90 variable `{}` out of its environment",
100 // Check if we are just moving a closure after it has been invoked.
101 if let Some(target) = target {
102 if let ty::Closure(did, _) = self.body_cache.local_decls[target].ty.kind {
103 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
105 if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
106 .closure_kind_origins()
112 "closure cannot be moved more than once as it is not `Copy` due to \
113 moving the variable `{}` out of its environment",
122 /// End-user visible description of `place` if one can be found. If the
123 /// place is a temporary for instance, None will be returned.
124 pub(super) fn describe_place(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<String> {
125 self.describe_place_with_options(place_ref, IncludingDowncast(false))
128 /// End-user visible description of `place` if one can be found. If the
129 /// place is a temporary for instance, None will be returned.
130 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
131 /// `Downcast` and `IncludingDowncast` is true
132 pub(super) fn describe_place_with_options(
134 place: PlaceRef<'cx, 'tcx>,
135 including_downcast: IncludingDowncast,
136 ) -> Option<String> {
137 let mut buf = String::new();
138 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
144 /// Appends end-user visible description of `place` to `buf`.
145 fn append_place_to_string(
147 place: PlaceRef<'cx, 'tcx>,
150 including_downcast: &IncludingDowncast,
151 ) -> Result<(), ()> {
154 base: PlaceBase::Local(local),
157 self.append_local_to_string(*local, buf)?;
161 PlaceBase::Static(box Static {
162 kind: StaticKind::Promoted(..),
167 buf.push_str("promoted");
171 PlaceBase::Static(box Static {
172 kind: StaticKind::Static,
178 buf.push_str(&self.infcx.tcx.item_name(*def_id).to_string());
181 base: &PlaceBase::Local(local),
182 projection: [ProjectionElem::Deref]
183 } if self.body.local_decls[local].is_ref_for_guard() => {
184 self.append_place_to_string(
186 base: &PlaceBase::Local(local),
195 base: &PlaceBase::Local(local),
196 projection: [ProjectionElem::Deref]
197 } if self.body.local_decls[local].is_ref_to_static() => {
198 let local_info = &self.body.local_decls[local].local_info;
199 if let LocalInfo::StaticRef { def_id, .. } = *local_info {
200 buf.push_str(&self.infcx.tcx.item_name(def_id).as_str());
207 projection: [proj_base @ .., elem],
210 ProjectionElem::Deref => {
211 let upvar_field_projection =
212 self.is_upvar_field_projection(place);
213 if let Some(field) = upvar_field_projection {
214 let var_index = field.index();
215 let name = self.upvars[var_index].name.to_string();
216 if self.upvars[var_index].by_ref {
219 buf.push_str(&format!("*{}", &name));
223 // FIXME turn this recursion into iteration
224 self.append_place_to_string(
227 projection: proj_base,
234 match (proj_base, base) {
237 self.append_place_to_string(
240 projection: proj_base,
251 ProjectionElem::Downcast(..) => {
252 self.append_place_to_string(
255 projection: proj_base,
261 if including_downcast.0 {
265 ProjectionElem::Field(field, _ty) => {
268 let upvar_field_projection =
269 self.is_upvar_field_projection(place);
270 if let Some(field) = upvar_field_projection {
271 let var_index = field.index();
272 let name = self.upvars[var_index].name.to_string();
275 let field_name = self.describe_field(PlaceRef {
277 projection: proj_base,
279 self.append_place_to_string(
282 projection: proj_base,
288 buf.push_str(&format!(".{}", field_name));
291 ProjectionElem::Index(index) => {
294 self.append_place_to_string(
297 projection: proj_base,
304 if self.append_local_to_string(*index, buf).is_err() {
309 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
311 // Since it isn't possible to borrow an element on a particular index and
312 // then use another while the borrow is held, don't output indices details
313 // to avoid confusing the end-user
314 self.append_place_to_string(
317 projection: proj_base,
323 buf.push_str(&"[..]");
332 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
333 /// a name, or its name was generated by the compiler, then `Err` is returned
334 fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
335 let decl = &self.body_cache.local_decls[local];
336 match self.local_names[local] {
337 Some(name) if !decl.from_compiler_desugaring() => {
338 buf.push_str(&name.as_str());
345 /// End-user visible description of the `field`nth field of `base`
346 fn describe_field(&self, place: PlaceRef<'cx, 'tcx>, field: Field) -> String {
347 // FIXME Place2 Make this work iteratively
350 base: PlaceBase::Local(local),
353 let local = &self.body_cache.local_decls[*local];
354 self.describe_field_from_ty(&local.ty, field, None)
357 base: PlaceBase::Static(static_),
360 self.describe_field_from_ty(&static_.ty, field, None),
363 projection: [proj_base @ .., elem],
365 ProjectionElem::Deref => {
366 self.describe_field(PlaceRef {
368 projection: proj_base,
371 ProjectionElem::Downcast(_, variant_index) => {
373 Place::ty_from(place.base, place.projection, self.body_cache.body(), self.infcx.tcx).ty;
374 self.describe_field_from_ty(&base_ty, field, Some(*variant_index))
376 ProjectionElem::Field(_, field_type) => {
377 self.describe_field_from_ty(&field_type, field, None)
379 ProjectionElem::Index(..)
380 | ProjectionElem::ConstantIndex { .. }
381 | ProjectionElem::Subslice { .. } => {
382 self.describe_field(PlaceRef {
384 projection: proj_base,
391 /// End-user visible description of the `field_index`nth field of `ty`
392 fn describe_field_from_ty(
396 variant_index: Option<VariantIdx>
399 // If the type is a box, the field is described from the boxed type
400 self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
404 let variant = if let Some(idx) = variant_index {
405 assert!(def.is_enum());
408 def.non_enum_variant()
410 variant.fields[field.index()]
414 ty::Tuple(_) => field.index().to_string(),
415 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
416 self.describe_field_from_ty(&ty, field, variant_index)
418 ty::Array(ty, _) | ty::Slice(ty) =>
419 self.describe_field_from_ty(&ty, field, variant_index),
420 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
421 // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
422 // the closure comes from another crate. But in that case we wouldn't
423 // be borrowck'ing it, so we can just unwrap:
424 let (&var_id, _) = self.infcx.tcx.upvars(def_id).unwrap()
425 .get_index(field.index()).unwrap();
427 self.infcx.tcx.hir().name(var_id).to_string()
430 // Might need a revision when the fields in trait RFC is implemented
431 // (https://github.com/rust-lang/rfcs/pull/1546)
433 "End-user description not implemented for field access on `{:?}`",
441 /// Add a note that a type does not implement `Copy`
442 pub(super) fn note_type_does_not_implement_copy(
444 err: &mut DiagnosticBuilder<'a>,
449 let message = format!(
450 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
454 if let Some(span) = span {
455 err.span_label(span, message);
461 pub(super) fn borrowed_content_source(
463 deref_base: PlaceRef<'cx, 'tcx>,
464 ) -> BorrowedContentSource<'tcx> {
465 let tcx = self.infcx.tcx;
467 // Look up the provided place and work out the move path index for it,
468 // we'll use this to check whether it was originally from an overloaded
470 match self.move_data.rev_lookup.find(deref_base) {
471 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
472 debug!("borrowed_content_source: mpi={:?}", mpi);
474 for i in &self.move_data.init_path_map[mpi] {
475 let init = &self.move_data.inits[*i];
476 debug!("borrowed_content_source: init={:?}", init);
477 // We're only interested in statements that initialized a value, not the
478 // initializations from arguments.
479 let loc = match init.location {
480 InitLocation::Statement(stmt) => stmt,
484 let bbd = &self.body_cache[loc.block];
485 let is_terminator = bbd.statements.len() == loc.statement_index;
487 "borrowed_content_source: loc={:?} is_terminator={:?}",
493 } else if let Some(Terminator {
494 kind: TerminatorKind::Call {
496 from_hir_call: false,
500 }) = bbd.terminator {
502 = BorrowedContentSource::from_call(func.ty(self.body_cache.body(), tcx), tcx)
509 // Base is a `static` so won't be from an overloaded operator
513 // If we didn't find an overloaded deref or index, then assume it's a
514 // built in deref and check the type of the base.
515 let base_ty = Place::ty_from(deref_base.base, deref_base.projection, self.body_cache.body(), tcx).ty;
516 if base_ty.is_unsafe_ptr() {
517 BorrowedContentSource::DerefRawPointer
518 } else if base_ty.is_mutable_ptr() {
519 BorrowedContentSource::DerefMutableRef
521 BorrowedContentSource::DerefSharedRef
526 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
527 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
528 /// name where required.
529 pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
530 let mut s = String::new();
531 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
533 // We need to add synthesized lifetimes where appropriate. We do
534 // this by hooking into the pretty printer and telling it to label the
535 // lifetimes without names with the value `'0`.
537 ty::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
539 ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
542 ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
546 let _ = ty.print(printer);
550 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
551 /// synthesized lifetime name where required.
552 pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
553 let mut s = String::new();
554 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
556 let region = match ty.kind {
557 ty::Ref(region, _, _) => {
559 ty::RegionKind::ReLateBound(_, br)
560 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
561 printer.region_highlight_mode.highlighting_bound_region(*br, counter)
568 _ => bug!("ty for annotation of borrow region is not a reference"),
571 let _ = region.print(printer);
576 // The span(s) associated to a use of a place.
577 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
578 pub(super) enum UseSpans {
579 // The access is caused by capturing a variable for a closure.
581 // This is true if the captured variable was from a generator.
582 generator_kind: Option<GeneratorKind>,
583 // The span of the args of the closure, including the `move` keyword if
586 // The span of the first use of the captured variable inside the closure.
589 // This access has a single span associated to it: common case.
594 pub(super) fn args_or_use(self) -> Span {
596 UseSpans::ClosureUse {
599 | UseSpans::OtherUse(span) => span,
603 pub(super) fn var_or_use(self) -> Span {
605 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
609 pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
611 UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
616 // Add a span label to the arguments of the closure, if it exists.
617 pub(super) fn args_span_label(
619 err: &mut DiagnosticBuilder<'_>,
620 message: impl Into<String>,
622 if let UseSpans::ClosureUse { args_span, .. } = self {
623 err.span_label(args_span, message);
627 // Add a span label to the use of the captured variable, if it exists.
628 pub(super) fn var_span_label(
630 err: &mut DiagnosticBuilder<'_>,
631 message: impl Into<String>,
633 if let UseSpans::ClosureUse { var_span, .. } = self {
634 err.span_label(var_span, message);
638 /// Returns `false` if this place is not used in a closure.
639 pub(super) fn for_closure(&self) -> bool {
641 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
646 /// Returns `false` if this place is not used in a generator.
647 pub(super) fn for_generator(&self) -> bool {
649 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
654 /// Describe the span associated with a use of a place.
655 pub(super) fn describe(&self) -> String {
657 UseSpans::ClosureUse { generator_kind, .. } => if generator_kind.is_some() {
658 " in generator".to_string()
660 " in closure".to_string()
666 pub(super) fn or_else<F>(self, if_other: F) -> Self
671 closure @ UseSpans::ClosureUse { .. } => closure,
672 UseSpans::OtherUse(_) => if_other(),
677 pub(super) enum BorrowedContentSource<'tcx> {
681 OverloadedDeref(Ty<'tcx>),
682 OverloadedIndex(Ty<'tcx>),
685 impl BorrowedContentSource<'tcx> {
686 pub(super) fn describe_for_unnamed_place(&self) -> String {
688 BorrowedContentSource::DerefRawPointer => format!("a raw pointer"),
689 BorrowedContentSource::DerefSharedRef => format!("a shared reference"),
690 BorrowedContentSource::DerefMutableRef => {
691 format!("a mutable reference")
693 BorrowedContentSource::OverloadedDeref(ty) => {
696 } else if ty.is_arc() {
699 format!("dereference of `{}`", ty)
702 BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
706 pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
708 BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
709 BorrowedContentSource::DerefSharedRef => Some("shared reference"),
710 BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
711 // Overloaded deref and index operators should be evaluated into a
712 // temporary. So we don't need a description here.
713 BorrowedContentSource::OverloadedDeref(_)
714 | BorrowedContentSource::OverloadedIndex(_) => None
718 pub(super) fn describe_for_immutable_place(&self) -> String {
720 BorrowedContentSource::DerefRawPointer => format!("a `*const` pointer"),
721 BorrowedContentSource::DerefSharedRef => format!("a `&` reference"),
722 BorrowedContentSource::DerefMutableRef => {
723 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
725 BorrowedContentSource::OverloadedDeref(ty) => {
728 } else if ty.is_arc() {
731 format!("a dereference of `{}`", ty)
734 BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
738 fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
740 ty::FnDef(def_id, substs) => {
741 let trait_id = tcx.trait_of_item(def_id)?;
743 let lang_items = tcx.lang_items();
744 if Some(trait_id) == lang_items.deref_trait()
745 || Some(trait_id) == lang_items.deref_mut_trait()
747 Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
748 } else if Some(trait_id) == lang_items.index_trait()
749 || Some(trait_id) == lang_items.index_mut_trait()
751 Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
761 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
762 /// Finds the spans associated to a move or copy of move_place at location.
763 pub(super) fn move_spans(
765 moved_place: PlaceRef<'cx, 'tcx>, // Could also be an upvar.
768 use self::UseSpans::*;
770 let stmt = match self.body_cache[location.block].statements.get(location.statement_index) {
772 None => return OtherUse(self.body_cache.source_info(location).span),
775 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
776 if let StatementKind::Assign(
777 box(_, Rvalue::Aggregate(ref kind, ref places))
779 let def_id = match kind {
780 box AggregateKind::Closure(def_id, _)
781 | box AggregateKind::Generator(def_id, _, _) => def_id,
782 _ => return OtherUse(stmt.source_info.span),
786 "move_spans: def_id={:?} places={:?}",
789 if let Some((args_span, generator_kind, var_span))
790 = self.closure_span(*def_id, moved_place, places) {
799 OtherUse(stmt.source_info.span)
802 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
803 /// and its usage of the local assigned at `location`.
804 /// This is done by searching in statements succeeding `location`
805 /// and originating from `maybe_closure_span`.
806 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
807 use self::UseSpans::*;
808 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
810 let target = match self.body_cache[location.block]
812 .get(location.statement_index)
815 kind: StatementKind::Assign(box(ref place, _)),
818 if let Some(local) = place.as_local() {
821 return OtherUse(use_span);
824 _ => return OtherUse(use_span),
827 if self.body_cache.local_kind(target) != LocalKind::Temp {
828 // operands are always temporaries.
829 return OtherUse(use_span);
832 for stmt in &self.body_cache[location.block].statements[location.statement_index + 1..] {
833 if let StatementKind::Assign(
834 box(_, Rvalue::Aggregate(ref kind, ref places))
836 let (def_id, is_generator) = match kind {
837 box AggregateKind::Closure(def_id, _) => (def_id, false),
838 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
843 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
844 def_id, is_generator, places
846 if let Some((args_span, generator_kind, var_span)) = self.closure_span(
847 *def_id, Place::from(target).as_ref(), places
855 return OtherUse(use_span);
859 if use_span != stmt.source_info.span {
867 /// Finds the span of a captured variable within a closure or generator.
871 target_place: PlaceRef<'cx, 'tcx>,
872 places: &Vec<Operand<'tcx>>,
873 ) -> Option<(Span, Option<GeneratorKind>, Span)> {
875 "closure_span: def_id={:?} target_place={:?} places={:?}",
876 def_id, target_place, places
878 let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id)?;
879 let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
880 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
881 if let hir::ExprKind::Closure(
882 .., body_id, args_span, _
884 for (upvar, place) in self.infcx.tcx.upvars(def_id)?.values().zip(places) {
886 Operand::Copy(place) |
887 Operand::Move(place) if target_place == place.as_ref() => {
888 debug!("closure_span: found captured local {:?}", place);
889 let body = self.infcx.tcx.hir().body(*body_id);
890 let generator_kind = body.generator_kind();
891 return Some((*args_span, generator_kind, upvar.span));
901 /// Helper to retrieve span(s) of given borrow from the current MIR
903 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
904 let span = self.body_cache.source_info(borrow.reserve_location).span;
905 self.borrow_spans(span, borrow.reserve_location)