1 // Copyright 2018 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.
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.
14 use rustc_data_structures::indexed_vec::Idx;
15 use rustc_errors::DiagnosticBuilder;
18 use borrow_check::MirBorrowckCtxt;
19 use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
20 use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
21 use util::borrowck_errors::{BorrowckErrors, Origin};
23 // Often when desugaring a pattern match we may have many individual moves in
24 // MIR that are all part of one operation from the user's point-of-view. For
29 // would move x from the 0 field of some temporary, and y from the 1 field. We
30 // group such errors together for cleaner error reporting.
32 // Errors are kept separate if they are from places with different parent move
33 // paths. For example, this generates two errors:
35 // let (&x, &y) = (&String::new(), &String::new());
37 enum GroupedMoveError<'tcx> {
38 // Match place can't be moved from
39 // e.g. match x[0] { s => (), } where x: &[String]
42 move_from: Place<'tcx>,
43 kind: IllegalMoveOriginKind<'tcx>,
46 // Part of a pattern can't be moved from,
47 // e.g. match &String::new() { &x => (), }
50 move_from: MovePathIndex,
51 kind: IllegalMoveOriginKind<'tcx>,
54 // Everything that isn't from pattern matching.
57 kind: IllegalMoveOriginKind<'tcx>,
61 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
62 pub(crate) fn report_move_errors(&self, move_errors: Vec<MoveError<'tcx>>) {
63 let grouped_errors = self.group_move_errors(move_errors);
64 for error in grouped_errors {
69 fn group_move_errors(&self, errors: Vec<MoveError<'tcx>>) -> Vec<GroupedMoveError<'tcx>> {
70 let mut grouped_errors = Vec::new();
72 self.append_to_grouped_errors(&mut grouped_errors, error);
77 fn append_to_grouped_errors(
79 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
80 error: MoveError<'tcx>,
83 MoveError::UnionMove { .. } => {
84 unimplemented!("don't know how to report union move errors yet.")
86 MoveError::IllegalMove {
87 cannot_move_out_of: IllegalMoveOrigin { location, kind },
89 let stmt_source_info = self.mir.source_info(location);
90 if let Some(StatementKind::Assign(
92 Rvalue::Use(Operand::Move(move_from)),
93 )) = self.mir.basic_blocks()[location.block]
95 .get(location.statement_index)
96 .map(|stmt| &stmt.kind)
98 let local_decl = &self.mir.local_decls[*local];
99 // opt_match_place is the
100 // match_span is the span of the expression being matched on
101 // match *x.y { ... } match_place is Some(*x.y)
102 // ^^^^ match_span is the span of *x.y
104 // opt_match_place is None for let [mut] x = ... statements,
105 // whether or not the right-hand side is a place expression
106 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
107 opt_match_place: Some((ref opt_match_place, match_span)),
110 }))) = local_decl.is_user_variable
112 // HACK use scopes to determine if this assignment is
113 // the initialization of a variable.
114 // FIXME(matthewjasper) This would probably be more
115 // reliable if it used the ever initialized dataflow
116 // but move errors are currently reported before the
117 // rest of borrowck has run.
120 .is_sub_scope(local_decl.source_info.scope, stmt_source_info.scope)
122 self.append_binding_error(
134 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
135 span: stmt_source_info.span,
142 fn append_binding_error(
144 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
145 kind: IllegalMoveOriginKind<'tcx>,
146 move_from: &Place<'tcx>,
148 match_place: &Option<Place<'tcx>>,
152 "append_to_grouped_errors(match_place={:?}, match_span={:?})",
153 match_place, match_span
156 let from_simple_let = match_place.is_none();
157 let match_place = match_place.as_ref().unwrap_or(move_from);
159 match self.move_data.rev_lookup.find(match_place) {
160 // Error with the match place
161 LookupResult::Parent(_) => {
162 for ge in &mut *grouped_errors {
163 if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
164 if match_span == *span {
165 debug!("appending local({:?}) to list", bind_to);
166 if !binds_to.is_empty() {
167 binds_to.push(bind_to);
173 debug!("found a new move error location");
175 // Don't need to point to x in let x = ... .
176 let binds_to = if from_simple_let {
181 grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
183 move_from: match_place.clone(),
188 // Error with the pattern
189 LookupResult::Exact(_) => {
190 let mpi = match self.move_data.rev_lookup.find(move_from) {
191 LookupResult::Parent(Some(mpi)) => mpi,
192 // move_from should be a projection from match_place.
193 _ => unreachable!("Probably not unreachable..."),
195 for ge in &mut *grouped_errors {
196 if let GroupedMoveError::MovesFromPattern {
198 move_from: other_mpi,
203 if match_span == *span && mpi == *other_mpi {
204 debug!("appending local({:?}) to list", bind_to);
205 binds_to.push(bind_to);
210 debug!("found a new move error location");
211 grouped_errors.push(GroupedMoveError::MovesFromPattern {
215 binds_to: vec![bind_to],
221 fn report(&self, error: GroupedMoveError<'tcx>) {
222 let (mut err, err_span) = {
223 let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
224 GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
225 | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
226 | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
228 let origin = Origin::Mir;
231 IllegalMoveOriginKind::Static => {
232 self.tcx.cannot_move_out_of(span, "static item", origin)
234 IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
235 // Inspect the type of the content behind the
236 // borrow to provide feedback about why this
237 // was a move rather than a copy.
238 let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
240 ty::TyArray(..) | ty::TySlice(..) => self
242 .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
243 ty::TyClosure(def_id, closure_substs)
244 if !self.mir.upvar_decls.is_empty()
247 Place::Projection(ref proj) => {
248 proj.base == Place::Local(Local::new(1))
250 Place::Local(_) | Place::Static(_) => unreachable!(),
254 let closure_kind_ty =
255 closure_substs.closure_kind_ty(def_id, self.tcx);
256 let closure_kind = closure_kind_ty.to_opt_closure_kind();
257 let place_description = match closure_kind {
258 Some(ty::ClosureKind::Fn) => {
259 "captured variable in an `Fn` closure"
261 Some(ty::ClosureKind::FnMut) => {
262 "captured variable in an `FnMut` closure"
264 Some(ty::ClosureKind::FnOnce) => {
265 bug!("closure kind does not match first argument type")
267 None => bug!("closure kind not inferred by borrowck"),
269 self.tcx.cannot_move_out_of(span, place_description, origin)
273 .cannot_move_out_of(span, "borrowed content", origin),
276 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
278 .cannot_move_out_of_interior_of_drop(span, ty, origin)
280 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
282 .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
288 self.add_move_hints(error, &mut err, err_span);
294 error: GroupedMoveError<'tcx>,
295 err: &mut DiagnosticBuilder<'a>,
299 GroupedMoveError::MovesFromMatchPlace {
304 // Ok to suggest a borrow, since the target can't be moved from
306 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
308 Place::Projection(ref proj)
309 if self.suitable_to_remove_deref(proj, &snippet) =>
313 "consider removing this dereference operator",
314 format!("{}", &snippet[1..]),
320 "consider using a reference instead",
321 format!("&{}", snippet),
328 for local in binds_to {
329 let bind_to = &self.mir.local_decls[local];
330 let binding_span = bind_to.source_info.span;
334 "move occurs because {} has type `{}`, \
335 which does not implement the `Copy` trait",
336 bind_to.name.unwrap(),
343 GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
344 // Suggest ref, since there might be a move in
348 for local in binds_to {
349 let bind_to = &self.mir.local_decls[local];
350 let binding_span = bind_to.source_info.span;
352 // Suggest ref mut when the user has already written mut.
353 let ref_kind = match bind_to.mutability {
354 Mutability::Not => "ref",
355 Mutability::Mut => "ref mut",
361 "to prevent move, use ref or ref mut",
362 format!("{} {:?}", ref_kind, name),
368 format!("Local {:?} is not suitable for ref", bind_to),
374 // Nothing to suggest.
375 GroupedMoveError::OtherIllegalMove { .. } => (),
379 fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
380 let is_shared_ref = |ty: ty::Ty| match ty.sty {
381 ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
385 proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
386 Place::Local(local) => {
387 let local_decl = &self.mir.local_decls[local];
388 // If this is a temporary, then this could be from an
389 // overloaded * operator.
390 local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
392 Place::Promoted(_) => true,
393 Place::Static(ref st) => is_shared_ref(st.ty),
394 Place::Projection(ref proj) => match proj.elem {
395 ProjectionElem::Field(_, ty) => is_shared_ref(ty),