2 use rustc::hir::def::Namespace;
3 use rustc::hir::def_id::DefId;
5 AggregateKind, Constant, Field, Local, LocalKind, Location, Operand,
6 Place, PlaceBase, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind,
7 Static, StaticKind, Terminator, TerminatorKind,
9 use rustc::ty::{self, DefIdTree, Ty, TyCtxt};
10 use rustc::ty::layout::VariantIdx;
11 use rustc::ty::print::Print;
12 use rustc_errors::DiagnosticBuilder;
14 use syntax::symbol::sym;
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[location.block].statements[location.statement_index..] {
43 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
44 if let StatementKind::Assign(into, box 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[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 { sty: 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.local_decls[closure].ty.sty {
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.local_decls[target].ty.sty {
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());
182 projection: Some(ref proj),
185 ProjectionElem::Deref => {
186 let upvar_field_projection =
187 self.is_upvar_field_projection(place);
188 if let Some(field) = upvar_field_projection {
189 let var_index = field.index();
190 let name = self.upvars[var_index].name.to_string();
191 if self.upvars[var_index].by_ref {
194 buf.push_str(&format!("*{}", &name));
198 // FIXME turn this recursion into iteration
199 self.append_place_to_string(
202 projection: &proj.base,
209 match (&proj.base, base) {
210 (None, PlaceBase::Local(local)) => {
211 if self.body.local_decls[*local].is_ref_for_guard() {
212 self.append_place_to_string(
215 projection: &proj.base,
222 // FIXME deduplicate this and the _ => body below
224 self.append_place_to_string(
227 projection: &proj.base,
238 self.append_place_to_string(
241 projection: &proj.base,
252 ProjectionElem::Downcast(..) => {
253 self.append_place_to_string(
256 projection: &proj.base,
262 if including_downcast.0 {
266 ProjectionElem::Field(field, _ty) => {
269 let upvar_field_projection =
270 self.is_upvar_field_projection(place);
271 if let Some(field) = upvar_field_projection {
272 let var_index = field.index();
273 let name = self.upvars[var_index].name.to_string();
276 let field_name = self.describe_field(PlaceRef {
278 projection: &proj.base,
280 self.append_place_to_string(
283 projection: &proj.base,
289 buf.push_str(&format!(".{}", field_name));
292 ProjectionElem::Index(index) => {
295 self.append_place_to_string(
298 projection: &proj.base,
305 if self.append_local_to_string(index, buf).is_err() {
310 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
312 // Since it isn't possible to borrow an element on a particular index and
313 // then use another while the borrow is held, don't output indices details
314 // to avoid confusing the end-user
315 self.append_place_to_string(
318 projection: &proj.base,
324 buf.push_str(&"[..]");
333 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
334 /// a name, or its name was generated by the compiler, then `Err` is returned
335 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
336 let local = &self.body.local_decls[local_index];
338 Some(name) if !local.from_compiler_desugaring() => {
339 buf.push_str(&name.as_str());
346 /// End-user visible description of the `field`nth field of `base`
347 fn describe_field(&self, place: PlaceRef<'cx, 'tcx>, field: Field) -> String {
348 // FIXME Place2 Make this work iteratively
351 base: PlaceBase::Local(local),
354 let local = &self.body.local_decls[*local];
355 self.describe_field_from_ty(&local.ty, field, None)
358 base: PlaceBase::Static(static_),
361 self.describe_field_from_ty(&static_.ty, field, None),
364 projection: Some(proj),
365 } => match proj.elem {
366 ProjectionElem::Deref => self.describe_field(PlaceRef {
368 projection: &proj.base,
370 ProjectionElem::Downcast(_, variant_index) => {
372 Place::ty_from(place.base, place.projection, self.body, self.infcx.tcx).ty;
373 self.describe_field_from_ty(&base_ty, field, Some(variant_index))
375 ProjectionElem::Field(_, field_type) => {
376 self.describe_field_from_ty(&field_type, field, None)
378 ProjectionElem::Index(..)
379 | ProjectionElem::ConstantIndex { .. }
380 | ProjectionElem::Subslice { .. } => {
381 self.describe_field(PlaceRef {
383 projection: &proj.base,
390 /// End-user visible description of the `field_index`nth field of `ty`
391 fn describe_field_from_ty(
395 variant_index: Option<VariantIdx>
398 // If the type is a box, the field is described from the boxed type
399 self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
403 let variant = if let Some(idx) = variant_index {
404 assert!(def.is_enum());
407 def.non_enum_variant()
409 variant.fields[field.index()]
413 ty::Tuple(_) => field.index().to_string(),
414 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
415 self.describe_field_from_ty(&ty, field, variant_index)
417 ty::Array(ty, _) | ty::Slice(ty) =>
418 self.describe_field_from_ty(&ty, field, variant_index),
419 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
420 // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
421 // the closure comes from another crate. But in that case we wouldn't
422 // be borrowck'ing it, so we can just unwrap:
423 let (&var_id, _) = self.infcx.tcx.upvars(def_id).unwrap()
424 .get_index(field.index()).unwrap();
426 self.infcx.tcx.hir().name(var_id).to_string()
429 // Might need a revision when the fields in trait RFC is implemented
430 // (https://github.com/rust-lang/rfcs/pull/1546)
432 "End-user description not implemented for field access on `{:?}`",
440 /// Checks if a place is a thread-local static.
441 pub fn is_place_thread_local(&self, place_ref: PlaceRef<'cx, 'tcx>) -> bool {
443 base: PlaceBase::Static(box Static {
444 kind: StaticKind::Static,
450 let attrs = self.infcx.tcx.get_attrs(*def_id);
451 let is_thread_local = attrs.iter().any(|attr| attr.check_name(sym::thread_local));
454 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
455 attrs, is_thread_local
459 debug!("is_place_thread_local: no");
464 /// Add a note that a type does not implement `Copy`
465 pub(super) fn note_type_does_not_implement_copy(
467 err: &mut DiagnosticBuilder<'a>,
472 let message = format!(
473 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
477 if let Some(span) = span {
478 err.span_label(span, message);
484 pub(super) fn borrowed_content_source(
486 deref_base: PlaceRef<'cx, 'tcx>,
487 ) -> BorrowedContentSource<'tcx> {
488 let tcx = self.infcx.tcx;
490 // Look up the provided place and work out the move path index for it,
491 // we'll use this to check whether it was originally from an overloaded
493 match self.move_data.rev_lookup.find(deref_base) {
494 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
495 debug!("borrowed_content_source: mpi={:?}", mpi);
497 for i in &self.move_data.init_path_map[mpi] {
498 let init = &self.move_data.inits[*i];
499 debug!("borrowed_content_source: init={:?}", init);
500 // We're only interested in statements that initialized a value, not the
501 // initializations from arguments.
502 let loc = match init.location {
503 InitLocation::Statement(stmt) => stmt,
507 let bbd = &self.body[loc.block];
508 let is_terminator = bbd.statements.len() == loc.statement_index;
510 "borrowed_content_source: loc={:?} is_terminator={:?}",
516 } else if let Some(Terminator {
517 kind: TerminatorKind::Call {
519 from_hir_call: false,
523 }) = bbd.terminator {
525 = BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
532 // Base is a `static` so won't be from an overloaded operator
536 // If we didn't find an overloaded deref or index, then assume it's a
537 // built in deref and check the type of the base.
538 let base_ty = Place::ty_from(deref_base.base, deref_base.projection, self.body, tcx).ty;
539 if base_ty.is_unsafe_ptr() {
540 BorrowedContentSource::DerefRawPointer
541 } else if base_ty.is_mutable_ptr() {
542 BorrowedContentSource::DerefMutableRef
544 BorrowedContentSource::DerefSharedRef
549 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
550 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
551 /// name where required.
552 pub(super) fn get_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 // We need to add synthesized lifetimes where appropriate. We do
557 // this by hooking into the pretty printer and telling it to label the
558 // lifetimes without names with the value `'0`.
560 ty::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
562 ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
565 ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
569 let _ = ty.print(printer);
573 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
574 /// synthesized lifetime name where required.
575 pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
576 let mut s = String::new();
577 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
579 let region = match ty.sty {
580 ty::Ref(region, _, _) => {
582 ty::RegionKind::ReLateBound(_, br)
583 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
584 printer.region_highlight_mode.highlighting_bound_region(*br, counter)
591 _ => bug!("ty for annotation of borrow region is not a reference"),
594 let _ = region.print(printer);
599 // The span(s) associated to a use of a place.
600 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
601 pub(super) enum UseSpans {
602 // The access is caused by capturing a variable for a closure.
604 // This is true if the captured variable was from a generator.
606 // The span of the args of the closure, including the `move` keyword if
609 // The span of the first use of the captured variable inside the closure.
612 // This access has a single span associated to it: common case.
617 pub(super) fn args_or_use(self) -> Span {
619 UseSpans::ClosureUse {
622 | UseSpans::OtherUse(span) => span,
626 pub(super) fn var_or_use(self) -> Span {
628 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
632 // Add a span label to the arguments of the closure, if it exists.
633 pub(super) fn args_span_label(
635 err: &mut DiagnosticBuilder<'_>,
636 message: impl Into<String>,
638 if let UseSpans::ClosureUse { args_span, .. } = self {
639 err.span_label(args_span, message);
643 // Add a span label to the use of the captured variable, if it exists.
644 pub(super) fn var_span_label(
646 err: &mut DiagnosticBuilder<'_>,
647 message: impl Into<String>,
649 if let UseSpans::ClosureUse { var_span, .. } = self {
650 err.span_label(var_span, message);
654 /// Returns `false` if this place is not used in a closure.
655 pub(super) fn for_closure(&self) -> bool {
657 UseSpans::ClosureUse { is_generator, .. } => !is_generator,
662 /// Returns `false` if this place is not used in a generator.
663 pub(super) fn for_generator(&self) -> bool {
665 UseSpans::ClosureUse { is_generator, .. } => is_generator,
670 /// Describe the span associated with a use of a place.
671 pub(super) fn describe(&self) -> String {
673 UseSpans::ClosureUse { is_generator, .. } => if is_generator {
674 " in generator".to_string()
676 " in closure".to_string()
682 pub(super) fn or_else<F>(self, if_other: F) -> Self
687 closure @ UseSpans::ClosureUse { .. } => closure,
688 UseSpans::OtherUse(_) => if_other(),
693 pub(super) enum BorrowedContentSource<'tcx> {
697 OverloadedDeref(Ty<'tcx>),
698 OverloadedIndex(Ty<'tcx>),
701 impl BorrowedContentSource<'tcx> {
702 pub(super) fn describe_for_unnamed_place(&self) -> String {
704 BorrowedContentSource::DerefRawPointer => format!("a raw pointer"),
705 BorrowedContentSource::DerefSharedRef => format!("a shared reference"),
706 BorrowedContentSource::DerefMutableRef => {
707 format!("a mutable reference")
709 BorrowedContentSource::OverloadedDeref(ty) => {
712 } else if ty.is_arc() {
715 format!("dereference of `{}`", ty)
718 BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
722 pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
724 BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
725 BorrowedContentSource::DerefSharedRef => Some("shared reference"),
726 BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
727 // Overloaded deref and index operators should be evaluated into a
728 // temporary. So we don't need a description here.
729 BorrowedContentSource::OverloadedDeref(_)
730 | BorrowedContentSource::OverloadedIndex(_) => None
734 pub(super) fn describe_for_immutable_place(&self) -> String {
736 BorrowedContentSource::DerefRawPointer => format!("a `*const` pointer"),
737 BorrowedContentSource::DerefSharedRef => format!("a `&` reference"),
738 BorrowedContentSource::DerefMutableRef => {
739 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
741 BorrowedContentSource::OverloadedDeref(ty) => {
744 } else if ty.is_arc() {
747 format!("a dereference of `{}`", ty)
750 BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
754 fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
756 ty::FnDef(def_id, substs) => {
757 let trait_id = tcx.trait_of_item(def_id)?;
759 let lang_items = tcx.lang_items();
760 if Some(trait_id) == lang_items.deref_trait()
761 || Some(trait_id) == lang_items.deref_mut_trait()
763 Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
764 } else if Some(trait_id) == lang_items.index_trait()
765 || Some(trait_id) == lang_items.index_mut_trait()
767 Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
777 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
778 /// Finds the spans associated to a move or copy of move_place at location.
779 pub(super) fn move_spans(
781 moved_place: PlaceRef<'cx, 'tcx>, // Could also be an upvar.
784 use self::UseSpans::*;
786 let stmt = match self.body[location.block].statements.get(location.statement_index) {
788 None => return OtherUse(self.body.source_info(location).span),
791 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
792 if let StatementKind::Assign(
794 box Rvalue::Aggregate(ref kind, ref places)
796 let (def_id, is_generator) = match kind {
797 box AggregateKind::Closure(def_id, _) => (def_id, false),
798 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
799 _ => return OtherUse(stmt.source_info.span),
803 "move_spans: def_id={:?} is_generator={:?} places={:?}",
804 def_id, is_generator, places
806 if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
815 OtherUse(stmt.source_info.span)
818 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
819 /// and its usage of the local assigned at `location`.
820 /// This is done by searching in statements succeeding `location`
821 /// and originating from `maybe_closure_span`.
822 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
823 use self::UseSpans::*;
824 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
826 let target = match self.body[location.block]
828 .get(location.statement_index)
831 kind: StatementKind::Assign(Place {
832 base: PlaceBase::Local(local),
837 _ => return OtherUse(use_span),
840 if self.body.local_kind(target) != LocalKind::Temp {
841 // operands are always temporaries.
842 return OtherUse(use_span);
845 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
846 if let StatementKind::Assign(
847 _, box Rvalue::Aggregate(ref kind, ref places)
849 let (def_id, is_generator) = match kind {
850 box AggregateKind::Closure(def_id, _) => (def_id, false),
851 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
856 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
857 def_id, is_generator, places
859 if let Some((args_span, var_span)) = self.closure_span(
860 *def_id, Place::from(target).as_ref(), places
868 return OtherUse(use_span);
872 if use_span != stmt.source_info.span {
880 /// Finds the span of a captured variable within a closure or generator.
884 target_place: PlaceRef<'cx, 'tcx>,
885 places: &Vec<Operand<'tcx>>,
886 ) -> Option<(Span, Span)> {
888 "closure_span: def_id={:?} target_place={:?} places={:?}",
889 def_id, target_place, places
891 let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id)?;
892 let expr = &self.infcx.tcx.hir().expect_expr(hir_id).node;
893 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
894 if let hir::ExprKind::Closure(
897 for (upvar, place) in self.infcx.tcx.upvars(def_id)?.values().zip(places) {
899 Operand::Copy(place) |
900 Operand::Move(place) if target_place == place.as_ref() => {
901 debug!("closure_span: found captured local {:?}", place);
902 return Some((*args_span, upvar.span));
912 /// Helper to retrieve span(s) of given borrow from the current MIR
914 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
915 let span = self.body.source_info(borrow.reserve_location).span;
916 self.borrow_spans(span, borrow.reserve_location)