]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs
e81a012cef59ab8cefede0ead12c2de4627f5f17
[rust.git] / src / librustc_mir / borrow_check / diagnostics / mutability_errors.rs
1 use rustc::mir::{self, ClearCrossCrate, Local, LocalInfo, Location, ReadOnlyBodyAndCache};
2 use rustc::mir::{Mutability, Place, PlaceBase, PlaceRef, ProjectionElem};
3 use rustc::ty::{self, Ty, TyCtxt};
4 use rustc_hir as hir;
5 use rustc_hir::Node;
6 use rustc_index::vec::Idx;
7 use rustc_span::symbol::kw;
8 use rustc_span::Span;
9
10 use crate::borrow_check::diagnostics::BorrowedContentSource;
11 use crate::borrow_check::MirBorrowckCtxt;
12 use crate::util::collect_writes::FindAssignments;
13 use rustc_errors::Applicability;
14
15 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
16 pub(crate) enum AccessKind {
17     MutableBorrow,
18     Mutate,
19 }
20
21 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
22     pub(crate) fn report_mutability_error(
23         &mut self,
24         access_place: &Place<'tcx>,
25         span: Span,
26         the_place_err: PlaceRef<'cx, 'tcx>,
27         error_access: AccessKind,
28         location: Location,
29     ) {
30         debug!(
31             "report_mutability_error(\
32                 access_place={:?}, span={:?}, the_place_err={:?}, error_access={:?}, location={:?},\
33             )",
34             access_place, span, the_place_err, error_access, location,
35         );
36
37         let mut err;
38         let item_msg;
39         let reason;
40         let mut opt_source = None;
41         let access_place_desc = self.describe_place(access_place.as_ref());
42         debug!("report_mutability_error: access_place_desc={:?}", access_place_desc);
43
44         match the_place_err {
45             PlaceRef { base: PlaceBase::Local(local), projection: [] } => {
46                 item_msg = format!("`{}`", access_place_desc.unwrap());
47                 if access_place.as_local().is_some() {
48                     reason = ", as it is not declared as mutable".to_string();
49                 } else {
50                     let name = self.local_names[*local].expect("immutable unnamed local");
51                     reason = format!(", as `{}` is not declared as mutable", name);
52                 }
53             }
54
55             PlaceRef {
56                 base: _,
57                 projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
58             } => {
59                 debug_assert!(is_closure_or_generator(
60                     Place::ty_from(&the_place_err.base, proj_base, *self.body, self.infcx.tcx).ty
61                 ));
62
63                 item_msg = format!("`{}`", access_place_desc.unwrap());
64                 if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
65                     reason = ", as it is not declared as mutable".to_string();
66                 } else {
67                     let name = self.upvars[upvar_index.index()].name;
68                     reason = format!(", as `{}` is not declared as mutable", name);
69                 }
70             }
71
72             PlaceRef { base: &PlaceBase::Local(local), projection: [ProjectionElem::Deref] }
73                 if self.body.local_decls[local].is_ref_for_guard() =>
74             {
75                 item_msg = format!("`{}`", access_place_desc.unwrap());
76                 reason = ", as it is immutable for the pattern guard".to_string();
77             }
78             PlaceRef { base: &PlaceBase::Local(local), projection: [ProjectionElem::Deref] }
79                 if self.body.local_decls[local].is_ref_to_static() =>
80             {
81                 if access_place.projection.len() == 1 {
82                     item_msg = format!("immutable static item `{}`", access_place_desc.unwrap());
83                     reason = String::new();
84                 } else {
85                     item_msg = format!("`{}`", access_place_desc.unwrap());
86                     let local_info = &self.body.local_decls[local].local_info;
87                     if let LocalInfo::StaticRef { def_id, .. } = *local_info {
88                         let static_name = &self.infcx.tcx.item_name(def_id);
89                         reason = format!(", as `{}` is an immutable static item", static_name);
90                     } else {
91                         bug!("is_ref_to_static return true, but not ref to static?");
92                     }
93                 }
94             }
95             PlaceRef { base: _, projection: [proj_base @ .., ProjectionElem::Deref] } => {
96                 if the_place_err.base == &PlaceBase::Local(Local::new(1))
97                     && proj_base.is_empty()
98                     && !self.upvars.is_empty()
99                 {
100                     item_msg = format!("`{}`", access_place_desc.unwrap());
101                     debug_assert!(self.body.local_decls[Local::new(1)].ty.is_region_ptr());
102                     debug_assert!(is_closure_or_generator(
103                         Place::ty_from(
104                             the_place_err.base,
105                             the_place_err.projection,
106                             *self.body,
107                             self.infcx.tcx
108                         )
109                         .ty
110                     ));
111
112                     reason = if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
113                         ", as it is a captured variable in a `Fn` closure".to_string()
114                     } else {
115                         ", as `Fn` closures cannot mutate their captured variables".to_string()
116                     }
117                 } else {
118                     let source = self.borrowed_content_source(PlaceRef {
119                         base: the_place_err.base,
120                         projection: proj_base,
121                     });
122                     let pointer_type = source.describe_for_immutable_place();
123                     opt_source = Some(source);
124                     if let Some(desc) = access_place_desc {
125                         item_msg = format!("`{}`", desc);
126                         reason = match error_access {
127                             AccessKind::Mutate => format!(" which is behind {}", pointer_type),
128                             AccessKind::MutableBorrow => {
129                                 format!(", as it is behind {}", pointer_type)
130                             }
131                         }
132                     } else {
133                         item_msg = format!("data in {}", pointer_type);
134                         reason = String::new();
135                     }
136                 }
137             }
138
139             PlaceRef { base: _, projection: [.., ProjectionElem::Index(_)] }
140             | PlaceRef { base: _, projection: [.., ProjectionElem::ConstantIndex { .. }] }
141             | PlaceRef { base: _, projection: [.., ProjectionElem::Subslice { .. }] }
142             | PlaceRef { base: _, projection: [.., ProjectionElem::Downcast(..)] } => {
143                 bug!("Unexpected immutable place.")
144             }
145         }
146
147         debug!("report_mutability_error: item_msg={:?}, reason={:?}", item_msg, reason);
148
149         // `act` and `acted_on` are strings that let us abstract over
150         // the verbs used in some diagnostic messages.
151         let act;
152         let acted_on;
153
154         let span = match error_access {
155             AccessKind::Mutate => {
156                 err = self.cannot_assign(span, &(item_msg + &reason));
157                 act = "assign";
158                 acted_on = "written";
159                 span
160             }
161             AccessKind::MutableBorrow => {
162                 act = "borrow as mutable";
163                 acted_on = "borrowed as mutable";
164
165                 let borrow_spans = self.borrow_spans(span, location);
166                 let borrow_span = borrow_spans.args_or_use();
167                 err = self.cannot_borrow_path_as_mutable_because(borrow_span, &item_msg, &reason);
168                 borrow_spans.var_span_label(
169                     &mut err,
170                     format!(
171                         "mutable borrow occurs due to use of `{}` in closure",
172                         // always Some() if the message is printed.
173                         self.describe_place(access_place.as_ref()).unwrap_or_default(),
174                     ),
175                 );
176                 borrow_span
177             }
178         };
179
180         debug!("report_mutability_error: act={:?}, acted_on={:?}", act, acted_on);
181
182         match the_place_err {
183             // Suggest making an existing shared borrow in a struct definition a mutable borrow.
184             //
185             // This is applicable when we have a deref of a field access to a deref of a local -
186             // something like `*((*_1).0`. The local that we get will be a reference to the
187             // struct we've got a field access of (it must be a reference since there's a deref
188             // after the field access).
189             PlaceRef {
190                 base,
191                 projection:
192                     [proj_base @ .., ProjectionElem::Deref, ProjectionElem::Field(field, _), ProjectionElem::Deref],
193             } => {
194                 err.span_label(span, format!("cannot {ACT}", ACT = act));
195
196                 if let Some((span, message)) = annotate_struct_field(
197                     self.infcx.tcx,
198                     Place::ty_from(base, proj_base, *self.body, self.infcx.tcx).ty,
199                     field,
200                 ) {
201                     err.span_suggestion(
202                         span,
203                         "consider changing this to be mutable",
204                         message,
205                         Applicability::MaybeIncorrect,
206                     );
207                 }
208             }
209
210             // Suggest removing a `&mut` from the use of a mutable reference.
211             PlaceRef { base: PlaceBase::Local(local), projection: [] }
212                 if {
213                     self.body
214                         .local_decls
215                         .get(*local)
216                         .map(|local_decl| {
217                             if let LocalInfo::User(ClearCrossCrate::Set(
218                                 mir::BindingForm::ImplicitSelf(kind),
219                             )) = local_decl.local_info
220                             {
221                                 // Check if the user variable is a `&mut self` and we can therefore
222                                 // suggest removing the `&mut`.
223                                 //
224                                 // Deliberately fall into this case for all implicit self types,
225                                 // so that we don't fall in to the next case with them.
226                                 kind == mir::ImplicitSelfKind::MutRef
227                             } else if Some(kw::SelfLower) == self.local_names[*local] {
228                                 // Otherwise, check if the name is the self kewyord - in which case
229                                 // we have an explicit self. Do the same thing in this case and check
230                                 // for a `self: &mut Self` to suggest removing the `&mut`.
231                                 if let ty::Ref(_, _, hir::Mutability::Mut) = local_decl.ty.kind {
232                                     true
233                                 } else {
234                                     false
235                                 }
236                             } else {
237                                 false
238                             }
239                         })
240                         .unwrap_or(false)
241                 } =>
242             {
243                 err.span_label(span, format!("cannot {ACT}", ACT = act));
244                 err.span_label(span, "try removing `&mut` here");
245             }
246
247             // We want to suggest users use `let mut` for local (user
248             // variable) mutations...
249             PlaceRef { base: PlaceBase::Local(local), projection: [] }
250                 if self.body.local_decls[*local].can_be_made_mutable() =>
251             {
252                 // ... but it doesn't make sense to suggest it on
253                 // variables that are `ref x`, `ref mut x`, `&self`,
254                 // or `&mut self` (such variables are simply not
255                 // mutable).
256                 let local_decl = &self.body.local_decls[*local];
257                 assert_eq!(local_decl.mutability, Mutability::Not);
258
259                 err.span_label(span, format!("cannot {ACT}", ACT = act));
260                 err.span_suggestion(
261                     local_decl.source_info.span,
262                     "consider changing this to be mutable",
263                     format!("mut {}", self.local_names[*local].unwrap()),
264                     Applicability::MachineApplicable,
265                 );
266             }
267
268             // Also suggest adding mut for upvars
269             PlaceRef {
270                 base,
271                 projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
272             } => {
273                 debug_assert!(is_closure_or_generator(
274                     Place::ty_from(base, proj_base, *self.body, self.infcx.tcx).ty
275                 ));
276
277                 err.span_label(span, format!("cannot {ACT}", ACT = act));
278
279                 let upvar_hir_id = self.upvars[upvar_index.index()].var_hir_id;
280                 if let Some(Node::Binding(pat)) = self.infcx.tcx.hir().find(upvar_hir_id) {
281                     if let hir::PatKind::Binding(
282                         hir::BindingAnnotation::Unannotated,
283                         _,
284                         upvar_ident,
285                         _,
286                     ) = pat.kind
287                     {
288                         err.span_suggestion(
289                             upvar_ident.span,
290                             "consider changing this to be mutable",
291                             format!("mut {}", upvar_ident.name),
292                             Applicability::MachineApplicable,
293                         );
294                     }
295                 }
296             }
297
298             // complete hack to approximate old AST-borrowck
299             // diagnostic: if the span starts with a mutable borrow of
300             // a local variable, then just suggest the user remove it.
301             PlaceRef { base: PlaceBase::Local(_), projection: [] }
302                 if {
303                     if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
304                         snippet.starts_with("&mut ")
305                     } else {
306                         false
307                     }
308                 } =>
309             {
310                 err.span_label(span, format!("cannot {ACT}", ACT = act));
311                 err.span_label(span, "try removing `&mut` here");
312             }
313
314             PlaceRef { base: PlaceBase::Local(local), projection: [ProjectionElem::Deref] }
315                 if self.body.local_decls[*local].is_ref_for_guard() =>
316             {
317                 err.span_label(span, format!("cannot {ACT}", ACT = act));
318                 err.note(
319                     "variables bound in patterns are immutable until the end of the pattern guard",
320                 );
321             }
322
323             // We want to point out when a `&` can be readily replaced
324             // with an `&mut`.
325             //
326             // FIXME: can this case be generalized to work for an
327             // arbitrary base for the projection?
328             PlaceRef { base: PlaceBase::Local(local), projection: [ProjectionElem::Deref] }
329                 if self.body.local_decls[*local].is_user_variable() =>
330             {
331                 let local_decl = &self.body.local_decls[*local];
332                 let suggestion = match local_decl.local_info {
333                     LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::ImplicitSelf(_))) => {
334                         Some(suggest_ampmut_self(self.infcx.tcx, local_decl))
335                     }
336
337                     LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::Var(
338                         mir::VarBindingForm {
339                             binding_mode: ty::BindingMode::BindByValue(_),
340                             opt_ty_info,
341                             ..
342                         },
343                     ))) => Some(suggest_ampmut(
344                         self.infcx.tcx,
345                         self.body,
346                         *local,
347                         local_decl,
348                         opt_ty_info,
349                     )),
350
351                     LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::Var(
352                         mir::VarBindingForm {
353                             binding_mode: ty::BindingMode::BindByReference(_),
354                             ..
355                         },
356                     ))) => {
357                         let pattern_span = local_decl.source_info.span;
358                         suggest_ref_mut(self.infcx.tcx, pattern_span)
359                             .map(|replacement| (pattern_span, replacement))
360                     }
361
362                     LocalInfo::User(ClearCrossCrate::Clear) => bug!("saw cleared local state"),
363
364                     _ => unreachable!(),
365                 };
366
367                 let (pointer_sigil, pointer_desc) = if local_decl.ty.is_region_ptr() {
368                     ("&", "reference")
369                 } else {
370                     ("*const", "pointer")
371                 };
372
373                 if let Some((err_help_span, suggested_code)) = suggestion {
374                     err.span_suggestion(
375                         err_help_span,
376                         &format!("consider changing this to be a mutable {}", pointer_desc),
377                         suggested_code,
378                         Applicability::MachineApplicable,
379                     );
380                 }
381
382                 match self.local_names[*local] {
383                     Some(name) if !local_decl.from_compiler_desugaring() => {
384                         err.span_label(
385                             span,
386                             format!(
387                                 "`{NAME}` is a `{SIGIL}` {DESC}, \
388                                 so the data it refers to cannot be {ACTED_ON}",
389                                 NAME = name,
390                                 SIGIL = pointer_sigil,
391                                 DESC = pointer_desc,
392                                 ACTED_ON = acted_on
393                             ),
394                         );
395                     }
396                     _ => {
397                         err.span_label(
398                             span,
399                             format!(
400                                 "cannot {ACT} through `{SIGIL}` {DESC}",
401                                 ACT = act,
402                                 SIGIL = pointer_sigil,
403                                 DESC = pointer_desc
404                             ),
405                         );
406                     }
407                 }
408             }
409
410             PlaceRef {
411                 base,
412                 projection: [ProjectionElem::Deref],
413                 // FIXME document what is this 1 magic number about
414             } if *base == PlaceBase::Local(Local::new(1)) && !self.upvars.is_empty() => {
415                 err.span_label(span, format!("cannot {ACT}", ACT = act));
416                 err.span_help(
417                     self.body.span,
418                     "consider changing this to accept closures that implement `FnMut`",
419                 );
420             }
421
422             PlaceRef { base: _, projection: [.., ProjectionElem::Deref] } => {
423                 err.span_label(span, format!("cannot {ACT}", ACT = act));
424
425                 match opt_source {
426                     Some(BorrowedContentSource::OverloadedDeref(ty)) => {
427                         err.help(&format!(
428                             "trait `DerefMut` is required to modify through a dereference, \
429                                 but it is not implemented for `{}`",
430                             ty,
431                         ));
432                     }
433                     Some(BorrowedContentSource::OverloadedIndex(ty)) => {
434                         err.help(&format!(
435                             "trait `IndexMut` is required to modify indexed content, \
436                                 but it is not implemented for `{}`",
437                             ty,
438                         ));
439                     }
440                     _ => (),
441                 }
442             }
443
444             _ => {
445                 err.span_label(span, format!("cannot {ACT}", ACT = act));
446             }
447         }
448
449         err.buffer(&mut self.errors_buffer);
450     }
451 }
452
453 fn suggest_ampmut_self<'tcx>(
454     tcx: TyCtxt<'tcx>,
455     local_decl: &mir::LocalDecl<'tcx>,
456 ) -> (Span, String) {
457     let sp = local_decl.source_info.span;
458     (
459         sp,
460         match tcx.sess.source_map().span_to_snippet(sp) {
461             Ok(snippet) => {
462                 let lt_pos = snippet.find('\'');
463                 if let Some(lt_pos) = lt_pos {
464                     format!("&{}mut self", &snippet[lt_pos..snippet.len() - 4])
465                 } else {
466                     "&mut self".to_string()
467                 }
468             }
469             _ => "&mut self".to_string(),
470         },
471     )
472 }
473
474 // When we want to suggest a user change a local variable to be a `&mut`, there
475 // are three potential "obvious" things to highlight:
476 //
477 // let ident [: Type] [= RightHandSideExpression];
478 //     ^^^^^    ^^^^     ^^^^^^^^^^^^^^^^^^^^^^^
479 //     (1.)     (2.)              (3.)
480 //
481 // We can always fallback on highlighting the first. But chances are good that
482 // the user experience will be better if we highlight one of the others if possible;
483 // for example, if the RHS is present and the Type is not, then the type is going to
484 // be inferred *from* the RHS, which means we should highlight that (and suggest
485 // that they borrow the RHS mutably).
486 //
487 // This implementation attempts to emulate AST-borrowck prioritization
488 // by trying (3.), then (2.) and finally falling back on (1.).
489 fn suggest_ampmut<'tcx>(
490     tcx: TyCtxt<'tcx>,
491     body: ReadOnlyBodyAndCache<'_, 'tcx>,
492     local: Local,
493     local_decl: &mir::LocalDecl<'tcx>,
494     opt_ty_info: Option<Span>,
495 ) -> (Span, String) {
496     let locations = body.find_assignments(local);
497     if !locations.is_empty() {
498         let assignment_rhs_span = body.source_info(locations[0]).span;
499         if let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span) {
500             if let (true, Some(ws_pos)) =
501                 (src.starts_with("&'"), src.find(|c: char| -> bool { c.is_whitespace() }))
502             {
503                 let lt_name = &src[1..ws_pos];
504                 let ty = &src[ws_pos..];
505                 return (assignment_rhs_span, format!("&{} mut {}", lt_name, ty));
506             } else if src.starts_with('&') {
507                 let borrowed_expr = &src[1..];
508                 return (assignment_rhs_span, format!("&mut {}", borrowed_expr));
509             }
510         }
511     }
512
513     let highlight_span = match opt_ty_info {
514         // if this is a variable binding with an explicit type,
515         // try to highlight that for the suggestion.
516         Some(ty_span) => ty_span,
517
518         // otherwise, just highlight the span associated with
519         // the (MIR) LocalDecl.
520         None => local_decl.source_info.span,
521     };
522
523     if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span) {
524         if let (true, Some(ws_pos)) =
525             (src.starts_with("&'"), src.find(|c: char| -> bool { c.is_whitespace() }))
526         {
527             let lt_name = &src[1..ws_pos];
528             let ty = &src[ws_pos..];
529             return (highlight_span, format!("&{} mut{}", lt_name, ty));
530         }
531     }
532
533     let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
534     assert_eq!(ty_mut.mutbl, hir::Mutability::Not);
535     (
536         highlight_span,
537         if local_decl.ty.is_region_ptr() {
538             format!("&mut {}", ty_mut.ty)
539         } else {
540             format!("*mut {}", ty_mut.ty)
541         },
542     )
543 }
544
545 fn is_closure_or_generator(ty: Ty<'_>) -> bool {
546     ty.is_closure() || ty.is_generator()
547 }
548
549 /// Adds a suggestion to a struct definition given a field access to a local.
550 /// This function expects the local to be a reference to a struct in order to produce a suggestion.
551 ///
552 /// ```text
553 /// LL |     s: &'a String
554 ///    |        ---------- use `&'a mut String` here to make mutable
555 /// ```
556 fn annotate_struct_field(
557     tcx: TyCtxt<'tcx>,
558     ty: Ty<'tcx>,
559     field: &mir::Field,
560 ) -> Option<(Span, String)> {
561     // Expect our local to be a reference to a struct of some kind.
562     if let ty::Ref(_, ty, _) = ty.kind {
563         if let ty::Adt(def, _) = ty.kind {
564             let field = def.all_fields().nth(field.index())?;
565             // Use the HIR types to construct the diagnostic message.
566             let hir_id = tcx.hir().as_local_hir_id(field.did)?;
567             let node = tcx.hir().find(hir_id)?;
568             // Now we're dealing with the actual struct that we're going to suggest a change to,
569             // we can expect a field that is an immutable reference to a type.
570             if let hir::Node::Field(field) = node {
571                 if let hir::TyKind::Rptr(
572                     lifetime,
573                     hir::MutTy { mutbl: hir::Mutability::Not, ref ty },
574                 ) = field.ty.kind
575                 {
576                     // Get the snippets in two parts - the named lifetime (if there is one) and
577                     // type being referenced, that way we can reconstruct the snippet without loss
578                     // of detail.
579                     let type_snippet = tcx.sess.source_map().span_to_snippet(ty.span).ok()?;
580                     let lifetime_snippet = if !lifetime.is_elided() {
581                         format!("{} ", tcx.sess.source_map().span_to_snippet(lifetime.span).ok()?)
582                     } else {
583                         String::new()
584                     };
585
586                     return Some((
587                         field.ty.span,
588                         format!("&{}mut {}", lifetime_snippet, &*type_snippet,),
589                     ));
590                 }
591             }
592         }
593     }
594
595     None
596 }
597
598 /// If possible, suggest replacing `ref` with `ref mut`.
599 fn suggest_ref_mut(tcx: TyCtxt<'_>, binding_span: Span) -> Option<String> {
600     let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).ok()?;
601     if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(rustc_lexer::is_whitespace) {
602         let replacement = format!("ref mut{}", &hi_src["ref".len()..]);
603         Some(replacement)
604     } else {
605         None
606     }
607 }