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::symbol::kw;
17 use syntax_pos::symbol::InternedString;
20 crate struct RegionName {
21 crate name: InternedString,
22 crate source: RegionNameSource,
26 crate enum RegionNameSource {
27 NamedEarlyBoundRegion(Span),
28 NamedFreeRegion(Span),
30 SynthesizedFreeEnvRegion(Span, String),
31 CannotMatchHirTy(Span, String),
33 MatchedAdtAndSegment(Span),
34 AnonRegionFromUpvar(Span, String),
35 AnonRegionFromOutput(Span, String, String),
36 AnonRegionFromYieldTy(Span, String),
41 crate fn was_named(&self) -> bool {
43 RegionNameSource::NamedEarlyBoundRegion(..) |
44 RegionNameSource::NamedFreeRegion(..) |
45 RegionNameSource::Static => true,
46 RegionNameSource::SynthesizedFreeEnvRegion(..) |
47 RegionNameSource::CannotMatchHirTy(..) |
48 RegionNameSource::MatchedHirTy(..) |
49 RegionNameSource::MatchedAdtAndSegment(..) |
50 RegionNameSource::AnonRegionFromUpvar(..) |
51 RegionNameSource::AnonRegionFromOutput(..) |
52 RegionNameSource::AnonRegionFromYieldTy(..) => false,
57 crate fn was_synthesized(&self) -> bool {
62 crate fn name(&self) -> InternedString {
66 crate fn highlight_region_name(
68 diag: &mut DiagnosticBuilder<'_>
71 RegionNameSource::NamedFreeRegion(span) |
72 RegionNameSource::NamedEarlyBoundRegion(span) => {
75 format!("lifetime `{}` defined here", self),
78 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
81 format!("lifetime `{}` represents this closure's body", self),
85 RegionNameSource::CannotMatchHirTy(span, type_name) => {
86 diag.span_label(*span, format!("has type `{}`", type_name));
88 RegionNameSource::MatchedHirTy(span) => {
91 format!("let's call the lifetime of this reference `{}`", self),
94 RegionNameSource::MatchedAdtAndSegment(span) => {
95 diag.span_label(*span, format!("let's call this `{}`", self));
97 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
100 format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
103 RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
106 format!("return type{} is {}", mir_description, type_name),
109 RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
112 format!("yield type is {}", type_name),
115 RegionNameSource::Static => {},
120 impl Display for RegionName {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 write!(f, "{}", self.name)
126 impl<'tcx> RegionInferenceContext<'tcx> {
127 /// Maps from an internal MIR region vid to something that we can
128 /// report to the user. In some cases, the region vids will map
129 /// directly to lifetimes that the user has a name for (e.g.,
130 /// `'static`). But frequently they will not, in which case we
131 /// have to find some way to identify the lifetime to the user. To
132 /// that end, this function takes a "diagnostic" so that it can
133 /// create auxiliary notes as needed.
135 /// Example (function arguments):
137 /// Suppose we are trying to give a name to the lifetime of the
141 /// fn foo(x: &u32) { .. }
144 /// This function would create a label like this:
147 /// | fn foo(x: &u32) { .. }
148 /// ------- fully elaborated type of `x` is `&'1 u32`
151 /// and then return the name `'1` for us to use.
152 crate fn give_region_a_name(
154 infcx: &InferCtxt<'_, 'tcx>,
160 ) -> Option<RegionName> {
161 debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
163 assert!(self.universal_regions.is_universal_region(fr));
165 let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
167 self.give_name_if_anonymous_region_appears_in_arguments(
168 infcx, body, mir_def_id, fr, counter,
172 self.give_name_if_anonymous_region_appears_in_upvars(
173 infcx.tcx, upvars, fr, counter,
177 self.give_name_if_anonymous_region_appears_in_output(
178 infcx, body, mir_def_id, fr, counter,
182 self.give_name_if_anonymous_region_appears_in_yield_ty(
183 infcx, body, mir_def_id, fr, counter,
187 debug!("give_region_a_name: gave name {:?}", value);
191 /// Checks for the case where `fr` maps to something that the
192 /// *user* has a name for. In that case, we'll be able to map
193 /// `fr` to a `Region<'tcx>`, and that region will be one of
195 fn give_name_from_error_region(
201 ) -> Option<RegionName> {
202 let error_region = self.to_error_region(fr)?;
204 debug!("give_region_a_name: error_region = {:?}", error_region);
206 ty::ReEarlyBound(ebr) => {
208 let span = self.get_named_span(tcx, error_region, ebr.name);
211 source: RegionNameSource::NamedEarlyBoundRegion(span)
218 ty::ReStatic => Some(RegionName {
219 name: kw::StaticLifetime.as_interned_str(),
220 source: RegionNameSource::Static
223 ty::ReFree(free_region) => match free_region.bound_region {
224 ty::BoundRegion::BrNamed(_, name) => {
225 let span = self.get_named_span(tcx, error_region, name);
228 source: RegionNameSource::NamedFreeRegion(span),
232 ty::BoundRegion::BrEnv => {
233 let mir_hir_id = tcx.hir()
234 .as_local_hir_id(mir_def_id)
235 .expect("non-local mir");
236 let def_ty = self.universal_regions.defining_ty;
238 if let DefiningTy::Closure(def_id, substs) = def_ty {
239 let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
240 tcx.hir().expect_expr(mir_hir_id).node
244 bug!("Closure is not defined by a closure expr");
246 let region_name = self.synthesize_region_name(counter);
248 let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
249 let note = match closure_kind_ty.to_opt_closure_kind() {
250 Some(ty::ClosureKind::Fn) => {
251 "closure implements `Fn`, so references to captured variables \
252 can't escape the closure"
254 Some(ty::ClosureKind::FnMut) => {
255 "closure implements `FnMut`, so references to captured variables \
256 can't escape the closure"
258 Some(ty::ClosureKind::FnOnce) => {
259 bug!("BrEnv in a `FnOnce` closure");
261 None => bug!("Closure kind not inferred in borrow check"),
266 source: RegionNameSource::SynthesizedFreeEnvRegion(
272 // Can't have BrEnv in functions, constants or generators.
273 bug!("BrEnv outside of closure.");
277 ty::BoundRegion::BrAnon(_) => None,
283 | ty::RePlaceholder(..)
286 | ty::ReClosureBound(..) => None,
290 /// Gets a span of a named region to provide context for error messages that
291 /// mention that span, for example:
295 /// | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
296 /// | -- -- lifetime `'b` defined here
298 /// | lifetime `'a` defined here
300 /// | with_signature(cell, t, |cell, t| require(cell, t));
301 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
307 error_region: &RegionKind,
308 name: InternedString,
310 let scope = error_region.free_region_binding_scope(tcx);
311 let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
313 let span = tcx.sess.source_map().def_span(tcx.hir().span(node));
314 if let Some(param) = tcx.hir()
316 .and_then(|generics| generics.get_named(name))
324 /// Finds an argument that contains `fr` and label it with a fully
325 /// elaborated type, returning something like `'1`. Result looks
329 /// | fn foo(x: &u32) { .. }
330 /// ------- fully elaborated type of `x` is `&'1 u32`
332 fn give_name_if_anonymous_region_appears_in_arguments(
334 infcx: &InferCtxt<'_, 'tcx>,
339 ) -> Option<RegionName> {
340 let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
341 let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
344 self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
345 if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
354 return Some(region_name);
357 self.give_name_if_we_cannot_match_hir_ty(infcx, body, fr, arg_ty, counter)
360 fn give_name_if_we_can_match_hir_ty_from_argument(
362 infcx: &InferCtxt<'_, 'tcx>,
365 needle_fr: RegionVid,
366 argument_ty: Ty<'tcx>,
367 argument_index: usize,
369 ) -> Option<RegionName> {
370 let mir_hir_id = infcx.tcx.hir().as_local_hir_id(mir_def_id)?;
371 let fn_decl = infcx.tcx.hir().fn_decl_by_hir_id(mir_hir_id)?;
372 let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
373 match argument_hir_ty.node {
374 // This indicates a variable with no type annotation, like
375 // `|x|`... in that case, we can't highlight the type but
376 // must highlight the variable.
377 hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
385 _ => self.give_name_if_we_can_match_hir_ty(
395 /// Attempts to highlight the specific part of a type in an argument
396 /// that has no type annotation.
397 /// For example, we might produce an annotation like this:
403 /// | | has type `&'1 u32`
404 /// | has type `&'2 u32`
406 fn give_name_if_we_cannot_match_hir_ty(
408 infcx: &InferCtxt<'_, 'tcx>,
410 needle_fr: RegionVid,
411 argument_ty: Ty<'tcx>,
413 ) -> Option<RegionName> {
414 let mut highlight = RegionHighlightMode::default();
415 highlight.highlighting_region_vid(needle_fr, *counter);
416 let type_name = infcx.extract_type_name(&argument_ty, Some(highlight));
419 "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
422 let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
423 // Only add a label if we can confirm that a region was labelled.
424 let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
425 let (_, span) = self.get_argument_name_and_span_for_region(body, argument_index);
428 // This counter value will already have been used, so this function will increment
429 // it so the next value will be used next and return the region name that would
431 name: self.synthesize_region_name(counter),
432 source: RegionNameSource::CannotMatchHirTy(span, type_name),
441 /// Attempts to highlight the specific part of a type annotation
442 /// that contains the anonymous reference we want to give a name
443 /// to. For example, we might produce an annotation like this:
446 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
447 /// | - let's call the lifetime of this reference `'1`
450 /// the way this works is that we match up `argument_ty`, which is
451 /// a `Ty<'tcx>` (the internal form of the type) with
452 /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
453 /// annotation). We are descending through the types stepwise,
454 /// looking in to find the region `needle_fr` in the internal
455 /// type. Once we find that, we can use the span of the `hir::Ty`
456 /// to add the highlight.
458 /// This is a somewhat imperfect process, so long the way we also
459 /// keep track of the **closest** type we've found. If we fail to
460 /// find the exact `&` or `'_` to highlight, then we may fall back
461 /// to highlighting that closest type instead.
462 fn give_name_if_we_can_match_hir_ty(
465 needle_fr: RegionVid,
466 argument_ty: Ty<'tcx>,
467 argument_hir_ty: &hir::Ty,
469 ) -> Option<RegionName> {
470 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
471 &mut vec![(argument_ty, argument_hir_ty)];
473 while let Some((ty, hir_ty)) = search_stack.pop() {
474 match (&ty.sty, &hir_ty.node) {
475 // Check if the `argument_ty` is `&'X ..` where `'X`
476 // is the region we are looking for -- if so, and we have a `&T`
477 // on the RHS, then we want to highlight the `&` like so:
480 // - let's call the lifetime of this reference `'1`
482 ty::Ref(region, referent_ty, _),
483 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
485 if region.to_region_vid() == needle_fr {
486 let region_name = self.synthesize_region_name(counter);
488 // Just grab the first character, the `&`.
489 let source_map = tcx.sess.source_map();
490 let ampersand_span = source_map.start_point(hir_ty.span);
492 return Some(RegionName {
494 source: RegionNameSource::MatchedHirTy(ampersand_span),
498 // Otherwise, let's descend into the referent types.
499 search_stack.push((referent_ty, &referent_hir_ty.ty));
502 // Match up something like `Foo<'1>`
504 ty::Adt(_adt_def, substs),
505 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
508 // Type parameters of the type alias have no reason to
509 // be the same as those of the ADT.
510 // FIXME: We should be able to do something similar to
511 // match_adt_and_segment in this case.
512 Res::Def(DefKind::TyAlias, _) => (),
513 _ => if let Some(last_segment) = path.segments.last() {
514 if let Some(name) = self.match_adt_and_segment(
527 // The following cases don't have lifetimes, so we
528 // just worry about trying to match up the rustc type
529 // with the HIR types:
530 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
531 search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(elem_hir_tys));
534 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
535 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
536 search_stack.push((elem_ty, elem_hir_ty));
539 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
540 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
544 // FIXME there are other cases that we could trace
552 /// We've found an enum/struct/union type with the substitutions
553 /// `substs` and -- in the HIR -- a path type with the final
554 /// segment `last_segment`. Try to find a `'_` to highlight in
555 /// the generic args (or, if not, to produce new zipped pairs of
556 /// types+hir to search through).
557 fn match_adt_and_segment<'hir>(
559 substs: SubstsRef<'tcx>,
560 needle_fr: RegionVid,
561 last_segment: &'hir hir::PathSegment,
563 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
564 ) -> Option<RegionName> {
565 // Did the user give explicit arguments? (e.g., `Foo<..>`)
566 let args = last_segment.args.as_ref()?;
567 let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
568 match lifetime.name {
569 hir::LifetimeName::Param(_)
570 | hir::LifetimeName::Error
571 | hir::LifetimeName::Static
572 | hir::LifetimeName::Underscore => {
573 let region_name = self.synthesize_region_name(counter);
574 let ampersand_span = lifetime.span;
577 source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
581 hir::LifetimeName::ImplicitObjectLifetimeDefault
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(
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_hir_id = tcx.hir().as_local_hir_id(mir_def_id).expect("non-local mir");
702 let (return_span, mir_description) = match tcx.hir().get(mir_hir_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(), ""),
721 _ => (body.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_hir_id = tcx.hir().as_local_hir_id(mir_def_id).expect("non-local mir");
765 let yield_span = match tcx.hir().get(mir_hir_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 InternedString::intern(&format!("'{:?}", c))