1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use borrow_check::nll::region_infer::RegionInferenceContext;
12 use borrow_check::nll::ToRegionVid;
14 use rustc::hir::def_id::DefId;
15 use rustc::mir::{Local, Mir};
16 use rustc::ty::subst::{Substs, UnpackedKind};
17 use rustc::ty::{self, RegionVid, Ty, TyCtxt};
18 use rustc_data_structures::indexed_vec::Idx;
19 use rustc_errors::DiagnosticBuilder;
20 use syntax::ast::Name;
21 use syntax::symbol::keywords;
22 use syntax_pos::symbol::InternedString;
24 impl<'tcx> RegionInferenceContext<'tcx> {
25 /// Maps from an internal MIR region vid to something that we can
26 /// report to the user. In some cases, the region vids will map
27 /// directly to lifetimes that the user has a name for (e.g.,
28 /// `'static`). But frequently they will not, in which case we
29 /// have to find some way to identify the lifetime to the user. To
30 /// that end, this function takes a "diagnostic" so that it can
31 /// create auxiliary notes as needed.
33 /// Example (function arguments):
35 /// Suppose we are trying to give a name to the lifetime of the
39 /// fn foo(x: &u32) { .. }
42 /// This function would create a label like this:
45 /// | fn foo(x: &u32) { .. }
46 /// ------- fully elaborated type of `x` is `&'1 u32`
49 /// and then return the name `'1` for us to use.
50 crate fn give_region_a_name(
52 tcx: TyCtxt<'_, '_, 'tcx>,
57 diag: &mut DiagnosticBuilder,
59 debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
61 assert!(self.universal_regions.is_universal_region(fr));
63 self.give_name_from_error_region(tcx, mir_def_id, fr, counter, diag)
65 self.give_name_if_anonymous_region_appears_in_arguments(
66 tcx, mir, mir_def_id, fr, counter, diag,
70 self.give_name_if_anonymous_region_appears_in_upvars(tcx, mir, fr, counter, diag)
73 self.give_name_if_anonymous_region_appears_in_output(tcx, mir, fr, counter, diag)
75 .unwrap_or_else(|| span_bug!(mir.span, "can't make a name for free region {:?}", fr))
78 /// Check for the case where `fr` maps to something that the
79 /// *user* has a name for. In that case, we'll be able to map
80 /// `fr` to a `Region<'tcx>`, and that region will be one of
82 fn give_name_from_error_region(
84 tcx: TyCtxt<'_, '_, 'tcx>,
88 diag: &mut DiagnosticBuilder<'_>,
89 ) -> Option<InternedString> {
90 let error_region = self.to_error_region(fr)?;
91 debug!("give_region_a_name: error_region = {:?}", error_region);
93 ty::ReEarlyBound(ebr) => Some(ebr.name),
95 ty::ReStatic => Some(keywords::StaticLifetime.name().as_interned_str()),
97 ty::ReFree(free_region) => match free_region.bound_region {
98 ty::BoundRegion::BrNamed(_, name) => Some(name),
100 ty::BoundRegion::BrEnv => {
101 let closure_span = tcx.hir.span_if_local(mir_def_id).unwrap();
102 let region_name = self.synthesize_region_name(counter);
105 format!("lifetime `{}` represents the closure body", region_name),
110 ty::BoundRegion::BrAnon(_) | ty::BoundRegion::BrFresh(_) => None,
116 | ty::ReSkolemized(..)
119 | ty::ReClosureBound(..)
120 | ty::ReCanonical(..) => None,
124 /// Find an argument that contains `fr` and label it with a fully
125 /// elaborated type, returning something like `'1`. Result looks
129 /// | fn foo(x: &u32) { .. }
130 /// ------- fully elaborated type of `x` is `&'1 u32`
132 fn give_name_if_anonymous_region_appears_in_arguments(
134 tcx: TyCtxt<'_, '_, 'tcx>,
139 diag: &mut DiagnosticBuilder<'_>,
140 ) -> Option<InternedString> {
141 let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
142 let argument_index = self
144 .unnormalized_input_tys
146 .skip(implicit_inputs)
149 "give_name_if_anonymous_region_appears_in_arguments: arg_ty = {:?}",
152 tcx.any_free_region_meets(arg_ty, |r| r.to_region_vid() == fr)
156 "give_name_if_anonymous_region_appears_in_arguments: \
157 found {:?} in argument {} which has type {:?}",
158 fr, argument_index, self.universal_regions.unnormalized_input_tys[argument_index],
162 self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
163 if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
172 return Some(region_name);
175 let region_name = self.synthesize_region_name(counter);
177 let argument_local = Local::new(argument_index + implicit_inputs + 1);
178 let argument_span = mir.local_decls[argument_local].source_info.span;
181 format!("lifetime `{}` appears in this argument", region_name,),
187 fn give_name_if_we_can_match_hir_ty_from_argument(
189 tcx: TyCtxt<'_, '_, 'tcx>,
191 needle_fr: RegionVid,
192 argument_ty: Ty<'tcx>,
193 argument_index: usize,
195 diag: &mut DiagnosticBuilder<'_>,
196 ) -> Option<InternedString> {
197 let mir_node_id = tcx.hir.as_local_node_id(mir_def_id)?;
198 let fn_decl = tcx.hir.fn_decl(mir_node_id)?;
199 let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
200 match argument_hir_ty.node {
201 // This indicates a variable with no type annotation, like
202 // `|x|`... in that case, we can't highlight the type but
203 // must highlight the variable.
204 hir::TyInfer => None,
206 _ => self.give_name_if_we_can_match_hir_ty(
217 /// Attempts to highlight the specific part of a type annotation
218 /// that contains the anonymous reference we want to give a name
219 /// to. For example, we might produce an annotation like this:
222 /// | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item=&T>> {
223 /// | - let's call the lifetime of this reference `'1`
226 /// the way this works is that we match up `argument_ty`, which is
227 /// a `Ty<'tcx>` (the internal form of the type) with
228 /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
229 /// annotation). We are descending through the types stepwise,
230 /// looking in to find the region `needle_fr` in the internal
231 /// type. Once we find that, we can use the span of the `hir::Ty`
232 /// to add the highlight.
234 /// This is a somewhat imperfect process, so long the way we also
235 /// keep track of the **closest** type we've found. If we fail to
236 /// find the exact `&` or `'_` to highlight, then we may fall back
237 /// to highlighting that closest type instead.
238 fn give_name_if_we_can_match_hir_ty(
240 tcx: TyCtxt<'_, '_, 'tcx>,
241 needle_fr: RegionVid,
242 argument_ty: Ty<'tcx>,
243 argument_hir_ty: &hir::Ty,
245 diag: &mut DiagnosticBuilder<'_>,
246 ) -> Option<InternedString> {
247 let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> = &mut Vec::new();
249 search_stack.push((argument_ty, argument_hir_ty));
251 let mut closest_match: &hir::Ty = argument_hir_ty;
253 while let Some((ty, hir_ty)) = search_stack.pop() {
254 // While we search, also track the closet match.
255 if tcx.any_free_region_meets(&ty, |r| r.to_region_vid() == needle_fr) {
256 closest_match = hir_ty;
259 match (&ty.sty, &hir_ty.node) {
260 // Check if the `argument_ty` is `&'X ..` where `'X`
261 // is the region we are looking for -- if so, and we have a `&T`
262 // on the RHS, then we want to highlight the `&` like so:
265 // - let's call the lifetime of this reference `'1`
266 (ty::TyRef(region, referent_ty, _), hir::TyRptr(_lifetime, referent_hir_ty)) => {
267 if region.to_region_vid() == needle_fr {
268 let region_name = self.synthesize_region_name(counter);
270 // Just grab the first character, the `&`.
271 let codemap = tcx.sess.codemap();
272 let ampersand_span = codemap.start_point(hir_ty.span);
277 "let's call the lifetime of this reference `{}`",
282 return Some(region_name);
285 // Otherwise, let's descend into the referent types.
286 search_stack.push((referent_ty, &referent_hir_ty.ty));
289 // Match up something like `Foo<'1>`
290 (ty::TyAdt(_adt_def, substs), hir::TyPath(hir::QPath::Resolved(None, path))) => {
291 if let Some(last_segment) = path.segments.last() {
292 if let Some(name) = self.match_adt_and_segment(
305 // The following cases don't have lifetimes, so we
306 // just worry about trying to match up the rustc type
307 // with the HIR types:
308 (ty::TyTuple(elem_tys), hir::TyTup(elem_hir_tys)) => {
309 search_stack.extend(elem_tys.iter().cloned().zip(elem_hir_tys));
312 (ty::TySlice(elem_ty), hir::TySlice(elem_hir_ty))
313 | (ty::TyArray(elem_ty, _), hir::TyArray(elem_hir_ty, _)) => {
314 search_stack.push((elem_ty, elem_hir_ty));
317 (ty::TyRawPtr(mut_ty), hir::TyPtr(mut_hir_ty)) => {
318 search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
322 // FIXME there are other cases that we could trace
327 let region_name = self.synthesize_region_name(counter);
330 format!("lifetime `{}` appears in this type", region_name),
333 return Some(region_name);
336 /// We've found an enum/struct/union type with the substitutions
337 /// `substs` and -- in the HIR -- a path type with the final
338 /// segment `last_segment`. Try to find a `'_` to highlight in
339 /// the generic args (or, if not, to produce new zipped pairs of
340 /// types+hir to search through).
341 fn match_adt_and_segment<'hir>(
343 substs: &'tcx Substs<'tcx>,
344 needle_fr: RegionVid,
345 last_segment: &'hir hir::PathSegment,
347 diag: &mut DiagnosticBuilder<'_>,
348 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
349 ) -> Option<InternedString> {
350 // Did the user give explicit arguments? (e.g., `Foo<..>`)
351 let args = last_segment.args.as_ref()?;
352 let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
353 match lifetime.name {
354 hir::LifetimeName::Param(_)
355 | hir::LifetimeName::Static
356 | hir::LifetimeName::Underscore => {
357 let region_name = self.synthesize_region_name(counter);
358 let ampersand_span = lifetime.span;
359 diag.span_label(ampersand_span, format!("let's call this `{}`", region_name));
360 return Some(region_name);
363 hir::LifetimeName::Implicit => {
364 // In this case, the user left off the lifetime; so
365 // they wrote something like:
371 // where the fully elaborated form is `Foo<'_, '1,
372 // T>`. We don't consider this a match; instead we let
373 // the "fully elaborated" type fallback above handle
380 /// We've found an enum/struct/union type with the substitutions
381 /// `substs` and -- in the HIR -- a path with the generic
382 /// arguments `args`. If `needle_fr` appears in the args, return
383 /// the `hir::Lifetime` that corresponds to it. If not, push onto
384 /// `search_stack` the types+hir to search through.
385 fn try_match_adt_and_generic_args<'hir>(
387 substs: &'tcx Substs<'tcx>,
388 needle_fr: RegionVid,
389 args: &'hir hir::GenericArgs,
390 search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
391 ) -> Option<&'hir hir::Lifetime> {
392 for (kind, hir_arg) in substs.iter().zip(&args.args) {
393 match (kind.unpack(), hir_arg) {
394 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
395 if r.to_region_vid() == needle_fr {
400 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
401 search_stack.push((ty, hir_ty));
404 (UnpackedKind::Lifetime(_), _) | (UnpackedKind::Type(_), _) => {
405 // I *think* that HIR lowering should ensure this
406 // doesn't happen, even in erroneous
407 // programs. Else we should use delay-span-bug.
410 "unmatched subst and hir arg: found {:?} vs {:?}",
421 /// Find a closure upvar that contains `fr` and label it with a
422 /// fully elaborated type, returning something like `'1`. Result
426 /// | let x = Some(&22);
427 /// - fully elaborated type of `x` is `Option<&'1 u32>`
429 fn give_name_if_anonymous_region_appears_in_upvars(
431 tcx: TyCtxt<'_, '_, 'tcx>,
435 diag: &mut DiagnosticBuilder<'_>,
436 ) -> Option<InternedString> {
437 let upvar_index = self
441 .position(|upvar_ty| {
443 "give_name_if_anonymous_region_appears_in_upvars: upvar_ty = {:?}",
446 tcx.any_free_region_meets(&upvar_ty, |r| r.to_region_vid() == fr)
456 "give_name_if_anonymous_region_appears_in_upvars: \
457 found {:?} in upvar {} which has type {:?}",
458 fr, upvar_index, upvar_ty,
461 let region_name = self.synthesize_region_name(counter);
463 let upvar_hir_id = mir.upvar_decls[upvar_index].var_hir_id.assert_crate_local();
464 let upvar_node_id = tcx.hir.hir_to_node_id(upvar_hir_id);
465 let upvar_span = tcx.hir.span(upvar_node_id);
466 let upvar_name = tcx.hir.name(upvar_node_id);
470 "lifetime `{}` appears in the type of `{}`",
471 region_name, upvar_name,
478 /// Check for arguments appearing in the (closure) return type. It
479 /// must be a closure since, in a free fn, such an argument would
480 /// have to either also appear in an argument (if using elision)
481 /// or be early bound (named, not in argument).
482 fn give_name_if_anonymous_region_appears_in_output(
484 tcx: TyCtxt<'_, '_, 'tcx>,
488 diag: &mut DiagnosticBuilder<'_>,
489 ) -> Option<InternedString> {
490 let return_ty = self.universal_regions.unnormalized_output_ty;
492 "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
495 if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
499 let region_name = self.synthesize_region_name(counter);
502 format!("lifetime `{}` appears in return type", region_name),
508 /// Create a synthetic region named `'1`, incrementing the
510 fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
514 Name::intern(&format!("'{:?}", c)).as_interned_str()