1 use std::fmt::{self, Display};
2 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
3 use crate::borrow_check::nll::universal_regions::DefiningTy;
4 use crate::borrow_check::nll::ToRegionVid;
5 use crate::borrow_check::Upvar;
7 use rustc::hir::def::{Res, DefKind};
8 use rustc::hir::def_id::DefId;
9 use rustc::infer::InferCtxt;
11 use rustc::ty::subst::{SubstsRef, UnpackedKind};
12 use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt};
13 use rustc::ty::print::RegionHighlightMode;
14 use rustc_errors::DiagnosticBuilder;
15 use syntax::ast::Name;
16 use syntax::symbol::keywords;
18 use syntax_pos::symbol::InternedString;
21 crate struct RegionName {
22 crate name: InternedString,
23 crate source: RegionNameSource,
27 crate enum RegionNameSource {
28 NamedEarlyBoundRegion(Span),
29 NamedFreeRegion(Span),
31 SynthesizedFreeEnvRegion(Span, String),
32 CannotMatchHirTy(Span, String),
34 MatchedAdtAndSegment(Span),
35 AnonRegionFromUpvar(Span, String),
36 AnonRegionFromOutput(Span, String, String),
37 AnonRegionFromYieldTy(Span, String),
42 crate fn was_named(&self) -> bool {
44 RegionNameSource::NamedEarlyBoundRegion(..) |
45 RegionNameSource::NamedFreeRegion(..) |
46 RegionNameSource::Static => true,
47 RegionNameSource::SynthesizedFreeEnvRegion(..) |
48 RegionNameSource::CannotMatchHirTy(..) |
49 RegionNameSource::MatchedHirTy(..) |
50 RegionNameSource::MatchedAdtAndSegment(..) |
51 RegionNameSource::AnonRegionFromUpvar(..) |
52 RegionNameSource::AnonRegionFromOutput(..) |
53 RegionNameSource::AnonRegionFromYieldTy(..) => false,
58 crate fn was_synthesized(&self) -> bool {
63 crate fn name(&self) -> &InternedString {
67 crate fn highlight_region_name(
69 diag: &mut DiagnosticBuilder<'_>
72 RegionNameSource::NamedFreeRegion(span) |
73 RegionNameSource::NamedEarlyBoundRegion(span) => {
76 format!("lifetime `{}` defined here", self),
79 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
82 format!("lifetime `{}` represents this closure's body", self),
86 RegionNameSource::CannotMatchHirTy(span, type_name) => {
87 diag.span_label(*span, format!("has type `{}`", type_name));
89 RegionNameSource::MatchedHirTy(span) => {
92 format!("let's call the lifetime of this reference `{}`", self),
95 RegionNameSource::MatchedAdtAndSegment(span) => {
96 diag.span_label(*span, format!("let's call this `{}`", self));
98 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
101 format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
104 RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
107 format!("return type{} is {}", mir_description, type_name),
110 RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
113 format!("yield type is {}", type_name),
116 RegionNameSource::Static => {},
121 impl Display for RegionName {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 write!(f, "{}", self.name)
127 impl<'tcx> RegionInferenceContext<'tcx> {
128 /// Maps from an internal MIR region vid to something that we can
129 /// report to the user. In some cases, the region vids will map
130 /// directly to lifetimes that the user has a name for (e.g.,
131 /// `'static`). But frequently they will not, in which case we
132 /// have to find some way to identify the lifetime to the user. To
133 /// that end, this function takes a "diagnostic" so that it can
134 /// create auxiliary notes as needed.
136 /// Example (function arguments):
138 /// Suppose we are trying to give a name to the lifetime of the
142 /// fn foo(x: &u32) { .. }
145 /// This function would create a label like this:
148 /// | fn foo(x: &u32) { .. }
149 /// ------- fully elaborated type of `x` is `&'1 u32`
152 /// and then return the name `'1` for us to use.
153 crate fn give_region_a_name(
155 infcx: &InferCtxt<'_, '_, 'tcx>,
161 ) -> Option<RegionName> {
162 debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
164 assert!(self.universal_regions.is_universal_region(fr));
166 let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
168 self.give_name_if_anonymous_region_appears_in_arguments(
169 infcx, mir, mir_def_id, fr, counter,
173 self.give_name_if_anonymous_region_appears_in_upvars(
174 infcx.tcx, upvars, fr, counter,
178 self.give_name_if_anonymous_region_appears_in_output(
179 infcx, mir, mir_def_id, fr, counter,
183 self.give_name_if_anonymous_region_appears_in_yield_ty(
184 infcx, mir, mir_def_id, fr, counter,
188 debug!("give_region_a_name: gave name {:?}", value);
192 /// Checks for the case where `fr` maps to something that the
193 /// *user* has a name for. In that case, we'll be able to map
194 /// `fr` to a `Region<'tcx>`, and that region will be one of
196 fn give_name_from_error_region(
198 tcx: TyCtxt<'_, '_, 'tcx>,
202 ) -> Option<RegionName> {
203 let error_region = self.to_error_region(fr)?;
205 debug!("give_region_a_name: error_region = {:?}", error_region);
207 ty::ReEarlyBound(ebr) => {
209 let span = self.get_named_span(tcx, error_region, &ebr.name);
212 source: RegionNameSource::NamedEarlyBoundRegion(span)
219 ty::ReStatic => Some(RegionName {
220 name: keywords::StaticLifetime.name().as_interned_str(),
221 source: RegionNameSource::Static
224 ty::ReFree(free_region) => match free_region.bound_region {
225 ty::BoundRegion::BrNamed(_, name) => {
226 let span = self.get_named_span(tcx, error_region, &name);
229 source: RegionNameSource::NamedFreeRegion(span),
233 ty::BoundRegion::BrEnv => {
234 let mir_node_id = tcx.hir()
235 .as_local_node_id(mir_def_id)
236 .expect("non-local mir");
237 let def_ty = self.universal_regions.defining_ty;
239 if let DefiningTy::Closure(def_id, substs) = def_ty {
240 let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
241 tcx.hir().expect_expr(mir_node_id).node
245 bug!("Closure is not defined by a closure expr");
247 let region_name = self.synthesize_region_name(counter);
249 let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
250 let note = match closure_kind_ty.to_opt_closure_kind() {
251 Some(ty::ClosureKind::Fn) => {
252 "closure implements `Fn`, so references to captured variables \
253 can't escape the closure"
255 Some(ty::ClosureKind::FnMut) => {
256 "closure implements `FnMut`, so references to captured variables \
257 can't escape the closure"
259 Some(ty::ClosureKind::FnOnce) => {
260 bug!("BrEnv in a `FnOnce` closure");
262 None => bug!("Closure kind not inferred in borrow check"),
267 source: RegionNameSource::SynthesizedFreeEnvRegion(
273 // Can't have BrEnv in functions, constants or generators.
274 bug!("BrEnv outside of closure.");
278 ty::BoundRegion::BrAnon(_) | ty::BoundRegion::BrFresh(_) => None,
284 | ty::RePlaceholder(..)
287 | ty::ReClosureBound(..) => None,
291 /// Gets a span of a named region to provide context for error messages that
292 /// mention that span, for example:
296 /// | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
297 /// | -- -- lifetime `'b` defined here
299 /// | lifetime `'a` defined here
301 /// | with_signature(cell, t, |cell, t| require(cell, t));
302 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
307 tcx: TyCtxt<'_, '_, 'tcx>,
308 error_region: &RegionKind,
309 name: &InternedString,
311 let scope = error_region.free_region_binding_scope(tcx);
312 let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
314 let span = tcx.sess.source_map().def_span(tcx.hir().span_by_hir_id(node));
315 if let Some(param) = tcx.hir()
317 .and_then(|generics| generics.get_named(name))
325 /// Finds an argument that contains `fr` and label it with a fully
326 /// elaborated type, returning something like `'1`. Result looks
330 /// | fn foo(x: &u32) { .. }
331 /// ------- fully elaborated type of `x` is `&'1 u32`
333 fn give_name_if_anonymous_region_appears_in_arguments(
335 infcx: &InferCtxt<'_, '_, 'tcx>,
340 ) -> Option<RegionName> {
341 let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
342 let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
345 self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
346 if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
355 return Some(region_name);
358 self.give_name_if_we_cannot_match_hir_ty(infcx, mir, fr, arg_ty, counter)
361 fn give_name_if_we_can_match_hir_ty_from_argument(
363 infcx: &InferCtxt<'_, '_, 'tcx>,
366 needle_fr: RegionVid,
367 argument_ty: Ty<'tcx>,
368 argument_index: usize,
370 ) -> Option<RegionName> {
371 let mir_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?;
372 let fn_decl = infcx.tcx.hir().fn_decl(mir_node_id)?;
373 let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
374 match argument_hir_ty.node {
375 // This indicates a variable with no type annotation, like
376 // `|x|`... in that case, we can't highlight the type but
377 // must highlight the variable.
378 hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
386 _ => self.give_name_if_we_can_match_hir_ty(
396 /// Attempts to highlight the specific part of a type in an argument
397 /// that has no type annotation.
398 /// For example, we might produce an annotation like this:
404 /// | | has type `&'1 u32`
405 /// | has type `&'2 u32`
407 fn give_name_if_we_cannot_match_hir_ty(
409 infcx: &InferCtxt<'_, '_, 'tcx>,
411 needle_fr: RegionVid,
412 argument_ty: Ty<'tcx>,
414 ) -> Option<RegionName> {
415 let mut highlight = RegionHighlightMode::default();
416 highlight.highlighting_region_vid(needle_fr, *counter);
417 let type_name = infcx.extract_type_name(&argument_ty, Some(highlight));
420 "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
423 let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
424 // Only add a label if we can confirm that a region was labelled.
425 let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
426 let (_, span) = self.get_argument_name_and_span_for_region(mir, argument_index);
429 // This counter value will already have been used, so this function will increment
430 // it so the next value will be used next and return the region name that would
432 name: self.synthesize_region_name(counter),
433 source: RegionNameSource::CannotMatchHirTy(span, type_name),
442 /// Attempts to highlight the specific part of a type annotation
443 /// that contains the anonymous reference we want to give a name
444 /// to. For example, we might produce an annotation like this:
447 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
448 /// | - let's call the lifetime of this reference `'1`
451 /// the way this works is that we match up `argument_ty`, which is
452 /// a `Ty<'tcx>` (the internal form of the type) with
453 /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
454 /// annotation). We are descending through the types stepwise,
455 /// looking in to find the region `needle_fr` in the internal
456 /// type. Once we find that, we can use the span of the `hir::Ty`
457 /// to add the highlight.
459 /// This is a somewhat imperfect process, so long the way we also
460 /// keep track of the **closest** type we've found. If we fail to
461 /// find the exact `&` or `'_` to highlight, then we may fall back
462 /// to highlighting that closest type instead.
463 fn give_name_if_we_can_match_hir_ty(
465 tcx: TyCtxt<'_, '_, 'tcx>,
466 needle_fr: RegionVid,
467 argument_ty: Ty<'tcx>,
468 argument_hir_ty: &hir::Ty,
470 ) -> Option<RegionName> {
471 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
472 &mut vec![(argument_ty, argument_hir_ty)];
474 while let Some((ty, hir_ty)) = search_stack.pop() {
475 match (&ty.sty, &hir_ty.node) {
476 // Check if the `argument_ty` is `&'X ..` where `'X`
477 // is the region we are looking for -- if so, and we have a `&T`
478 // on the RHS, then we want to highlight the `&` like so:
481 // - let's call the lifetime of this reference `'1`
483 ty::Ref(region, referent_ty, _),
484 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
486 if region.to_region_vid() == needle_fr {
487 let region_name = self.synthesize_region_name(counter);
489 // Just grab the first character, the `&`.
490 let source_map = tcx.sess.source_map();
491 let ampersand_span = source_map.start_point(hir_ty.span);
493 return Some(RegionName {
495 source: RegionNameSource::MatchedHirTy(ampersand_span),
499 // Otherwise, let's descend into the referent types.
500 search_stack.push((referent_ty, &referent_hir_ty.ty));
503 // Match up something like `Foo<'1>`
505 ty::Adt(_adt_def, substs),
506 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
509 // Type parameters of the type alias have no reason to
510 // be the same as those of the ADT.
511 // FIXME: We should be able to do something similar to
512 // match_adt_and_segment in this case.
513 Res::Def(DefKind::TyAlias, _) => (),
514 _ => if let Some(last_segment) = path.segments.last() {
515 if let Some(name) = self.match_adt_and_segment(
528 // The following cases don't have lifetimes, so we
529 // just worry about trying to match up the rustc type
530 // with the HIR types:
531 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
532 search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(elem_hir_tys));
535 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
536 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
537 search_stack.push((elem_ty, elem_hir_ty));
540 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
541 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
545 // FIXME there are other cases that we could trace
553 /// We've found an enum/struct/union type with the substitutions
554 /// `substs` and -- in the HIR -- a path type with the final
555 /// segment `last_segment`. Try to find a `'_` to highlight in
556 /// the generic args (or, if not, to produce new zipped pairs of
557 /// types+hir to search through).
558 fn match_adt_and_segment<'hir>(
560 substs: SubstsRef<'tcx>,
561 needle_fr: RegionVid,
562 last_segment: &'hir hir::PathSegment,
564 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
565 ) -> Option<RegionName> {
566 // Did the user give explicit arguments? (e.g., `Foo<..>`)
567 let args = last_segment.args.as_ref()?;
568 let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
569 match lifetime.name {
570 hir::LifetimeName::Param(_)
571 | hir::LifetimeName::Error
572 | hir::LifetimeName::Static
573 | hir::LifetimeName::Underscore => {
574 let region_name = self.synthesize_region_name(counter);
575 let ampersand_span = lifetime.span;
578 source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
582 hir::LifetimeName::Implicit => {
583 // In this case, the user left off the lifetime; so
584 // they wrote something like:
590 // where the fully elaborated form is `Foo<'_, '1,
591 // T>`. We don't consider this a match; instead we let
592 // the "fully elaborated" type fallback above handle
599 /// We've found an enum/struct/union type with the substitutions
600 /// `substs` and -- in the HIR -- a path with the generic
601 /// arguments `args`. If `needle_fr` appears in the args, return
602 /// the `hir::Lifetime` that corresponds to it. If not, push onto
603 /// `search_stack` the types+hir to search through.
604 fn try_match_adt_and_generic_args<'hir>(
606 substs: SubstsRef<'tcx>,
607 needle_fr: RegionVid,
608 args: &'hir hir::GenericArgs,
609 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
610 ) -> Option<&'hir hir::Lifetime> {
611 for (kind, hir_arg) in substs.iter().zip(&args.args) {
612 match (kind.unpack(), hir_arg) {
613 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
614 if r.to_region_vid() == needle_fr {
619 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
620 search_stack.push((ty, hir_ty));
623 (UnpackedKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
624 // Lifetimes cannot be found in consts, so we don't need
625 // to search anything here.
628 (UnpackedKind::Lifetime(_), _)
629 | (UnpackedKind::Type(_), _)
630 | (UnpackedKind::Const(_), _) => {
631 // I *think* that HIR lowering should ensure this
632 // doesn't happen, even in erroneous
633 // programs. Else we should use delay-span-bug.
636 "unmatched subst and hir arg: found {:?} vs {:?}",
647 /// Finds a closure upvar that contains `fr` and label it with a
648 /// fully elaborated type, returning something like `'1`. Result
652 /// | let x = Some(&22);
653 /// - fully elaborated type of `x` is `Option<&'1 u32>`
655 fn give_name_if_anonymous_region_appears_in_upvars(
657 tcx: TyCtxt<'_, '_, 'tcx>,
661 ) -> Option<RegionName> {
662 let upvar_index = self.get_upvar_index_for_region(tcx, fr)?;
663 let (upvar_name, upvar_span) =
664 self.get_upvar_name_and_span_for_region(tcx, upvars, upvar_index);
665 let region_name = self.synthesize_region_name(counter);
669 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
673 /// Checks for arguments appearing in the (closure) return type. It
674 /// must be a closure since, in a free fn, such an argument would
675 /// have to either also appear in an argument (if using elision)
676 /// or be early bound (named, not in argument).
677 fn give_name_if_anonymous_region_appears_in_output(
679 infcx: &InferCtxt<'_, '_, 'tcx>,
684 ) -> Option<RegionName> {
687 let return_ty = self.universal_regions.unnormalized_output_ty;
689 "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
692 if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
696 let mut highlight = RegionHighlightMode::default();
697 highlight.highlighting_region_vid(fr, *counter);
698 let type_name = infcx.extract_type_name(&return_ty, Some(highlight));
700 let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
702 let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
703 hir::Node::Expr(hir::Expr {
704 node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
707 match return_ty.output {
708 hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
709 hir::FunctionRetTy::Return(_) => return_ty.output.span(),
711 if gen_move.is_some() {
717 hir::Node::ImplItem(hir::ImplItem {
718 node: hir::ImplItemKind::Method(method_sig, _),
720 }) => (method_sig.decl.output.span(), ""),
725 // This counter value will already have been used, so this function will increment it
726 // so the next value will be used next and return the region name that would have been
728 name: self.synthesize_region_name(counter),
729 source: RegionNameSource::AnonRegionFromOutput(
731 mir_description.to_string(),
737 fn give_name_if_anonymous_region_appears_in_yield_ty(
739 infcx: &InferCtxt<'_, '_, 'tcx>,
744 ) -> Option<RegionName> {
745 // Note: generators from `async fn` yield `()`, so we don't have to
746 // worry about them here.
747 let yield_ty = self.universal_regions.yield_ty?;
749 "give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}",
755 if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
759 let mut highlight = RegionHighlightMode::default();
760 highlight.highlighting_region_vid(fr, *counter);
761 let type_name = infcx.extract_type_name(&yield_ty, Some(highlight));
763 let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
765 let yield_span = match tcx.hir().get(mir_node_id) {
766 hir::Node::Expr(hir::Expr {
767 node: hir::ExprKind::Closure(_, _, _, span, _),
770 tcx.sess.source_map().end_point(*span)
776 "give_name_if_anonymous_region_appears_in_yield_ty: \
777 type_name = {:?}, yield_span = {:?}",
783 name: self.synthesize_region_name(counter),
784 source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
788 /// Creates a synthetic region named `'1`, incrementing the
790 fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
794 Name::intern(&format!("'{:?}", c)).as_interned_str()