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;
6 use rustc::hir::def_id::DefId;
7 use rustc::infer::InferCtxt;
9 use rustc::ty::subst::{Substs, UnpackedKind};
10 use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt};
11 use rustc::util::ppaux::RegionHighlightMode;
12 use rustc_errors::DiagnosticBuilder;
13 use syntax::ast::Name;
14 use syntax::symbol::keywords;
16 use syntax_pos::symbol::InternedString;
19 crate struct RegionName {
20 crate name: InternedString,
21 crate source: RegionNameSource,
25 crate enum RegionNameSource {
26 NamedEarlyBoundRegion(Span),
27 NamedFreeRegion(Span),
29 SynthesizedFreeEnvRegion(Span, String),
30 CannotMatchHirTy(Span, String),
32 MatchedAdtAndSegment(Span),
33 AnonRegionFromUpvar(Span, String),
34 AnonRegionFromOutput(Span, String, String),
39 crate fn was_named(&self) -> bool {
41 RegionNameSource::NamedEarlyBoundRegion(..) |
42 RegionNameSource::NamedFreeRegion(..) |
43 RegionNameSource::Static => true,
44 RegionNameSource::SynthesizedFreeEnvRegion(..) |
45 RegionNameSource::CannotMatchHirTy(..) |
46 RegionNameSource::MatchedHirTy(..) |
47 RegionNameSource::MatchedAdtAndSegment(..) |
48 RegionNameSource::AnonRegionFromUpvar(..) |
49 RegionNameSource::AnonRegionFromOutput(..) => false,
54 crate fn was_synthesized(&self) -> bool {
59 crate fn name(&self) -> &InternedString {
63 crate fn highlight_region_name(
65 diag: &mut DiagnosticBuilder<'_>
68 RegionNameSource::NamedFreeRegion(span) |
69 RegionNameSource::NamedEarlyBoundRegion(span) => {
72 format!("lifetime `{}` defined here", self),
75 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
78 format!("lifetime `{}` represents this closure's body", self),
82 RegionNameSource::CannotMatchHirTy(span, type_name) => {
83 diag.span_label(*span, format!("has type `{}`", type_name));
85 RegionNameSource::MatchedHirTy(span) => {
88 format!("let's call the lifetime of this reference `{}`", self),
91 RegionNameSource::MatchedAdtAndSegment(span) => {
92 diag.span_label(*span, format!("let's call this `{}`", self));
94 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
97 format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
100 RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
103 format!("return type{} is {}", mir_description, type_name),
106 RegionNameSource::Static => {},
111 impl Display for RegionName {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 write!(f, "{}", self.name)
117 impl<'tcx> RegionInferenceContext<'tcx> {
118 /// Maps from an internal MIR region vid to something that we can
119 /// report to the user. In some cases, the region vids will map
120 /// directly to lifetimes that the user has a name for (e.g.,
121 /// `'static`). But frequently they will not, in which case we
122 /// have to find some way to identify the lifetime to the user. To
123 /// that end, this function takes a "diagnostic" so that it can
124 /// create auxiliary notes as needed.
126 /// Example (function arguments):
128 /// Suppose we are trying to give a name to the lifetime of the
132 /// fn foo(x: &u32) { .. }
135 /// This function would create a label like this:
138 /// | fn foo(x: &u32) { .. }
139 /// ------- fully elaborated type of `x` is `&'1 u32`
142 /// and then return the name `'1` for us to use.
143 crate fn give_region_a_name(
145 infcx: &InferCtxt<'_, '_, 'tcx>,
150 ) -> Option<RegionName> {
151 debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
153 assert!(self.universal_regions.is_universal_region(fr));
155 let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
157 self.give_name_if_anonymous_region_appears_in_arguments(
158 infcx, mir, mir_def_id, fr, counter,
162 self.give_name_if_anonymous_region_appears_in_upvars(
163 infcx.tcx, mir, fr, counter,
167 self.give_name_if_anonymous_region_appears_in_output(
168 infcx, mir, mir_def_id, fr, counter,
172 debug!("give_region_a_name: gave name {:?}", value);
176 /// Check for the case where `fr` maps to something that the
177 /// *user* has a name for. In that case, we'll be able to map
178 /// `fr` to a `Region<'tcx>`, and that region will be one of
180 fn give_name_from_error_region(
182 tcx: TyCtxt<'_, '_, 'tcx>,
186 ) -> Option<RegionName> {
187 let error_region = self.to_error_region(fr)?;
189 debug!("give_region_a_name: error_region = {:?}", error_region);
191 ty::ReEarlyBound(ebr) => {
193 let span = self.get_named_span(tcx, error_region, &ebr.name);
196 source: RegionNameSource::NamedEarlyBoundRegion(span)
203 ty::ReStatic => Some(RegionName {
204 name: keywords::StaticLifetime.name().as_interned_str(),
205 source: RegionNameSource::Static
208 ty::ReFree(free_region) => match free_region.bound_region {
209 ty::BoundRegion::BrNamed(_, name) => {
210 let span = self.get_named_span(tcx, error_region, &name);
213 source: RegionNameSource::NamedFreeRegion(span),
217 ty::BoundRegion::BrEnv => {
218 let mir_node_id = tcx.hir()
219 .as_local_node_id(mir_def_id)
220 .expect("non-local mir");
221 let def_ty = self.universal_regions.defining_ty;
223 if let DefiningTy::Closure(def_id, substs) = def_ty {
224 let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
225 tcx.hir().expect_expr(mir_node_id).node
229 bug!("Closure is not defined by a closure expr");
231 let region_name = self.synthesize_region_name(counter);
233 let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
234 let note = match closure_kind_ty.to_opt_closure_kind() {
235 Some(ty::ClosureKind::Fn) => {
236 "closure implements `Fn`, so references to captured variables \
237 can't escape the closure"
239 Some(ty::ClosureKind::FnMut) => {
240 "closure implements `FnMut`, so references to captured variables \
241 can't escape the closure"
243 Some(ty::ClosureKind::FnOnce) => {
244 bug!("BrEnv in a `FnOnce` closure");
246 None => bug!("Closure kind not inferred in borrow check"),
251 source: RegionNameSource::SynthesizedFreeEnvRegion(
257 // Can't have BrEnv in functions, constants or generators.
258 bug!("BrEnv outside of closure.");
262 ty::BoundRegion::BrAnon(_) | ty::BoundRegion::BrFresh(_) => None,
268 | ty::RePlaceholder(..)
271 | ty::ReClosureBound(..) => None,
275 /// Get a span of a named region to provide context for error messages that
276 /// mention that span, for example:
280 /// | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
281 /// | -- -- lifetime `'b` defined here
283 /// | lifetime `'a` defined here
285 /// | with_signature(cell, t, |cell, t| require(cell, t));
286 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
291 tcx: TyCtxt<'_, '_, 'tcx>,
292 error_region: &RegionKind,
293 name: &InternedString,
295 let scope = error_region.free_region_binding_scope(tcx);
296 let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
298 let span = tcx.sess.source_map().def_span(tcx.hir().span_by_hir_id(node));
299 if let Some(param) = tcx.hir()
301 .and_then(|generics| generics.get_named(name))
309 /// Find an argument that contains `fr` and label it with a fully
310 /// elaborated type, returning something like `'1`. Result looks
314 /// | fn foo(x: &u32) { .. }
315 /// ------- fully elaborated type of `x` is `&'1 u32`
317 fn give_name_if_anonymous_region_appears_in_arguments(
319 infcx: &InferCtxt<'_, '_, 'tcx>,
324 ) -> Option<RegionName> {
325 let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
326 let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
329 self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
330 if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
339 return Some(region_name);
342 self.give_name_if_we_cannot_match_hir_ty(infcx, mir, fr, arg_ty, counter)
345 fn give_name_if_we_can_match_hir_ty_from_argument(
347 infcx: &InferCtxt<'_, '_, 'tcx>,
350 needle_fr: RegionVid,
351 argument_ty: Ty<'tcx>,
352 argument_index: usize,
354 ) -> Option<RegionName> {
355 let mir_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?;
356 let fn_decl = infcx.tcx.hir().fn_decl(mir_node_id)?;
357 let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
358 match argument_hir_ty.node {
359 // This indicates a variable with no type annotation, like
360 // `|x|`... in that case, we can't highlight the type but
361 // must highlight the variable.
362 hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
370 _ => self.give_name_if_we_can_match_hir_ty(
380 /// Attempts to highlight the specific part of a type in an argument
381 /// that has no type annotation.
382 /// For example, we might produce an annotation like this:
388 /// | | has type `&'1 u32`
389 /// | has type `&'2 u32`
391 fn give_name_if_we_cannot_match_hir_ty(
393 infcx: &InferCtxt<'_, '_, 'tcx>,
395 needle_fr: RegionVid,
396 argument_ty: Ty<'tcx>,
398 ) -> Option<RegionName> {
399 let type_name = RegionHighlightMode::highlighting_region_vid(needle_fr, *counter, || {
400 infcx.extract_type_name(&argument_ty)
404 "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
407 let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
408 // Only add a label if we can confirm that a region was labelled.
409 let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
410 let (_, span) = self.get_argument_name_and_span_for_region(mir, argument_index);
413 // This counter value will already have been used, so this function will increment
414 // it so the next value will be used next and return the region name that would
416 name: self.synthesize_region_name(counter),
417 source: RegionNameSource::CannotMatchHirTy(span, type_name),
426 /// Attempts to highlight the specific part of a type annotation
427 /// that contains the anonymous reference we want to give a name
428 /// to. For example, we might produce an annotation like this:
431 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item=&T>> {
432 /// | - let's call the lifetime of this reference `'1`
435 /// the way this works is that we match up `argument_ty`, which is
436 /// a `Ty<'tcx>` (the internal form of the type) with
437 /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
438 /// annotation). We are descending through the types stepwise,
439 /// looking in to find the region `needle_fr` in the internal
440 /// type. Once we find that, we can use the span of the `hir::Ty`
441 /// to add the highlight.
443 /// This is a somewhat imperfect process, so long the way we also
444 /// keep track of the **closest** type we've found. If we fail to
445 /// find the exact `&` or `'_` to highlight, then we may fall back
446 /// to highlighting that closest type instead.
447 fn give_name_if_we_can_match_hir_ty(
449 tcx: TyCtxt<'_, '_, 'tcx>,
450 needle_fr: RegionVid,
451 argument_ty: Ty<'tcx>,
452 argument_hir_ty: &hir::Ty,
454 ) -> Option<RegionName> {
455 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
456 &mut vec![(argument_ty, argument_hir_ty)];
458 while let Some((ty, hir_ty)) = search_stack.pop() {
459 match (&ty.sty, &hir_ty.node) {
460 // Check if the `argument_ty` is `&'X ..` where `'X`
461 // is the region we are looking for -- if so, and we have a `&T`
462 // on the RHS, then we want to highlight the `&` like so:
465 // - let's call the lifetime of this reference `'1`
467 ty::Ref(region, referent_ty, _),
468 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
470 if region.to_region_vid() == needle_fr {
471 let region_name = self.synthesize_region_name(counter);
473 // Just grab the first character, the `&`.
474 let source_map = tcx.sess.source_map();
475 let ampersand_span = source_map.start_point(hir_ty.span);
477 return Some(RegionName {
479 source: RegionNameSource::MatchedHirTy(ampersand_span),
483 // Otherwise, let's descend into the referent types.
484 search_stack.push((referent_ty, &referent_hir_ty.ty));
487 // Match up something like `Foo<'1>`
489 ty::Adt(_adt_def, substs),
490 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
493 // Type parameters of the type alias have no reason to
494 // be the same as those of the ADT.
495 // FIXME: We should be able to do something similar to
496 // match_adt_and_segment in this case.
497 hir::def::Def::TyAlias(_) => (),
498 _ => if let Some(last_segment) = path.segments.last() {
499 if let Some(name) = self.match_adt_and_segment(
512 // The following cases don't have lifetimes, so we
513 // just worry about trying to match up the rustc type
514 // with the HIR types:
515 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
516 search_stack.extend(elem_tys.iter().cloned().zip(elem_hir_tys));
519 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
520 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
521 search_stack.push((elem_ty, elem_hir_ty));
524 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
525 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
529 // FIXME there are other cases that we could trace
537 /// We've found an enum/struct/union type with the substitutions
538 /// `substs` and -- in the HIR -- a path type with the final
539 /// segment `last_segment`. Try to find a `'_` to highlight in
540 /// the generic args (or, if not, to produce new zipped pairs of
541 /// types+hir to search through).
542 fn match_adt_and_segment<'hir>(
544 substs: &'tcx Substs<'tcx>,
545 needle_fr: RegionVid,
546 last_segment: &'hir hir::PathSegment,
548 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
549 ) -> Option<RegionName> {
550 // Did the user give explicit arguments? (e.g., `Foo<..>`)
551 let args = last_segment.args.as_ref()?;
552 let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
553 match lifetime.name {
554 hir::LifetimeName::Param(_)
555 | hir::LifetimeName::Error
556 | hir::LifetimeName::Static
557 | hir::LifetimeName::Underscore => {
558 let region_name = self.synthesize_region_name(counter);
559 let ampersand_span = lifetime.span;
562 source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
566 hir::LifetimeName::Implicit => {
567 // In this case, the user left off the lifetime; so
568 // they wrote something like:
574 // where the fully elaborated form is `Foo<'_, '1,
575 // T>`. We don't consider this a match; instead we let
576 // the "fully elaborated" type fallback above handle
583 /// We've found an enum/struct/union type with the substitutions
584 /// `substs` and -- in the HIR -- a path with the generic
585 /// arguments `args`. If `needle_fr` appears in the args, return
586 /// the `hir::Lifetime` that corresponds to it. If not, push onto
587 /// `search_stack` the types+hir to search through.
588 fn try_match_adt_and_generic_args<'hir>(
590 substs: &'tcx Substs<'tcx>,
591 needle_fr: RegionVid,
592 args: &'hir hir::GenericArgs,
593 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
594 ) -> Option<&'hir hir::Lifetime> {
595 for (kind, hir_arg) in substs.iter().zip(&args.args) {
596 match (kind.unpack(), hir_arg) {
597 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
598 if r.to_region_vid() == needle_fr {
603 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
604 search_stack.push((ty, hir_ty));
607 (UnpackedKind::Lifetime(_), _) | (UnpackedKind::Type(_), _) => {
608 // I *think* that HIR lowering should ensure this
609 // doesn't happen, even in erroneous
610 // programs. Else we should use delay-span-bug.
613 "unmatched subst and hir arg: found {:?} vs {:?}",
624 /// Find a closure upvar that contains `fr` and label it with a
625 /// fully elaborated type, returning something like `'1`. Result
629 /// | let x = Some(&22);
630 /// - fully elaborated type of `x` is `Option<&'1 u32>`
632 fn give_name_if_anonymous_region_appears_in_upvars(
634 tcx: TyCtxt<'_, '_, 'tcx>,
638 ) -> Option<RegionName> {
639 let upvar_index = self.get_upvar_index_for_region(tcx, fr)?;
640 let (upvar_name, upvar_span) =
641 self.get_upvar_name_and_span_for_region(tcx, mir, upvar_index);
642 let region_name = self.synthesize_region_name(counter);
646 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
650 /// Check for arguments appearing in the (closure) return type. It
651 /// must be a closure since, in a free fn, such an argument would
652 /// have to either also appear in an argument (if using elision)
653 /// or be early bound (named, not in argument).
654 fn give_name_if_anonymous_region_appears_in_output(
656 infcx: &InferCtxt<'_, '_, 'tcx>,
661 ) -> Option<RegionName> {
664 let return_ty = self.universal_regions.unnormalized_output_ty;
666 "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
671 .any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr)
676 let type_name = RegionHighlightMode::highlighting_region_vid(
677 fr, *counter, || infcx.extract_type_name(&return_ty),
680 let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
682 let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
683 hir::Node::Expr(hir::Expr {
684 node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
687 match return_ty.output {
688 hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
689 hir::FunctionRetTy::Return(_) => return_ty.output.span(),
691 if gen_move.is_some() {
697 hir::Node::ImplItem(hir::ImplItem {
698 node: hir::ImplItemKind::Method(method_sig, _),
700 }) => (method_sig.decl.output.span(), ""),
705 // This counter value will already have been used, so this function will increment it
706 // so the next value will be used next and return the region name that would have been
708 name: self.synthesize_region_name(counter),
709 source: RegionNameSource::AnonRegionFromOutput(
711 mir_description.to_string(),
717 /// Create a synthetic region named `'1`, incrementing the
719 fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
723 Name::intern(&format!("'{:?}", c)).as_interned_str()