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),
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(..) => false,
56 crate fn was_synthesized(&self) -> bool {
61 crate fn name(&self) -> &InternedString {
65 crate fn highlight_region_name(
67 diag: &mut DiagnosticBuilder<'_>
70 RegionNameSource::NamedFreeRegion(span) |
71 RegionNameSource::NamedEarlyBoundRegion(span) => {
74 format!("lifetime `{}` defined here", self),
77 RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
80 format!("lifetime `{}` represents this closure's body", self),
84 RegionNameSource::CannotMatchHirTy(span, type_name) => {
85 diag.span_label(*span, format!("has type `{}`", type_name));
87 RegionNameSource::MatchedHirTy(span) => {
90 format!("let's call the lifetime of this reference `{}`", self),
93 RegionNameSource::MatchedAdtAndSegment(span) => {
94 diag.span_label(*span, format!("let's call this `{}`", self));
96 RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
99 format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
102 RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
105 format!("return type{} is {}", mir_description, type_name),
108 RegionNameSource::Static => {},
113 impl Display for RegionName {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 write!(f, "{}", self.name)
119 impl<'tcx> RegionInferenceContext<'tcx> {
120 /// Maps from an internal MIR region vid to something that we can
121 /// report to the user. In some cases, the region vids will map
122 /// directly to lifetimes that the user has a name for (e.g.,
123 /// `'static`). But frequently they will not, in which case we
124 /// have to find some way to identify the lifetime to the user. To
125 /// that end, this function takes a "diagnostic" so that it can
126 /// create auxiliary notes as needed.
128 /// Example (function arguments):
130 /// Suppose we are trying to give a name to the lifetime of the
134 /// fn foo(x: &u32) { .. }
137 /// This function would create a label like this:
140 /// | fn foo(x: &u32) { .. }
141 /// ------- fully elaborated type of `x` is `&'1 u32`
144 /// and then return the name `'1` for us to use.
145 crate fn give_region_a_name(
147 infcx: &InferCtxt<'_, '_, 'tcx>,
153 ) -> Option<RegionName> {
154 debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
156 assert!(self.universal_regions.is_universal_region(fr));
158 let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
160 self.give_name_if_anonymous_region_appears_in_arguments(
161 infcx, mir, mir_def_id, fr, counter,
165 self.give_name_if_anonymous_region_appears_in_upvars(
166 infcx.tcx, upvars, fr, counter,
170 self.give_name_if_anonymous_region_appears_in_output(
171 infcx, mir, mir_def_id, fr, counter,
175 debug!("give_region_a_name: gave name {:?}", value);
179 /// Checks for the case where `fr` maps to something that the
180 /// *user* has a name for. In that case, we'll be able to map
181 /// `fr` to a `Region<'tcx>`, and that region will be one of
183 fn give_name_from_error_region(
185 tcx: TyCtxt<'_, '_, 'tcx>,
189 ) -> Option<RegionName> {
190 let error_region = self.to_error_region(fr)?;
192 debug!("give_region_a_name: error_region = {:?}", error_region);
194 ty::ReEarlyBound(ebr) => {
196 let span = self.get_named_span(tcx, error_region, &ebr.name);
199 source: RegionNameSource::NamedEarlyBoundRegion(span)
206 ty::ReStatic => Some(RegionName {
207 name: keywords::StaticLifetime.name().as_interned_str(),
208 source: RegionNameSource::Static
211 ty::ReFree(free_region) => match free_region.bound_region {
212 ty::BoundRegion::BrNamed(_, name) => {
213 let span = self.get_named_span(tcx, error_region, &name);
216 source: RegionNameSource::NamedFreeRegion(span),
220 ty::BoundRegion::BrEnv => {
221 let mir_node_id = tcx.hir()
222 .as_local_node_id(mir_def_id)
223 .expect("non-local mir");
224 let def_ty = self.universal_regions.defining_ty;
226 if let DefiningTy::Closure(def_id, substs) = def_ty {
227 let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
228 tcx.hir().expect_expr(mir_node_id).node
232 bug!("Closure is not defined by a closure expr");
234 let region_name = self.synthesize_region_name(counter);
236 let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
237 let note = match closure_kind_ty.to_opt_closure_kind() {
238 Some(ty::ClosureKind::Fn) => {
239 "closure implements `Fn`, so references to captured variables \
240 can't escape the closure"
242 Some(ty::ClosureKind::FnMut) => {
243 "closure implements `FnMut`, so references to captured variables \
244 can't escape the closure"
246 Some(ty::ClosureKind::FnOnce) => {
247 bug!("BrEnv in a `FnOnce` closure");
249 None => bug!("Closure kind not inferred in borrow check"),
254 source: RegionNameSource::SynthesizedFreeEnvRegion(
260 // Can't have BrEnv in functions, constants or generators.
261 bug!("BrEnv outside of closure.");
265 ty::BoundRegion::BrAnon(_) | ty::BoundRegion::BrFresh(_) => None,
271 | ty::RePlaceholder(..)
274 | ty::ReClosureBound(..) => None,
278 /// Gets a span of a named region to provide context for error messages that
279 /// mention that span, for example:
283 /// | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
284 /// | -- -- lifetime `'b` defined here
286 /// | lifetime `'a` defined here
288 /// | with_signature(cell, t, |cell, t| require(cell, t));
289 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
294 tcx: TyCtxt<'_, '_, 'tcx>,
295 error_region: &RegionKind,
296 name: &InternedString,
298 let scope = error_region.free_region_binding_scope(tcx);
299 let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
301 let span = tcx.sess.source_map().def_span(tcx.hir().span_by_hir_id(node));
302 if let Some(param) = tcx.hir()
304 .and_then(|generics| generics.get_named(name))
312 /// Finds an argument that contains `fr` and label it with a fully
313 /// elaborated type, returning something like `'1`. Result looks
317 /// | fn foo(x: &u32) { .. }
318 /// ------- fully elaborated type of `x` is `&'1 u32`
320 fn give_name_if_anonymous_region_appears_in_arguments(
322 infcx: &InferCtxt<'_, '_, 'tcx>,
327 ) -> Option<RegionName> {
328 let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
329 let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
332 self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
333 if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
342 return Some(region_name);
345 self.give_name_if_we_cannot_match_hir_ty(infcx, mir, fr, arg_ty, counter)
348 fn give_name_if_we_can_match_hir_ty_from_argument(
350 infcx: &InferCtxt<'_, '_, 'tcx>,
353 needle_fr: RegionVid,
354 argument_ty: Ty<'tcx>,
355 argument_index: usize,
357 ) -> Option<RegionName> {
358 let mir_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?;
359 let fn_decl = infcx.tcx.hir().fn_decl(mir_node_id)?;
360 let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
361 match argument_hir_ty.node {
362 // This indicates a variable with no type annotation, like
363 // `|x|`... in that case, we can't highlight the type but
364 // must highlight the variable.
365 hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
373 _ => self.give_name_if_we_can_match_hir_ty(
383 /// Attempts to highlight the specific part of a type in an argument
384 /// that has no type annotation.
385 /// For example, we might produce an annotation like this:
391 /// | | has type `&'1 u32`
392 /// | has type `&'2 u32`
394 fn give_name_if_we_cannot_match_hir_ty(
396 infcx: &InferCtxt<'_, '_, 'tcx>,
398 needle_fr: RegionVid,
399 argument_ty: Ty<'tcx>,
401 ) -> Option<RegionName> {
402 let mut highlight = RegionHighlightMode::default();
403 highlight.highlighting_region_vid(needle_fr, *counter);
404 let type_name = infcx.extract_type_name(&argument_ty, Some(highlight));
407 "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
410 let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
411 // Only add a label if we can confirm that a region was labelled.
412 let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
413 let (_, span) = self.get_argument_name_and_span_for_region(mir, argument_index);
416 // This counter value will already have been used, so this function will increment
417 // it so the next value will be used next and return the region name that would
419 name: self.synthesize_region_name(counter),
420 source: RegionNameSource::CannotMatchHirTy(span, type_name),
429 /// Attempts to highlight the specific part of a type annotation
430 /// that contains the anonymous reference we want to give a name
431 /// to. For example, we might produce an annotation like this:
434 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
435 /// | - let's call the lifetime of this reference `'1`
438 /// the way this works is that we match up `argument_ty`, which is
439 /// a `Ty<'tcx>` (the internal form of the type) with
440 /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
441 /// annotation). We are descending through the types stepwise,
442 /// looking in to find the region `needle_fr` in the internal
443 /// type. Once we find that, we can use the span of the `hir::Ty`
444 /// to add the highlight.
446 /// This is a somewhat imperfect process, so long the way we also
447 /// keep track of the **closest** type we've found. If we fail to
448 /// find the exact `&` or `'_` to highlight, then we may fall back
449 /// to highlighting that closest type instead.
450 fn give_name_if_we_can_match_hir_ty(
452 tcx: TyCtxt<'_, '_, 'tcx>,
453 needle_fr: RegionVid,
454 argument_ty: Ty<'tcx>,
455 argument_hir_ty: &hir::Ty,
457 ) -> Option<RegionName> {
458 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
459 &mut vec![(argument_ty, argument_hir_ty)];
461 while let Some((ty, hir_ty)) = search_stack.pop() {
462 match (&ty.sty, &hir_ty.node) {
463 // Check if the `argument_ty` is `&'X ..` where `'X`
464 // is the region we are looking for -- if so, and we have a `&T`
465 // on the RHS, then we want to highlight the `&` like so:
468 // - let's call the lifetime of this reference `'1`
470 ty::Ref(region, referent_ty, _),
471 hir::TyKind::Rptr(_lifetime, referent_hir_ty),
473 if region.to_region_vid() == needle_fr {
474 let region_name = self.synthesize_region_name(counter);
476 // Just grab the first character, the `&`.
477 let source_map = tcx.sess.source_map();
478 let ampersand_span = source_map.start_point(hir_ty.span);
480 return Some(RegionName {
482 source: RegionNameSource::MatchedHirTy(ampersand_span),
486 // Otherwise, let's descend into the referent types.
487 search_stack.push((referent_ty, &referent_hir_ty.ty));
490 // Match up something like `Foo<'1>`
492 ty::Adt(_adt_def, substs),
493 hir::TyKind::Path(hir::QPath::Resolved(None, path)),
496 // Type parameters of the type alias have no reason to
497 // be the same as those of the ADT.
498 // FIXME: We should be able to do something similar to
499 // match_adt_and_segment in this case.
500 Res::Def(DefKind::TyAlias, _) => (),
501 _ => if let Some(last_segment) = path.segments.last() {
502 if let Some(name) = self.match_adt_and_segment(
515 // The following cases don't have lifetimes, so we
516 // just worry about trying to match up the rustc type
517 // with the HIR types:
518 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
519 search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(elem_hir_tys));
522 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
523 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
524 search_stack.push((elem_ty, elem_hir_ty));
527 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
528 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
532 // FIXME there are other cases that we could trace
540 /// We've found an enum/struct/union type with the substitutions
541 /// `substs` and -- in the HIR -- a path type with the final
542 /// segment `last_segment`. Try to find a `'_` to highlight in
543 /// the generic args (or, if not, to produce new zipped pairs of
544 /// types+hir to search through).
545 fn match_adt_and_segment<'hir>(
547 substs: SubstsRef<'tcx>,
548 needle_fr: RegionVid,
549 last_segment: &'hir hir::PathSegment,
551 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
552 ) -> Option<RegionName> {
553 // Did the user give explicit arguments? (e.g., `Foo<..>`)
554 let args = last_segment.args.as_ref()?;
555 let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
556 match lifetime.name {
557 hir::LifetimeName::Param(_)
558 | hir::LifetimeName::Error
559 | hir::LifetimeName::Static
560 | hir::LifetimeName::Underscore => {
561 let region_name = self.synthesize_region_name(counter);
562 let ampersand_span = lifetime.span;
565 source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
569 hir::LifetimeName::Implicit => {
570 // In this case, the user left off the lifetime; so
571 // they wrote something like:
577 // where the fully elaborated form is `Foo<'_, '1,
578 // T>`. We don't consider this a match; instead we let
579 // the "fully elaborated" type fallback above handle
586 /// We've found an enum/struct/union type with the substitutions
587 /// `substs` and -- in the HIR -- a path with the generic
588 /// arguments `args`. If `needle_fr` appears in the args, return
589 /// the `hir::Lifetime` that corresponds to it. If not, push onto
590 /// `search_stack` the types+hir to search through.
591 fn try_match_adt_and_generic_args<'hir>(
593 substs: SubstsRef<'tcx>,
594 needle_fr: RegionVid,
595 args: &'hir hir::GenericArgs,
596 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
597 ) -> Option<&'hir hir::Lifetime> {
598 for (kind, hir_arg) in substs.iter().zip(&args.args) {
599 match (kind.unpack(), hir_arg) {
600 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
601 if r.to_region_vid() == needle_fr {
606 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
607 search_stack.push((ty, hir_ty));
610 (UnpackedKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
611 // Lifetimes cannot be found in consts, so we don't need
612 // to search anything here.
615 (UnpackedKind::Lifetime(_), _)
616 | (UnpackedKind::Type(_), _)
617 | (UnpackedKind::Const(_), _) => {
618 // I *think* that HIR lowering should ensure this
619 // doesn't happen, even in erroneous
620 // programs. Else we should use delay-span-bug.
623 "unmatched subst and hir arg: found {:?} vs {:?}",
634 /// Finds a closure upvar that contains `fr` and label it with a
635 /// fully elaborated type, returning something like `'1`. Result
639 /// | let x = Some(&22);
640 /// - fully elaborated type of `x` is `Option<&'1 u32>`
642 fn give_name_if_anonymous_region_appears_in_upvars(
644 tcx: TyCtxt<'_, '_, 'tcx>,
648 ) -> Option<RegionName> {
649 let upvar_index = self.get_upvar_index_for_region(tcx, fr)?;
650 let (upvar_name, upvar_span) =
651 self.get_upvar_name_and_span_for_region(tcx, upvars, upvar_index);
652 let region_name = self.synthesize_region_name(counter);
656 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
660 /// Checks for arguments appearing in the (closure) return type. It
661 /// must be a closure since, in a free fn, such an argument would
662 /// have to either also appear in an argument (if using elision)
663 /// or be early bound (named, not in argument).
664 fn give_name_if_anonymous_region_appears_in_output(
666 infcx: &InferCtxt<'_, '_, 'tcx>,
671 ) -> Option<RegionName> {
674 let return_ty = self.universal_regions.unnormalized_output_ty;
676 "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
681 .any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr)
686 let mut highlight = RegionHighlightMode::default();
687 highlight.highlighting_region_vid(fr, *counter);
688 let type_name = infcx.extract_type_name(&return_ty, Some(highlight));
690 let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
692 let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
693 hir::Node::Expr(hir::Expr {
694 node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
697 match return_ty.output {
698 hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
699 hir::FunctionRetTy::Return(_) => return_ty.output.span(),
701 if gen_move.is_some() {
707 hir::Node::ImplItem(hir::ImplItem {
708 node: hir::ImplItemKind::Method(method_sig, _),
710 }) => (method_sig.decl.output.span(), ""),
715 // This counter value will already have been used, so this function will increment it
716 // so the next value will be used next and return the region name that would have been
718 name: self.synthesize_region_name(counter),
719 source: RegionNameSource::AnonRegionFromOutput(
721 mir_description.to_string(),
727 /// Creates a synthetic region named `'1`, incrementing the
729 fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
733 Name::intern(&format!("'{:?}", c)).as_interned_str()