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_errors::DiagnosticBuilder;
17 use borrow_check::MirBorrowckCtxt;
18 use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
19 use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
20 use util::borrowck_errors::{BorrowckErrors, Origin};
22 // Often when desugaring a pattern match we may have many individual moves in
23 // MIR that are all part of one operation from the user's point-of-view. For
28 // would move x from the 0 field of some temporary, and y from the 1 field. We
29 // group such errors together for cleaner error reporting.
31 // Errors are kept separate if they are from places with different parent move
32 // paths. For example, this generates two errors:
34 // let (&x, &y) = (&String::new(), &String::new());
36 enum GroupedMoveError<'tcx> {
37 // Match place can't be moved from
38 // e.g. match x[0] { s => (), } where x: &[String]
41 move_from: Place<'tcx>,
42 kind: IllegalMoveOriginKind<'tcx>,
45 // Part of a pattern can't be moved from,
46 // e.g. match &String::new() { &x => (), }
49 move_from: MovePathIndex,
50 kind: IllegalMoveOriginKind<'tcx>,
53 // Everything that isn't from pattern matching.
56 kind: IllegalMoveOriginKind<'tcx>,
60 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
61 pub(crate) fn report_move_errors(&self, move_errors: Vec<MoveError<'tcx>>) {
62 let grouped_errors = self.group_move_errors(move_errors);
63 for error in grouped_errors {
68 fn group_move_errors(&self, errors: Vec<MoveError<'tcx>>) -> Vec<GroupedMoveError<'tcx>> {
69 let mut grouped_errors = Vec::new();
71 self.append_to_grouped_errors(&mut grouped_errors, error);
76 fn append_to_grouped_errors(
78 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
79 error: MoveError<'tcx>,
82 MoveError::UnionMove { .. } => {
83 unimplemented!("don't know how to report union move errors yet.")
85 MoveError::IllegalMove {
86 cannot_move_out_of: IllegalMoveOrigin { location, kind },
88 let stmt_source_info = self.mir.source_info(location);
89 if let Some(StatementKind::Assign(
91 Rvalue::Use(Operand::Move(move_from)),
92 )) = self.mir.basic_blocks()[location.block]
94 .get(location.statement_index)
95 .map(|stmt| &stmt.kind)
97 let local_decl = &self.mir.local_decls[*local];
98 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
99 opt_match_place: Some((ref opt_match_place, match_span)),
102 }))) = local_decl.is_user_variable
104 // opt_match_place is the
105 // match_span is the span of the expression being matched on
106 // match *x.y { ... } match_place is Some(*x.y)
107 // ^^^^ match_span is the span of *x.y
108 // opt_match_place is None for let [mut] x = ... statements,
109 // whether or not the right-hand side is a place expression
111 // HACK use scopes to determine if this assignment is
112 // the initialization of a variable.
113 // FIXME(matthewjasper) This would probably be more
114 // reliable if it used the ever initialized dataflow
115 // but move errors are currently reported before the
116 // rest of borrowck has run.
119 .is_sub_scope(local_decl.source_info.scope, stmt_source_info.scope)
121 self.append_binding_error(
133 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
134 span: stmt_source_info.span,
141 fn append_binding_error(
143 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
144 kind: IllegalMoveOriginKind<'tcx>,
145 move_from: &Place<'tcx>,
147 match_place: &Option<Place<'tcx>>,
151 "append_to_grouped_errors(match_place={:?}, match_span={:?})",
152 match_place, match_span
155 let from_simple_let = match_place.is_none();
156 let match_place = match_place.as_ref().unwrap_or(move_from);
158 match self.move_data.rev_lookup.find(match_place) {
159 // Error with the match place
160 LookupResult::Parent(_) => {
161 for ge in &mut *grouped_errors {
162 if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
163 if match_span == *span {
164 debug!("appending local({:?}) to list", bind_to);
165 if !binds_to.is_empty() {
166 binds_to.push(bind_to);
172 debug!("found a new move error location");
174 // Don't need to point to x in let x = ... .
175 let binds_to = if from_simple_let {
180 grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
182 move_from: match_place.clone(),
187 // Error with the pattern
188 LookupResult::Exact(_) => {
189 let mpi = match self.move_data.rev_lookup.find(move_from) {
190 LookupResult::Parent(Some(mpi)) => mpi,
191 // move_from should be a projection from match_place.
192 _ => unreachable!("Probably not unreachable..."),
194 for ge in &mut *grouped_errors {
195 if let GroupedMoveError::MovesFromPattern {
197 move_from: other_mpi,
202 if match_span == *span && mpi == *other_mpi {
203 debug!("appending local({:?}) to list", bind_to);
204 binds_to.push(bind_to);
209 debug!("found a new move error location");
210 grouped_errors.push(GroupedMoveError::MovesFromPattern {
214 binds_to: vec![bind_to],
220 fn report(&self, error: GroupedMoveError<'tcx>) {
221 let (mut err, err_span) = {
222 let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
223 GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
224 | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
225 | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
227 let origin = Origin::Mir;
230 IllegalMoveOriginKind::Static => {
231 self.tcx.cannot_move_out_of(span, "static item", origin)
233 IllegalMoveOriginKind::BorrowedContent { target_ty: ty } => {
234 // Inspect the type of the content behind the
235 // borrow to provide feedback about why this
236 // was a move rather than a copy.
238 ty::TyArray(..) | ty::TySlice(..) => self
240 .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
243 .cannot_move_out_of(span, "borrowed content", origin),
246 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
248 .cannot_move_out_of_interior_of_drop(span, ty, origin)
250 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
252 .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
258 self.add_move_hints(error, &mut err, err_span);
264 error: GroupedMoveError<'tcx>,
265 err: &mut DiagnosticBuilder<'a>,
269 GroupedMoveError::MovesFromMatchPlace {
274 // Ok to suggest a borrow, since the target can't be moved from
276 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
278 Place::Projection(ref proj)
279 if self.suitable_to_remove_deref(proj, &snippet) =>
283 "consider removing this dereference operator",
284 format!("{}", &snippet[1..]),
290 "consider using a reference instead",
291 format!("&{}", snippet),
298 for local in binds_to {
299 let bind_to = &self.mir.local_decls[local];
300 let binding_span = bind_to.source_info.span;
304 "move occurs because {} has type `{}`, \
305 which does not implement the `Copy` trait",
306 bind_to.name.unwrap(),
313 GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
314 // Suggest ref, since there might be a move in
318 for local in binds_to {
319 let bind_to = &self.mir.local_decls[local];
320 let binding_span = bind_to.source_info.span;
322 // Suggest ref mut when the user has already written mut.
323 let ref_kind = match bind_to.mutability {
324 Mutability::Not => "ref",
325 Mutability::Mut => "ref mut",
331 "to prevent move, use ref or ref mut",
332 format!("{} {:?}", ref_kind, name),
338 format!("Local {:?} is not suitable for ref", bind_to),
344 // Nothing to suggest.
345 GroupedMoveError::OtherIllegalMove { .. } => (),
349 fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
350 let is_shared_ref = |ty: ty::Ty| match ty.sty {
351 ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
355 proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
356 Place::Local(local) => {
357 let local_decl = &self.mir.local_decls[local];
358 // If this is a temporary, then this could be from an
359 // overloaded * operator.
360 local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
362 Place::Static(ref st) => is_shared_ref(st.ty),
363 Place::Projection(ref proj) => match proj.elem {
364 ProjectionElem::Field(_, ty) => is_shared_ref(ty),