]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/resolve_lifetime.rs
New upstream version 1.31.0~beta.4+dfsg1
[rustc.git] / src / librustc / middle / resolve_lifetime.rs
1 // Copyright 2012-2013 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.
4 //
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.
10
11 //! Name resolution for lifetimes.
12 //!
13 //! Name resolution for lifetimes follows MUCH simpler rules than the
14 //! full resolve. For example, lifetime names are never exported or
15 //! used between functions, and they operate in a purely top-down
16 //! way. Therefore we break lifetime name resolution into a separate pass.
17
18 use hir::def::Def;
19 use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
20 use hir::map::Map;
21 use hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName};
22 use ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
23
24 use errors::{Applicability, DiagnosticBuilder};
25 use rustc::lint;
26 use rustc_data_structures::sync::Lrc;
27 use session::Session;
28 use std::borrow::Cow;
29 use std::cell::Cell;
30 use std::mem::replace;
31 use syntax::ast;
32 use syntax::attr;
33 use syntax::ptr::P;
34 use syntax::symbol::keywords;
35 use syntax_pos::Span;
36 use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet};
37
38 use hir::intravisit::{self, NestedVisitorMap, Visitor};
39 use hir::{self, GenericParamKind, LifetimeParamKind};
40
41 /// The origin of a named lifetime definition.
42 ///
43 /// This is used to prevent the usage of in-band lifetimes in `Fn`/`fn` syntax.
44 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
45 pub enum LifetimeDefOrigin {
46 // Explicit binders like `fn foo<'a>(x: &'a u8)` or elided like `impl Foo<&u32>`
47 ExplicitOrElided,
48 // In-band declarations like `fn foo(x: &'a u8)`
49 InBand,
50 // Some kind of erroneous origin
51 Error,
52 }
53
54 impl LifetimeDefOrigin {
55 fn from_param(param: &GenericParam) -> Self {
56 match param.kind {
57 GenericParamKind::Lifetime { kind } => match kind {
58 LifetimeParamKind::InBand => LifetimeDefOrigin::InBand,
59 LifetimeParamKind::Explicit => LifetimeDefOrigin::ExplicitOrElided,
60 LifetimeParamKind::Elided => LifetimeDefOrigin::ExplicitOrElided,
61 LifetimeParamKind::Error => LifetimeDefOrigin::Error,
62 },
63 _ => bug!("expected a lifetime param"),
64 }
65 }
66 }
67
68 // This counts the no of times a lifetime is used
69 #[derive(Clone, Copy, Debug)]
70 pub enum LifetimeUseSet<'tcx> {
71 One(&'tcx hir::Lifetime),
72 Many,
73 }
74
75 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
76 pub enum Region {
77 Static,
78 EarlyBound(
79 /* index */ u32,
80 /* lifetime decl */ DefId,
81 LifetimeDefOrigin,
82 ),
83 LateBound(
84 ty::DebruijnIndex,
85 /* lifetime decl */ DefId,
86 LifetimeDefOrigin,
87 ),
88 LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
89 Free(DefId, /* lifetime decl */ DefId),
90 }
91
92 impl Region {
93 fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam) -> (ParamName, Region) {
94 let i = *index;
95 *index += 1;
96 let def_id = hir_map.local_def_id(param.id);
97 let origin = LifetimeDefOrigin::from_param(param);
98 debug!("Region::early: index={} def_id={:?}", i, def_id);
99 (param.name.modern(), Region::EarlyBound(i, def_id, origin))
100 }
101
102 fn late(hir_map: &Map<'_>, param: &GenericParam) -> (ParamName, Region) {
103 let depth = ty::INNERMOST;
104 let def_id = hir_map.local_def_id(param.id);
105 let origin = LifetimeDefOrigin::from_param(param);
106 debug!(
107 "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
108 param, depth, def_id, origin,
109 );
110 (
111 param.name.modern(),
112 Region::LateBound(depth, def_id, origin),
113 )
114 }
115
116 fn late_anon(index: &Cell<u32>) -> Region {
117 let i = index.get();
118 index.set(i + 1);
119 let depth = ty::INNERMOST;
120 Region::LateBoundAnon(depth, i)
121 }
122
123 fn id(&self) -> Option<DefId> {
124 match *self {
125 Region::Static | Region::LateBoundAnon(..) => None,
126
127 Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
128 Some(id)
129 }
130 }
131 }
132
133 fn shifted(self, amount: u32) -> Region {
134 match self {
135 Region::LateBound(debruijn, id, origin) => {
136 Region::LateBound(debruijn.shifted_in(amount), id, origin)
137 }
138 Region::LateBoundAnon(debruijn, index) => {
139 Region::LateBoundAnon(debruijn.shifted_in(amount), index)
140 }
141 _ => self,
142 }
143 }
144
145 fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
146 match self {
147 Region::LateBound(debruijn, id, origin) => {
148 Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
149 }
150 Region::LateBoundAnon(debruijn, index) => {
151 Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
152 }
153 _ => self,
154 }
155 }
156
157 fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
158 where
159 L: Iterator<Item = &'a hir::Lifetime>,
160 {
161 if let Region::EarlyBound(index, _, _) = self {
162 params
163 .nth(index as usize)
164 .and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
165 } else {
166 Some(self)
167 }
168 }
169 }
170
171 /// A set containing, at most, one known element.
172 /// If two distinct values are inserted into a set, then it
173 /// becomes `Many`, which can be used to detect ambiguities.
174 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
175 pub enum Set1<T> {
176 Empty,
177 One(T),
178 Many,
179 }
180
181 impl<T: PartialEq> Set1<T> {
182 pub fn insert(&mut self, value: T) {
183 if let Set1::Empty = *self {
184 *self = Set1::One(value);
185 return;
186 }
187 if let Set1::One(ref old) = *self {
188 if *old == value {
189 return;
190 }
191 }
192 *self = Set1::Many;
193 }
194 }
195
196 pub type ObjectLifetimeDefault = Set1<Region>;
197
198 /// Maps the id of each lifetime reference to the lifetime decl
199 /// that it corresponds to.
200 ///
201 /// FIXME. This struct gets converted to a `ResolveLifetimes` for
202 /// actual use. It has the same data, but indexed by `DefIndex`. This
203 /// is silly.
204 #[derive(Default)]
205 struct NamedRegionMap {
206 // maps from every use of a named (not anonymous) lifetime to a
207 // `Region` describing how that region is bound
208 pub defs: NodeMap<Region>,
209
210 // the set of lifetime def ids that are late-bound; a region can
211 // be late-bound if (a) it does NOT appear in a where-clause and
212 // (b) it DOES appear in the arguments.
213 pub late_bound: NodeSet,
214
215 // For each type and trait definition, maps type parameters
216 // to the trait object lifetime defaults computed from them.
217 pub object_lifetime_defaults: NodeMap<Vec<ObjectLifetimeDefault>>,
218 }
219
220 /// See `NamedRegionMap`.
221 #[derive(Default)]
222 pub struct ResolveLifetimes {
223 defs: FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Region>>>,
224 late_bound: FxHashMap<LocalDefId, Lrc<FxHashSet<ItemLocalId>>>,
225 object_lifetime_defaults:
226 FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Lrc<Vec<ObjectLifetimeDefault>>>>>,
227 }
228
229 impl_stable_hash_for!(struct ::middle::resolve_lifetime::ResolveLifetimes {
230 defs,
231 late_bound,
232 object_lifetime_defaults
233 });
234
235 struct LifetimeContext<'a, 'tcx: 'a> {
236 tcx: TyCtxt<'a, 'tcx, 'tcx>,
237 map: &'a mut NamedRegionMap,
238 scope: ScopeRef<'a>,
239
240 /// Deep breath. Our representation for poly trait refs contains a single
241 /// binder and thus we only allow a single level of quantification. However,
242 /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
243 /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
244 /// correct when representing these constraints, we should only introduce one
245 /// scope. However, we want to support both locations for the quantifier and
246 /// during lifetime resolution we want precise information (so we can't
247 /// desugar in an earlier phase).
248 ///
249 /// SO, if we encounter a quantifier at the outer scope, we set
250 /// trait_ref_hack to true (and introduce a scope), and then if we encounter
251 /// a quantifier at the inner scope, we error. If trait_ref_hack is false,
252 /// then we introduce the scope at the inner quantifier.
253 ///
254 /// I'm sorry.
255 trait_ref_hack: bool,
256
257 /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
258 is_in_fn_syntax: bool,
259
260 /// List of labels in the function/method currently under analysis.
261 labels_in_fn: Vec<ast::Ident>,
262
263 /// Cache for cross-crate per-definition object lifetime defaults.
264 xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
265
266 lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
267 }
268
269 #[derive(Debug)]
270 enum Scope<'a> {
271 /// Declares lifetimes, and each can be early-bound or late-bound.
272 /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
273 /// it should be shifted by the number of `Binder`s in between the
274 /// declaration `Binder` and the location it's referenced from.
275 Binder {
276 lifetimes: FxHashMap<hir::ParamName, Region>,
277
278 /// if we extend this scope with another scope, what is the next index
279 /// we should use for an early-bound region?
280 next_early_index: u32,
281
282 /// Flag is set to true if, in this binder, `'_` would be
283 /// equivalent to a "single-use region". This is true on
284 /// impls, but not other kinds of items.
285 track_lifetime_uses: bool,
286
287 /// Whether or not this binder would serve as the parent
288 /// binder for abstract types introduced within. For example:
289 ///
290 /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
291 ///
292 /// Here, the abstract types we create for the `impl Trait`
293 /// and `impl Trait2` references will both have the `foo` item
294 /// as their parent. When we get to `impl Trait2`, we find
295 /// that it is nested within the `for<>` binder -- this flag
296 /// allows us to skip that when looking for the parent binder
297 /// of the resulting abstract type.
298 abstract_type_parent: bool,
299
300 s: ScopeRef<'a>,
301 },
302
303 /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
304 /// if this is a fn body, otherwise the original definitions are used.
305 /// Unspecified lifetimes are inferred, unless an elision scope is nested,
306 /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
307 Body {
308 id: hir::BodyId,
309 s: ScopeRef<'a>,
310 },
311
312 /// A scope which either determines unspecified lifetimes or errors
313 /// on them (e.g. due to ambiguity). For more details, see `Elide`.
314 Elision {
315 elide: Elide,
316 s: ScopeRef<'a>,
317 },
318
319 /// Use a specific lifetime (if `Some`) or leave it unset (to be
320 /// inferred in a function body or potentially error outside one),
321 /// for the default choice of lifetime in a trait object type.
322 ObjectLifetimeDefault {
323 lifetime: Option<Region>,
324 s: ScopeRef<'a>,
325 },
326
327 Root,
328 }
329
330 #[derive(Clone, Debug)]
331 enum Elide {
332 /// Use a fresh anonymous late-bound lifetime each time, by
333 /// incrementing the counter to generate sequential indices.
334 FreshLateAnon(Cell<u32>),
335 /// Always use this one lifetime.
336 Exact(Region),
337 /// Less or more than one lifetime were found, error on unspecified.
338 Error(Vec<ElisionFailureInfo>),
339 }
340
341 #[derive(Clone, Debug)]
342 struct ElisionFailureInfo {
343 /// Where we can find the argument pattern.
344 parent: Option<hir::BodyId>,
345 /// The index of the argument in the original definition.
346 index: usize,
347 lifetime_count: usize,
348 have_bound_regions: bool,
349 }
350
351 type ScopeRef<'a> = &'a Scope<'a>;
352
353 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
354
355 pub fn provide(providers: &mut ty::query::Providers<'_>) {
356 *providers = ty::query::Providers {
357 resolve_lifetimes,
358
359 named_region_map: |tcx, id| {
360 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
361 tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id).cloned()
362 },
363
364 is_late_bound_map: |tcx, id| {
365 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
366 tcx.resolve_lifetimes(LOCAL_CRATE)
367 .late_bound
368 .get(&id)
369 .cloned()
370 },
371
372 object_lifetime_defaults_map: |tcx, id| {
373 let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
374 tcx.resolve_lifetimes(LOCAL_CRATE)
375 .object_lifetime_defaults
376 .get(&id)
377 .cloned()
378 },
379
380 ..*providers
381 };
382
383 // (*) FIXME the query should be defined to take a LocalDefId
384 }
385
386 /// Computes the `ResolveLifetimes` map that contains data for the
387 /// entire crate. You should not read the result of this query
388 /// directly, but rather use `named_region_map`, `is_late_bound_map`,
389 /// etc.
390 fn resolve_lifetimes<'tcx>(
391 tcx: TyCtxt<'_, 'tcx, 'tcx>,
392 for_krate: CrateNum,
393 ) -> Lrc<ResolveLifetimes> {
394 assert_eq!(for_krate, LOCAL_CRATE);
395
396 let named_region_map = krate(tcx);
397
398 let mut rl = ResolveLifetimes::default();
399
400 for (k, v) in named_region_map.defs {
401 let hir_id = tcx.hir.node_to_hir_id(k);
402 let map = rl.defs.entry(hir_id.owner_local_def_id()).or_default();
403 Lrc::get_mut(map).unwrap().insert(hir_id.local_id, v);
404 }
405 for k in named_region_map.late_bound {
406 let hir_id = tcx.hir.node_to_hir_id(k);
407 let map = rl.late_bound
408 .entry(hir_id.owner_local_def_id())
409 .or_default();
410 Lrc::get_mut(map).unwrap().insert(hir_id.local_id);
411 }
412 for (k, v) in named_region_map.object_lifetime_defaults {
413 let hir_id = tcx.hir.node_to_hir_id(k);
414 let map = rl.object_lifetime_defaults
415 .entry(hir_id.owner_local_def_id())
416 .or_default();
417 Lrc::get_mut(map)
418 .unwrap()
419 .insert(hir_id.local_id, Lrc::new(v));
420 }
421
422 Lrc::new(rl)
423 }
424
425 fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> NamedRegionMap {
426 let krate = tcx.hir.krate();
427 let mut map = NamedRegionMap {
428 defs: NodeMap(),
429 late_bound: NodeSet(),
430 object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
431 };
432 {
433 let mut visitor = LifetimeContext {
434 tcx,
435 map: &mut map,
436 scope: ROOT_SCOPE,
437 trait_ref_hack: false,
438 is_in_fn_syntax: false,
439 labels_in_fn: vec![],
440 xcrate_object_lifetime_defaults: DefIdMap(),
441 lifetime_uses: &mut DefIdMap(),
442 };
443 for (_, item) in &krate.items {
444 visitor.visit_item(item);
445 }
446 }
447 map
448 }
449
450 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
451 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
452 NestedVisitorMap::All(&self.tcx.hir)
453 }
454
455 // We want to nest trait/impl items in their parent, but nothing else.
456 fn visit_nested_item(&mut self, _: hir::ItemId) {}
457
458 fn visit_nested_body(&mut self, body: hir::BodyId) {
459 // Each body has their own set of labels, save labels.
460 let saved = replace(&mut self.labels_in_fn, vec![]);
461 let body = self.tcx.hir.body(body);
462 extract_labels(self, body);
463 self.with(
464 Scope::Body {
465 id: body.id(),
466 s: self.scope,
467 },
468 |_, this| {
469 this.visit_body(body);
470 },
471 );
472 replace(&mut self.labels_in_fn, saved);
473 }
474
475 fn visit_item(&mut self, item: &'tcx hir::Item) {
476 match item.node {
477 hir::ItemKind::Fn(ref decl, _, ref generics, _) => {
478 self.visit_early_late(None, decl, generics, |this| {
479 intravisit::walk_item(this, item);
480 });
481 }
482
483 hir::ItemKind::ExternCrate(_)
484 | hir::ItemKind::Use(..)
485 | hir::ItemKind::Mod(..)
486 | hir::ItemKind::ForeignMod(..)
487 | hir::ItemKind::GlobalAsm(..) => {
488 // These sorts of items have no lifetime parameters at all.
489 intravisit::walk_item(self, item);
490 }
491 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
492 // No lifetime parameters, but implied 'static.
493 let scope = Scope::Elision {
494 elide: Elide::Exact(Region::Static),
495 s: ROOT_SCOPE,
496 };
497 self.with(scope, |_, this| intravisit::walk_item(this, item));
498 }
499 hir::ItemKind::Existential(hir::ExistTy {
500 impl_trait_fn: Some(_),
501 ..
502 }) => {
503 // currently existential type declarations are just generated from impl Trait
504 // items. doing anything on this node is irrelevant, as we currently don't need
505 // it.
506 }
507 hir::ItemKind::Ty(_, ref generics)
508 | hir::ItemKind::Existential(hir::ExistTy {
509 impl_trait_fn: None,
510 ref generics,
511 ..
512 })
513 | hir::ItemKind::Enum(_, ref generics)
514 | hir::ItemKind::Struct(_, ref generics)
515 | hir::ItemKind::Union(_, ref generics)
516 | hir::ItemKind::Trait(_, _, ref generics, ..)
517 | hir::ItemKind::TraitAlias(ref generics, ..)
518 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
519 // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
520 // This is not true for other kinds of items.x
521 let track_lifetime_uses = match item.node {
522 hir::ItemKind::Impl(..) => true,
523 _ => false,
524 };
525 // These kinds of items have only early bound lifetime parameters.
526 let mut index = if let hir::ItemKind::Trait(..) = item.node {
527 1 // Self comes before lifetimes
528 } else {
529 0
530 };
531 let mut type_count = 0;
532 let lifetimes = generics
533 .params
534 .iter()
535 .filter_map(|param| match param.kind {
536 GenericParamKind::Lifetime { .. } => {
537 Some(Region::early(&self.tcx.hir, &mut index, param))
538 }
539 GenericParamKind::Type { .. } => {
540 type_count += 1;
541 None
542 }
543 })
544 .collect();
545 let scope = Scope::Binder {
546 lifetimes,
547 next_early_index: index + type_count,
548 abstract_type_parent: true,
549 track_lifetime_uses,
550 s: ROOT_SCOPE,
551 };
552 self.with(scope, |old_scope, this| {
553 this.check_lifetime_params(old_scope, &generics.params);
554 intravisit::walk_item(this, item);
555 });
556 }
557 }
558 }
559
560 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
561 match item.node {
562 hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
563 self.visit_early_late(None, decl, generics, |this| {
564 intravisit::walk_foreign_item(this, item);
565 })
566 }
567 hir::ForeignItemKind::Static(..) => {
568 intravisit::walk_foreign_item(self, item);
569 }
570 hir::ForeignItemKind::Type => {
571 intravisit::walk_foreign_item(self, item);
572 }
573 }
574 }
575
576 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
577 debug!("visit_ty: id={:?} ty={:?}", ty.id, ty);
578 match ty.node {
579 hir::TyKind::BareFn(ref c) => {
580 let next_early_index = self.next_early_index();
581 let was_in_fn_syntax = self.is_in_fn_syntax;
582 self.is_in_fn_syntax = true;
583 let scope = Scope::Binder {
584 lifetimes: c.generic_params
585 .iter()
586 .filter_map(|param| match param.kind {
587 GenericParamKind::Lifetime { .. } => {
588 Some(Region::late(&self.tcx.hir, param))
589 }
590 _ => None,
591 })
592 .collect(),
593 s: self.scope,
594 next_early_index,
595 track_lifetime_uses: true,
596 abstract_type_parent: false,
597 };
598 self.with(scope, |old_scope, this| {
599 // a bare fn has no bounds, so everything
600 // contained within is scoped within its binder.
601 this.check_lifetime_params(old_scope, &c.generic_params);
602 intravisit::walk_ty(this, ty);
603 });
604 self.is_in_fn_syntax = was_in_fn_syntax;
605 }
606 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
607 for bound in bounds {
608 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
609 }
610 match lifetime.name {
611 LifetimeName::Implicit => {
612 // If the user does not write *anything*, we
613 // use the object lifetime defaulting
614 // rules. So e.g. `Box<dyn Debug>` becomes
615 // `Box<dyn Debug + 'static>`.
616 self.resolve_object_lifetime_default(lifetime)
617 }
618 LifetimeName::Underscore => {
619 // If the user writes `'_`, we use the *ordinary* elision
620 // rules. So the `'_` in e.g. `Box<dyn Debug + '_>` will be
621 // resolved the same as the `'_` in `&'_ Foo`.
622 //
623 // cc #48468
624 self.resolve_elided_lifetimes(vec![lifetime])
625 }
626 LifetimeName::Param(_) | LifetimeName::Static => {
627 // If the user wrote an explicit name, use that.
628 self.visit_lifetime(lifetime);
629 }
630 LifetimeName::Error => {}
631 }
632 }
633 hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
634 self.visit_lifetime(lifetime_ref);
635 let scope = Scope::ObjectLifetimeDefault {
636 lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
637 s: self.scope,
638 };
639 self.with(scope, |_, this| this.visit_ty(&mt.ty));
640 }
641 hir::TyKind::Def(item_id, ref lifetimes) => {
642 // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
643 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
644 // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
645 // ^ ^ this gets resolved in the scope of
646 // the exist_ty generics
647 let (generics, bounds) = match self.tcx.hir.expect_item(item_id.id).node {
648 // named existential types are reached via TyKind::Path
649 // this arm is for `impl Trait` in the types of statics, constants and locals
650 hir::ItemKind::Existential(hir::ExistTy {
651 impl_trait_fn: None,
652 ..
653 }) => {
654 intravisit::walk_ty(self, ty);
655 return;
656 }
657 // RPIT (return position impl trait)
658 hir::ItemKind::Existential(hir::ExistTy {
659 ref generics,
660 ref bounds,
661 ..
662 }) => (generics, bounds),
663 ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
664 };
665
666 // Resolve the lifetimes that are applied to the existential type.
667 // These are resolved in the current scope.
668 // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
669 // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
670 // ^ ^this gets resolved in the current scope
671 for lifetime in lifetimes {
672 if let hir::GenericArg::Lifetime(lifetime) = lifetime {
673 self.visit_lifetime(lifetime);
674
675 // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
676 // and ban them. Type variables instantiated inside binders aren't
677 // well-supported at the moment, so this doesn't work.
678 // In the future, this should be fixed and this error should be removed.
679 let def = self.map.defs.get(&lifetime.id).cloned();
680 if let Some(Region::LateBound(_, def_id, _)) = def {
681 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
682 // Ensure that the parent of the def is an item, not HRTB
683 let parent_id = self.tcx.hir.get_parent_node(node_id);
684 let parent_impl_id = hir::ImplItemId { node_id: parent_id };
685 let parent_trait_id = hir::TraitItemId { node_id: parent_id };
686 let krate = self.tcx.hir.forest.krate();
687 if !(krate.items.contains_key(&parent_id)
688 || krate.impl_items.contains_key(&parent_impl_id)
689 || krate.trait_items.contains_key(&parent_trait_id))
690 {
691 span_err!(
692 self.tcx.sess,
693 lifetime.span,
694 E0657,
695 "`impl Trait` can only capture lifetimes \
696 bound at the fn or impl level"
697 );
698 self.uninsert_lifetime_on_error(lifetime, def.unwrap());
699 }
700 }
701 }
702 }
703 }
704
705 // We want to start our early-bound indices at the end of the parent scope,
706 // not including any parent `impl Trait`s.
707 let mut index = self.next_early_index_for_abstract_type();
708 debug!("visit_ty: index = {}", index);
709
710 let mut elision = None;
711 let mut lifetimes = FxHashMap::default();
712 let mut type_count = 0;
713 for param in &generics.params {
714 match param.kind {
715 GenericParamKind::Lifetime { .. } => {
716 let (name, reg) = Region::early(&self.tcx.hir, &mut index, &param);
717 if let hir::ParamName::Plain(param_name) = name {
718 if param_name.name == keywords::UnderscoreLifetime.name() {
719 // Pick the elided lifetime "definition" if one exists
720 // and use it to make an elision scope.
721 elision = Some(reg);
722 } else {
723 lifetimes.insert(name, reg);
724 }
725 } else {
726 lifetimes.insert(name, reg);
727 }
728 }
729 GenericParamKind::Type { .. } => {
730 type_count += 1;
731 }
732 }
733 }
734 let next_early_index = index + type_count;
735
736 if let Some(elision_region) = elision {
737 let scope = Scope::Elision {
738 elide: Elide::Exact(elision_region),
739 s: self.scope,
740 };
741 self.with(scope, |_old_scope, this| {
742 let scope = Scope::Binder {
743 lifetimes,
744 next_early_index,
745 s: this.scope,
746 track_lifetime_uses: true,
747 abstract_type_parent: false,
748 };
749 this.with(scope, |_old_scope, this| {
750 this.visit_generics(generics);
751 for bound in bounds {
752 this.visit_param_bound(bound);
753 }
754 });
755 });
756 } else {
757 let scope = Scope::Binder {
758 lifetimes,
759 next_early_index,
760 s: self.scope,
761 track_lifetime_uses: true,
762 abstract_type_parent: false,
763 };
764 self.with(scope, |_old_scope, this| {
765 this.visit_generics(generics);
766 for bound in bounds {
767 this.visit_param_bound(bound);
768 }
769 });
770 }
771 }
772 _ => intravisit::walk_ty(self, ty),
773 }
774 }
775
776 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
777 use self::hir::TraitItemKind::*;
778 match trait_item.node {
779 Method(ref sig, _) => {
780 let tcx = self.tcx;
781 self.visit_early_late(
782 Some(tcx.hir.get_parent(trait_item.id)),
783 &sig.decl,
784 &trait_item.generics,
785 |this| intravisit::walk_trait_item(this, trait_item),
786 );
787 }
788 Type(ref bounds, ref ty) => {
789 let generics = &trait_item.generics;
790 let mut index = self.next_early_index();
791 debug!("visit_ty: index = {}", index);
792 let mut type_count = 0;
793 let lifetimes = generics
794 .params
795 .iter()
796 .filter_map(|param| match param.kind {
797 GenericParamKind::Lifetime { .. } => {
798 Some(Region::early(&self.tcx.hir, &mut index, param))
799 }
800 GenericParamKind::Type { .. } => {
801 type_count += 1;
802 None
803 }
804 })
805 .collect();
806 let scope = Scope::Binder {
807 lifetimes,
808 next_early_index: index + type_count,
809 s: self.scope,
810 track_lifetime_uses: true,
811 abstract_type_parent: true,
812 };
813 self.with(scope, |_old_scope, this| {
814 this.visit_generics(generics);
815 for bound in bounds {
816 this.visit_param_bound(bound);
817 }
818 if let Some(ty) = ty {
819 this.visit_ty(ty);
820 }
821 });
822 }
823 Const(_, _) => {
824 // Only methods and types support generics.
825 assert!(trait_item.generics.params.is_empty());
826 intravisit::walk_trait_item(self, trait_item);
827 }
828 }
829 }
830
831 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
832 use self::hir::ImplItemKind::*;
833 match impl_item.node {
834 Method(ref sig, _) => {
835 let tcx = self.tcx;
836 self.visit_early_late(
837 Some(tcx.hir.get_parent(impl_item.id)),
838 &sig.decl,
839 &impl_item.generics,
840 |this| intravisit::walk_impl_item(this, impl_item),
841 )
842 }
843 Type(ref ty) => {
844 let generics = &impl_item.generics;
845 let mut index = self.next_early_index();
846 let mut next_early_index = index;
847 debug!("visit_ty: index = {}", index);
848 let lifetimes = generics
849 .params
850 .iter()
851 .filter_map(|param| match param.kind {
852 GenericParamKind::Lifetime { .. } => {
853 Some(Region::early(&self.tcx.hir, &mut index, param))
854 }
855 GenericParamKind::Type { .. } => {
856 next_early_index += 1;
857 None
858 }
859 })
860 .collect();
861 let scope = Scope::Binder {
862 lifetimes,
863 next_early_index,
864 s: self.scope,
865 track_lifetime_uses: true,
866 abstract_type_parent: true,
867 };
868 self.with(scope, |_old_scope, this| {
869 this.visit_generics(generics);
870 this.visit_ty(ty);
871 });
872 }
873 Existential(ref bounds) => {
874 let generics = &impl_item.generics;
875 let mut index = self.next_early_index();
876 let mut next_early_index = index;
877 debug!("visit_ty: index = {}", index);
878 let lifetimes = generics
879 .params
880 .iter()
881 .filter_map(|param| match param.kind {
882 GenericParamKind::Lifetime { .. } => {
883 Some(Region::early(&self.tcx.hir, &mut index, param))
884 }
885 GenericParamKind::Type { .. } => {
886 next_early_index += 1;
887 None
888 }
889 })
890 .collect();
891
892 let scope = Scope::Binder {
893 lifetimes,
894 next_early_index,
895 s: self.scope,
896 track_lifetime_uses: true,
897 abstract_type_parent: true,
898 };
899 self.with(scope, |_old_scope, this| {
900 this.visit_generics(generics);
901 for bound in bounds {
902 this.visit_param_bound(bound);
903 }
904 });
905 }
906 Const(_, _) => {
907 // Only methods and types support generics.
908 assert!(impl_item.generics.params.is_empty());
909 intravisit::walk_impl_item(self, impl_item);
910 }
911 }
912 }
913
914 fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
915 if lifetime_ref.is_elided() {
916 self.resolve_elided_lifetimes(vec![lifetime_ref]);
917 return;
918 }
919 if lifetime_ref.is_static() {
920 self.insert_lifetime(lifetime_ref, Region::Static);
921 return;
922 }
923 self.resolve_lifetime_ref(lifetime_ref);
924 }
925
926 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
927 for (i, segment) in path.segments.iter().enumerate() {
928 let depth = path.segments.len() - i - 1;
929 if let Some(ref args) = segment.args {
930 self.visit_segment_args(path.def, depth, args);
931 }
932 }
933 }
934
935 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
936 let output = match fd.output {
937 hir::DefaultReturn(_) => None,
938 hir::Return(ref ty) => Some(ty),
939 };
940 self.visit_fn_like_elision(&fd.inputs, output);
941 }
942
943 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
944 check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
945 for param in &generics.params {
946 match param.kind {
947 GenericParamKind::Lifetime { .. } => {}
948 GenericParamKind::Type { ref default, .. } => {
949 walk_list!(self, visit_param_bound, &param.bounds);
950 if let Some(ref ty) = default {
951 self.visit_ty(&ty);
952 }
953 }
954 }
955 }
956 for predicate in &generics.where_clause.predicates {
957 match predicate {
958 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
959 ref bounded_ty,
960 ref bounds,
961 ref bound_generic_params,
962 ..
963 }) => {
964 let lifetimes: FxHashMap<_, _> = bound_generic_params
965 .iter()
966 .filter_map(|param| match param.kind {
967 GenericParamKind::Lifetime { .. } => {
968 Some(Region::late(&self.tcx.hir, param))
969 }
970 _ => None,
971 })
972 .collect();
973 if !lifetimes.is_empty() {
974 self.trait_ref_hack = true;
975 let next_early_index = self.next_early_index();
976 let scope = Scope::Binder {
977 lifetimes,
978 s: self.scope,
979 next_early_index,
980 track_lifetime_uses: true,
981 abstract_type_parent: false,
982 };
983 let result = self.with(scope, |old_scope, this| {
984 this.check_lifetime_params(old_scope, &bound_generic_params);
985 this.visit_ty(&bounded_ty);
986 walk_list!(this, visit_param_bound, bounds);
987 });
988 self.trait_ref_hack = false;
989 result
990 } else {
991 self.visit_ty(&bounded_ty);
992 walk_list!(self, visit_param_bound, bounds);
993 }
994 }
995 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
996 ref lifetime,
997 ref bounds,
998 ..
999 }) => {
1000 self.visit_lifetime(lifetime);
1001 walk_list!(self, visit_param_bound, bounds);
1002 }
1003 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1004 ref lhs_ty,
1005 ref rhs_ty,
1006 ..
1007 }) => {
1008 self.visit_ty(lhs_ty);
1009 self.visit_ty(rhs_ty);
1010 }
1011 }
1012 }
1013 }
1014
1015 fn visit_poly_trait_ref(
1016 &mut self,
1017 trait_ref: &'tcx hir::PolyTraitRef,
1018 _modifier: hir::TraitBoundModifier,
1019 ) {
1020 debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
1021
1022 if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| {
1023 match param.kind {
1024 GenericParamKind::Lifetime { .. } => true,
1025 _ => false,
1026 }
1027 }) {
1028 if self.trait_ref_hack {
1029 span_err!(
1030 self.tcx.sess,
1031 trait_ref.span,
1032 E0316,
1033 "nested quantification of lifetimes"
1034 );
1035 }
1036 let next_early_index = self.next_early_index();
1037 let scope = Scope::Binder {
1038 lifetimes: trait_ref
1039 .bound_generic_params
1040 .iter()
1041 .filter_map(|param| match param.kind {
1042 GenericParamKind::Lifetime { .. } => {
1043 Some(Region::late(&self.tcx.hir, param))
1044 }
1045 _ => None,
1046 })
1047 .collect(),
1048 s: self.scope,
1049 next_early_index,
1050 track_lifetime_uses: true,
1051 abstract_type_parent: false,
1052 };
1053 self.with(scope, |old_scope, this| {
1054 this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
1055 walk_list!(this, visit_generic_param, &trait_ref.bound_generic_params);
1056 this.visit_trait_ref(&trait_ref.trait_ref)
1057 })
1058 } else {
1059 self.visit_trait_ref(&trait_ref.trait_ref)
1060 }
1061 }
1062 }
1063
1064 #[derive(Copy, Clone, PartialEq)]
1065 enum ShadowKind {
1066 Label,
1067 Lifetime,
1068 }
1069 struct Original {
1070 kind: ShadowKind,
1071 span: Span,
1072 }
1073 struct Shadower {
1074 kind: ShadowKind,
1075 span: Span,
1076 }
1077
1078 fn original_label(span: Span) -> Original {
1079 Original {
1080 kind: ShadowKind::Label,
1081 span: span,
1082 }
1083 }
1084 fn shadower_label(span: Span) -> Shadower {
1085 Shadower {
1086 kind: ShadowKind::Label,
1087 span: span,
1088 }
1089 }
1090 fn original_lifetime(span: Span) -> Original {
1091 Original {
1092 kind: ShadowKind::Lifetime,
1093 span: span,
1094 }
1095 }
1096 fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
1097 Shadower {
1098 kind: ShadowKind::Lifetime,
1099 span: param.span,
1100 }
1101 }
1102
1103 impl ShadowKind {
1104 fn desc(&self) -> &'static str {
1105 match *self {
1106 ShadowKind::Label => "label",
1107 ShadowKind::Lifetime => "lifetime",
1108 }
1109 }
1110 }
1111
1112 fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_, '_, '_>, params: &P<[hir::GenericParam]>) {
1113 let lifetime_params: Vec<_> = params
1114 .iter()
1115 .filter_map(|param| match param.kind {
1116 GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
1117 _ => None,
1118 })
1119 .collect();
1120 let explicit = lifetime_params
1121 .iter()
1122 .find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
1123 let in_band = lifetime_params
1124 .iter()
1125 .find(|(kind, _)| *kind == LifetimeParamKind::InBand);
1126
1127 if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
1128 struct_span_err!(
1129 tcx.sess,
1130 *in_band_span,
1131 E0688,
1132 "cannot mix in-band and explicit lifetime definitions"
1133 ).span_label(*in_band_span, "in-band lifetime definition here")
1134 .span_label(*explicit_span, "explicit lifetime definition here")
1135 .emit();
1136 }
1137 }
1138
1139 fn signal_shadowing_problem(
1140 tcx: TyCtxt<'_, '_, '_>,
1141 name: ast::Name,
1142 orig: Original,
1143 shadower: Shadower,
1144 ) {
1145 let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
1146 // lifetime/lifetime shadowing is an error
1147 struct_span_err!(
1148 tcx.sess,
1149 shadower.span,
1150 E0496,
1151 "{} name `{}` shadows a \
1152 {} name that is already in scope",
1153 shadower.kind.desc(),
1154 name,
1155 orig.kind.desc()
1156 )
1157 } else {
1158 // shadowing involving a label is only a warning, due to issues with
1159 // labels and lifetimes not being macro-hygienic.
1160 tcx.sess.struct_span_warn(
1161 shadower.span,
1162 &format!(
1163 "{} name `{}` shadows a \
1164 {} name that is already in scope",
1165 shadower.kind.desc(),
1166 name,
1167 orig.kind.desc()
1168 ),
1169 )
1170 };
1171 err.span_label(orig.span, "first declared here");
1172 err.span_label(shadower.span, format!("lifetime {} already in scope", name));
1173 err.emit();
1174 }
1175
1176 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
1177 // if one of the label shadows a lifetime or another label.
1178 fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
1179 struct GatherLabels<'a, 'tcx: 'a> {
1180 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1181 scope: ScopeRef<'a>,
1182 labels_in_fn: &'a mut Vec<ast::Ident>,
1183 }
1184
1185 let mut gather = GatherLabels {
1186 tcx: ctxt.tcx,
1187 scope: ctxt.scope,
1188 labels_in_fn: &mut ctxt.labels_in_fn,
1189 };
1190 gather.visit_body(body);
1191
1192 impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
1193 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1194 NestedVisitorMap::None
1195 }
1196
1197 fn visit_expr(&mut self, ex: &hir::Expr) {
1198 if let Some(label) = expression_label(ex) {
1199 for prior_label in &self.labels_in_fn[..] {
1200 // FIXME (#24278): non-hygienic comparison
1201 if label.name == prior_label.name {
1202 signal_shadowing_problem(
1203 self.tcx,
1204 label.name,
1205 original_label(prior_label.span),
1206 shadower_label(label.span),
1207 );
1208 }
1209 }
1210
1211 check_if_label_shadows_lifetime(self.tcx, self.scope, label);
1212
1213 self.labels_in_fn.push(label);
1214 }
1215 intravisit::walk_expr(self, ex)
1216 }
1217 }
1218
1219 fn expression_label(ex: &hir::Expr) -> Option<ast::Ident> {
1220 match ex.node {
1221 hir::ExprKind::While(.., Some(label)) | hir::ExprKind::Loop(_, Some(label), _) => {
1222 Some(label.ident)
1223 }
1224 _ => None,
1225 }
1226 }
1227
1228 fn check_if_label_shadows_lifetime(
1229 tcx: TyCtxt<'_, '_, '_>,
1230 mut scope: ScopeRef<'_>,
1231 label: ast::Ident,
1232 ) {
1233 loop {
1234 match *scope {
1235 Scope::Body { s, .. }
1236 | Scope::Elision { s, .. }
1237 | Scope::ObjectLifetimeDefault { s, .. } => {
1238 scope = s;
1239 }
1240
1241 Scope::Root => {
1242 return;
1243 }
1244
1245 Scope::Binder {
1246 ref lifetimes, s, ..
1247 } => {
1248 // FIXME (#24278): non-hygienic comparison
1249 if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
1250 let node_id = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
1251
1252 signal_shadowing_problem(
1253 tcx,
1254 label.name,
1255 original_lifetime(tcx.hir.span(node_id)),
1256 shadower_label(label.span),
1257 );
1258 return;
1259 }
1260 scope = s;
1261 }
1262 }
1263 }
1264 }
1265 }
1266
1267 fn compute_object_lifetime_defaults(
1268 tcx: TyCtxt<'_, '_, '_>,
1269 ) -> NodeMap<Vec<ObjectLifetimeDefault>> {
1270 let mut map = NodeMap();
1271 for item in tcx.hir.krate().items.values() {
1272 match item.node {
1273 hir::ItemKind::Struct(_, ref generics)
1274 | hir::ItemKind::Union(_, ref generics)
1275 | hir::ItemKind::Enum(_, ref generics)
1276 | hir::ItemKind::Existential(hir::ExistTy {
1277 ref generics,
1278 impl_trait_fn: None,
1279 ..
1280 })
1281 | hir::ItemKind::Ty(_, ref generics)
1282 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1283 let result = object_lifetime_defaults_for_item(tcx, generics);
1284
1285 // Debugging aid.
1286 if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
1287 let object_lifetime_default_reprs: String = result
1288 .iter()
1289 .map(|set| match *set {
1290 Set1::Empty => "BaseDefault".into(),
1291 Set1::One(Region::Static) => "'static".into(),
1292 Set1::One(Region::EarlyBound(mut i, _, _)) => generics
1293 .params
1294 .iter()
1295 .find_map(|param| match param.kind {
1296 GenericParamKind::Lifetime { .. } => {
1297 if i == 0 {
1298 return Some(param.name.ident().to_string().into());
1299 }
1300 i -= 1;
1301 None
1302 }
1303 _ => None,
1304 })
1305 .unwrap(),
1306 Set1::One(_) => bug!(),
1307 Set1::Many => "Ambiguous".into(),
1308 })
1309 .collect::<Vec<Cow<'static, str>>>()
1310 .join(",");
1311 tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
1312 }
1313
1314 map.insert(item.id, result);
1315 }
1316 _ => {}
1317 }
1318 }
1319 map
1320 }
1321
1322 /// Scan the bounds and where-clauses on parameters to extract bounds
1323 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
1324 /// for each type parameter.
1325 fn object_lifetime_defaults_for_item(
1326 tcx: TyCtxt<'_, '_, '_>,
1327 generics: &hir::Generics,
1328 ) -> Vec<ObjectLifetimeDefault> {
1329 fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
1330 for bound in bounds {
1331 if let hir::GenericBound::Outlives(ref lifetime) = *bound {
1332 set.insert(lifetime.name.modern());
1333 }
1334 }
1335 }
1336
1337 generics
1338 .params
1339 .iter()
1340 .filter_map(|param| match param.kind {
1341 GenericParamKind::Lifetime { .. } => None,
1342 GenericParamKind::Type { .. } => {
1343 let mut set = Set1::Empty;
1344
1345 add_bounds(&mut set, &param.bounds);
1346
1347 let param_def_id = tcx.hir.local_def_id(param.id);
1348 for predicate in &generics.where_clause.predicates {
1349 // Look for `type: ...` where clauses.
1350 let data = match *predicate {
1351 hir::WherePredicate::BoundPredicate(ref data) => data,
1352 _ => continue,
1353 };
1354
1355 // Ignore `for<'a> type: ...` as they can change what
1356 // lifetimes mean (although we could "just" handle it).
1357 if !data.bound_generic_params.is_empty() {
1358 continue;
1359 }
1360
1361 let def = match data.bounded_ty.node {
1362 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.def,
1363 _ => continue,
1364 };
1365
1366 if def == Def::TyParam(param_def_id) {
1367 add_bounds(&mut set, &data.bounds);
1368 }
1369 }
1370
1371 Some(match set {
1372 Set1::Empty => Set1::Empty,
1373 Set1::One(name) => {
1374 if name == hir::LifetimeName::Static {
1375 Set1::One(Region::Static)
1376 } else {
1377 generics
1378 .params
1379 .iter()
1380 .filter_map(|param| match param.kind {
1381 GenericParamKind::Lifetime { .. } => Some((
1382 param.id,
1383 hir::LifetimeName::Param(param.name),
1384 LifetimeDefOrigin::from_param(param),
1385 )),
1386 _ => None,
1387 })
1388 .enumerate()
1389 .find(|&(_, (_, lt_name, _))| lt_name == name)
1390 .map_or(Set1::Many, |(i, (id, _, origin))| {
1391 let def_id = tcx.hir.local_def_id(id);
1392 Set1::One(Region::EarlyBound(i as u32, def_id, origin))
1393 })
1394 }
1395 }
1396 Set1::Many => Set1::Many,
1397 })
1398 }
1399 })
1400 .collect()
1401 }
1402
1403 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
1404 // FIXME(#37666) this works around a limitation in the region inferencer
1405 fn hack<F>(&mut self, f: F)
1406 where
1407 F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
1408 {
1409 f(self)
1410 }
1411
1412 fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
1413 where
1414 F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
1415 {
1416 let LifetimeContext {
1417 tcx,
1418 map,
1419 lifetime_uses,
1420 ..
1421 } = self;
1422 let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
1423 let xcrate_object_lifetime_defaults =
1424 replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap());
1425 let mut this = LifetimeContext {
1426 tcx: *tcx,
1427 map: map,
1428 scope: &wrap_scope,
1429 trait_ref_hack: self.trait_ref_hack,
1430 is_in_fn_syntax: self.is_in_fn_syntax,
1431 labels_in_fn,
1432 xcrate_object_lifetime_defaults,
1433 lifetime_uses: lifetime_uses,
1434 };
1435 debug!("entering scope {:?}", this.scope);
1436 f(self.scope, &mut this);
1437 this.check_uses_for_lifetimes_defined_by_scope();
1438 debug!("exiting scope {:?}", this.scope);
1439 self.labels_in_fn = this.labels_in_fn;
1440 self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
1441 }
1442
1443 /// helper method to determine the span to remove when suggesting the
1444 /// deletion of a lifetime
1445 fn lifetime_deletion_span(&self, name: ast::Ident, generics: &hir::Generics) -> Option<Span> {
1446 if generics.params.len() == 1 {
1447 // if sole lifetime, remove the `<>` brackets
1448 Some(generics.span)
1449 } else {
1450 generics.params.iter().enumerate().find_map(|(i, param)| {
1451 if param.name.ident() == name {
1452 // We also want to delete a leading or trailing comma
1453 // as appropriate
1454 if i >= generics.params.len() - 1 {
1455 Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
1456 } else {
1457 Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
1458 }
1459 } else {
1460 None
1461 }
1462 })
1463 }
1464 }
1465
1466 fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
1467 let defined_by = match self.scope {
1468 Scope::Binder { lifetimes, .. } => lifetimes,
1469 _ => {
1470 debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
1471 return;
1472 }
1473 };
1474
1475 let mut def_ids: Vec<_> = defined_by
1476 .values()
1477 .flat_map(|region| match region {
1478 Region::EarlyBound(_, def_id, _)
1479 | Region::LateBound(_, def_id, _)
1480 | Region::Free(_, def_id) => Some(*def_id),
1481
1482 Region::LateBoundAnon(..) | Region::Static => None,
1483 })
1484 .collect();
1485
1486 // ensure that we issue lints in a repeatable order
1487 def_ids.sort_by_key(|&def_id| self.tcx.def_path_hash(def_id));
1488
1489 for def_id in def_ids {
1490 debug!(
1491 "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
1492 def_id
1493 );
1494
1495 let lifetimeuseset = self.lifetime_uses.remove(&def_id);
1496
1497 debug!(
1498 "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
1499 lifetimeuseset
1500 );
1501
1502 match lifetimeuseset {
1503 Some(LifetimeUseSet::One(lifetime)) => {
1504 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1505 debug!("node id first={:?}", node_id);
1506 if let Some((id, span, name)) = match self.tcx.hir.get(node_id) {
1507 Node::Lifetime(hir_lifetime) => Some((
1508 hir_lifetime.id,
1509 hir_lifetime.span,
1510 hir_lifetime.name.ident(),
1511 )),
1512 Node::GenericParam(param) => {
1513 Some((param.id, param.span, param.name.ident()))
1514 }
1515 _ => None,
1516 } {
1517 debug!("id = {:?} span = {:?} name = {:?}", node_id, span, name);
1518 let mut err = self.tcx.struct_span_lint_node(
1519 lint::builtin::SINGLE_USE_LIFETIMES,
1520 id,
1521 span,
1522 &format!("lifetime parameter `{}` only used once", name),
1523 );
1524 err.span_label(span, "this lifetime...");
1525 err.span_label(lifetime.span, "...is used only here");
1526 err.emit();
1527 }
1528 }
1529 Some(LifetimeUseSet::Many) => {
1530 debug!("Not one use lifetime");
1531 }
1532 None => {
1533 let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1534 if let Some((id, span, name)) = match self.tcx.hir.get(node_id) {
1535 Node::Lifetime(hir_lifetime) => Some((
1536 hir_lifetime.id,
1537 hir_lifetime.span,
1538 hir_lifetime.name.ident(),
1539 )),
1540 Node::GenericParam(param) => {
1541 Some((param.id, param.span, param.name.ident()))
1542 }
1543 _ => None,
1544 } {
1545 debug!("id ={:?} span = {:?} name = {:?}", node_id, span, name);
1546 let mut err = self.tcx.struct_span_lint_node(
1547 lint::builtin::UNUSED_LIFETIMES,
1548 id,
1549 span,
1550 &format!("lifetime parameter `{}` never used", name),
1551 );
1552 if let Some(parent_def_id) = self.tcx.parent(def_id) {
1553 if let Some(generics) = self.tcx.hir.get_generics(parent_def_id) {
1554 let unused_lt_span = self.lifetime_deletion_span(name, generics);
1555 if let Some(span) = unused_lt_span {
1556 err.span_suggestion_with_applicability(
1557 span,
1558 "remove it",
1559 String::new(),
1560 Applicability::MachineApplicable,
1561 );
1562 }
1563 }
1564 }
1565 err.emit();
1566 }
1567 }
1568 }
1569 }
1570 }
1571
1572 /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
1573 ///
1574 /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
1575 /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
1576 /// within type bounds; those are early bound lifetimes, and the rest are late bound.
1577 ///
1578 /// For example:
1579 ///
1580 /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
1581 ///
1582 /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
1583 /// lifetimes may be interspersed together.
1584 ///
1585 /// If early bound lifetimes are present, we separate them into their own list (and likewise
1586 /// for late bound). They will be numbered sequentially, starting from the lowest index that is
1587 /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
1588 /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
1589 /// ordering is not important there.
1590 fn visit_early_late<F>(
1591 &mut self,
1592 parent_id: Option<ast::NodeId>,
1593 decl: &'tcx hir::FnDecl,
1594 generics: &'tcx hir::Generics,
1595 walk: F,
1596 ) where
1597 F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
1598 {
1599 insert_late_bound_lifetimes(self.map, decl, generics);
1600
1601 // Find the start of nested early scopes, e.g. in methods.
1602 let mut index = 0;
1603 if let Some(parent_id) = parent_id {
1604 let parent = self.tcx.hir.expect_item(parent_id);
1605 if let hir::ItemKind::Trait(..) = parent.node {
1606 index += 1; // Self comes first.
1607 }
1608 match parent.node {
1609 hir::ItemKind::Trait(_, _, ref generics, ..)
1610 | hir::ItemKind::Impl(_, _, _, ref generics, ..) => {
1611 index += generics.params.len() as u32;
1612 }
1613 _ => {}
1614 }
1615 }
1616
1617 let mut type_count = 0;
1618 let lifetimes = generics
1619 .params
1620 .iter()
1621 .filter_map(|param| match param.kind {
1622 GenericParamKind::Lifetime { .. } => {
1623 if self.map.late_bound.contains(&param.id) {
1624 Some(Region::late(&self.tcx.hir, param))
1625 } else {
1626 Some(Region::early(&self.tcx.hir, &mut index, param))
1627 }
1628 }
1629 GenericParamKind::Type { .. } => {
1630 type_count += 1;
1631 None
1632 }
1633 })
1634 .collect();
1635 let next_early_index = index + type_count;
1636
1637 let scope = Scope::Binder {
1638 lifetimes,
1639 next_early_index,
1640 s: self.scope,
1641 abstract_type_parent: true,
1642 track_lifetime_uses: false,
1643 };
1644 self.with(scope, move |old_scope, this| {
1645 this.check_lifetime_params(old_scope, &generics.params);
1646 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
1647 });
1648 }
1649
1650 fn next_early_index_helper(&self, only_abstract_type_parent: bool) -> u32 {
1651 let mut scope = self.scope;
1652 loop {
1653 match *scope {
1654 Scope::Root => return 0,
1655
1656 Scope::Binder {
1657 next_early_index,
1658 abstract_type_parent,
1659 ..
1660 } if (!only_abstract_type_parent || abstract_type_parent) =>
1661 {
1662 return next_early_index
1663 }
1664
1665 Scope::Binder { s, .. }
1666 | Scope::Body { s, .. }
1667 | Scope::Elision { s, .. }
1668 | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
1669 }
1670 }
1671 }
1672
1673 /// Returns the next index one would use for an early-bound-region
1674 /// if extending the current scope.
1675 fn next_early_index(&self) -> u32 {
1676 self.next_early_index_helper(true)
1677 }
1678
1679 /// Returns the next index one would use for an `impl Trait` that
1680 /// is being converted into an `abstract type`. This will be the
1681 /// next early index from the enclosing item, for the most
1682 /// part. See the `abstract_type_parent` field for more info.
1683 fn next_early_index_for_abstract_type(&self) -> u32 {
1684 self.next_early_index_helper(false)
1685 }
1686
1687 fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
1688 debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
1689
1690 // If we've already reported an error, just ignore `lifetime_ref`.
1691 if let LifetimeName::Error = lifetime_ref.name {
1692 return;
1693 }
1694
1695 // Walk up the scope chain, tracking the number of fn scopes
1696 // that we pass through, until we find a lifetime with the
1697 // given name or we run out of scopes.
1698 // search.
1699 let mut late_depth = 0;
1700 let mut scope = self.scope;
1701 let mut outermost_body = None;
1702 let result = loop {
1703 match *scope {
1704 Scope::Body { id, s } => {
1705 outermost_body = Some(id);
1706 scope = s;
1707 }
1708
1709 Scope::Root => {
1710 break None;
1711 }
1712
1713 Scope::Binder {
1714 ref lifetimes, s, ..
1715 } => {
1716 match lifetime_ref.name {
1717 LifetimeName::Param(param_name) => {
1718 if let Some(&def) = lifetimes.get(&param_name.modern()) {
1719 break Some(def.shifted(late_depth));
1720 }
1721 }
1722 _ => bug!("expected LifetimeName::Param"),
1723 }
1724
1725 late_depth += 1;
1726 scope = s;
1727 }
1728
1729 Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
1730 scope = s;
1731 }
1732 }
1733 };
1734
1735 if let Some(mut def) = result {
1736 if let Region::EarlyBound(..) = def {
1737 // Do not free early-bound regions, only late-bound ones.
1738 } else if let Some(body_id) = outermost_body {
1739 let fn_id = self.tcx.hir.body_owner(body_id);
1740 match self.tcx.hir.get(fn_id) {
1741 Node::Item(&hir::Item {
1742 node: hir::ItemKind::Fn(..),
1743 ..
1744 })
1745 | Node::TraitItem(&hir::TraitItem {
1746 node: hir::TraitItemKind::Method(..),
1747 ..
1748 })
1749 | Node::ImplItem(&hir::ImplItem {
1750 node: hir::ImplItemKind::Method(..),
1751 ..
1752 }) => {
1753 let scope = self.tcx.hir.local_def_id(fn_id);
1754 def = Region::Free(scope, def.id().unwrap());
1755 }
1756 _ => {}
1757 }
1758 }
1759
1760 // Check for fn-syntax conflicts with in-band lifetime definitions
1761 if self.is_in_fn_syntax {
1762 match def {
1763 Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
1764 | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
1765 struct_span_err!(
1766 self.tcx.sess,
1767 lifetime_ref.span,
1768 E0687,
1769 "lifetimes used in `fn` or `Fn` syntax must be \
1770 explicitly declared using `<...>` binders"
1771 ).span_label(lifetime_ref.span, "in-band lifetime definition")
1772 .emit();
1773 }
1774
1775 Region::Static
1776 | Region::EarlyBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1777 | Region::LateBound(_, _, LifetimeDefOrigin::ExplicitOrElided)
1778 | Region::EarlyBound(_, _, LifetimeDefOrigin::Error)
1779 | Region::LateBound(_, _, LifetimeDefOrigin::Error)
1780 | Region::LateBoundAnon(..)
1781 | Region::Free(..) => {}
1782 }
1783 }
1784
1785 self.insert_lifetime(lifetime_ref, def);
1786 } else {
1787 struct_span_err!(
1788 self.tcx.sess,
1789 lifetime_ref.span,
1790 E0261,
1791 "use of undeclared lifetime name `{}`",
1792 lifetime_ref
1793 ).span_label(lifetime_ref.span, "undeclared lifetime")
1794 .emit();
1795 }
1796 }
1797
1798 fn visit_segment_args(&mut self, def: Def, depth: usize, generic_args: &'tcx hir::GenericArgs) {
1799 if generic_args.parenthesized {
1800 let was_in_fn_syntax = self.is_in_fn_syntax;
1801 self.is_in_fn_syntax = true;
1802 self.visit_fn_like_elision(generic_args.inputs(), Some(&generic_args.bindings[0].ty));
1803 self.is_in_fn_syntax = was_in_fn_syntax;
1804 return;
1805 }
1806
1807 let mut elide_lifetimes = true;
1808 let lifetimes = generic_args
1809 .args
1810 .iter()
1811 .filter_map(|arg| match arg {
1812 hir::GenericArg::Lifetime(lt) => {
1813 if !lt.is_elided() {
1814 elide_lifetimes = false;
1815 }
1816 Some(lt)
1817 }
1818 _ => None,
1819 })
1820 .collect();
1821 if elide_lifetimes {
1822 self.resolve_elided_lifetimes(lifetimes);
1823 } else {
1824 lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
1825 }
1826
1827 // Figure out if this is a type/trait segment,
1828 // which requires object lifetime defaults.
1829 let parent_def_id = |this: &mut Self, def_id: DefId| {
1830 let def_key = this.tcx.def_key(def_id);
1831 DefId {
1832 krate: def_id.krate,
1833 index: def_key.parent.expect("missing parent"),
1834 }
1835 };
1836 let type_def_id = match def {
1837 Def::AssociatedTy(def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
1838 Def::Variant(def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
1839 Def::Struct(def_id)
1840 | Def::Union(def_id)
1841 | Def::Enum(def_id)
1842 | Def::TyAlias(def_id)
1843 | Def::Trait(def_id) if depth == 0 =>
1844 {
1845 Some(def_id)
1846 }
1847 _ => None,
1848 };
1849
1850 let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
1851 let in_body = {
1852 let mut scope = self.scope;
1853 loop {
1854 match *scope {
1855 Scope::Root => break false,
1856
1857 Scope::Body { .. } => break true,
1858
1859 Scope::Binder { s, .. }
1860 | Scope::Elision { s, .. }
1861 | Scope::ObjectLifetimeDefault { s, .. } => {
1862 scope = s;
1863 }
1864 }
1865 }
1866 };
1867
1868 let map = &self.map;
1869 let unsubst = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1870 &map.object_lifetime_defaults[&id]
1871 } else {
1872 let tcx = self.tcx;
1873 self.xcrate_object_lifetime_defaults
1874 .entry(def_id)
1875 .or_insert_with(|| {
1876 tcx.generics_of(def_id)
1877 .params
1878 .iter()
1879 .filter_map(|param| match param.kind {
1880 GenericParamDefKind::Type {
1881 object_lifetime_default,
1882 ..
1883 } => Some(object_lifetime_default),
1884 GenericParamDefKind::Lifetime => None,
1885 })
1886 .collect()
1887 })
1888 };
1889 unsubst
1890 .iter()
1891 .map(|set| match *set {
1892 Set1::Empty => if in_body {
1893 None
1894 } else {
1895 Some(Region::Static)
1896 },
1897 Set1::One(r) => {
1898 let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
1899 GenericArg::Lifetime(lt) => Some(lt),
1900 _ => None,
1901 });
1902 r.subst(lifetimes, map)
1903 }
1904 Set1::Many => None,
1905 })
1906 .collect()
1907 });
1908
1909 let mut i = 0;
1910 for arg in &generic_args.args {
1911 match arg {
1912 GenericArg::Lifetime(_) => {}
1913 GenericArg::Type(ty) => {
1914 if let Some(&lt) = object_lifetime_defaults.get(i) {
1915 let scope = Scope::ObjectLifetimeDefault {
1916 lifetime: lt,
1917 s: self.scope,
1918 };
1919 self.with(scope, |_, this| this.visit_ty(ty));
1920 } else {
1921 self.visit_ty(ty);
1922 }
1923 i += 1;
1924 }
1925 }
1926 }
1927
1928 for b in &generic_args.bindings {
1929 self.visit_assoc_type_binding(b);
1930 }
1931 }
1932
1933 fn visit_fn_like_elision(&mut self, inputs: &'tcx [hir::Ty], output: Option<&'tcx P<hir::Ty>>) {
1934 debug!("visit_fn_like_elision: enter");
1935 let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
1936 let arg_scope = Scope::Elision {
1937 elide: arg_elide.clone(),
1938 s: self.scope,
1939 };
1940 self.with(arg_scope, |_, this| {
1941 for input in inputs {
1942 this.visit_ty(input);
1943 }
1944 match *this.scope {
1945 Scope::Elision { ref elide, .. } => {
1946 arg_elide = elide.clone();
1947 }
1948 _ => bug!(),
1949 }
1950 });
1951
1952 let output = match output {
1953 Some(ty) => ty,
1954 None => return,
1955 };
1956
1957 debug!("visit_fn_like_elision: determine output");
1958
1959 // Figure out if there's a body we can get argument names from,
1960 // and whether there's a `self` argument (treated specially).
1961 let mut assoc_item_kind = None;
1962 let mut impl_self = None;
1963 let parent = self.tcx.hir.get_parent_node(output.id);
1964 let body = match self.tcx.hir.get(parent) {
1965 // `fn` definitions and methods.
1966 Node::Item(&hir::Item {
1967 node: hir::ItemKind::Fn(.., body),
1968 ..
1969 }) => Some(body),
1970
1971 Node::TraitItem(&hir::TraitItem {
1972 node: hir::TraitItemKind::Method(_, ref m),
1973 ..
1974 }) => {
1975 if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
1976 .hir
1977 .expect_item(self.tcx.hir.get_parent(parent))
1978 .node
1979 {
1980 assoc_item_kind = trait_items
1981 .iter()
1982 .find(|ti| ti.id.node_id == parent)
1983 .map(|ti| ti.kind);
1984 }
1985 match *m {
1986 hir::TraitMethod::Required(_) => None,
1987 hir::TraitMethod::Provided(body) => Some(body),
1988 }
1989 }
1990
1991 Node::ImplItem(&hir::ImplItem {
1992 node: hir::ImplItemKind::Method(_, body),
1993 ..
1994 }) => {
1995 if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
1996 .hir
1997 .expect_item(self.tcx.hir.get_parent(parent))
1998 .node
1999 {
2000 impl_self = Some(self_ty);
2001 assoc_item_kind = impl_items
2002 .iter()
2003 .find(|ii| ii.id.node_id == parent)
2004 .map(|ii| ii.kind);
2005 }
2006 Some(body)
2007 }
2008
2009 // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
2010 Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
2011 // Everything else (only closures?) doesn't
2012 // actually enjoy elision in return types.
2013 _ => {
2014 self.visit_ty(output);
2015 return;
2016 }
2017 };
2018
2019 let has_self = match assoc_item_kind {
2020 Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
2021 _ => false,
2022 };
2023
2024 // In accordance with the rules for lifetime elision, we can determine
2025 // what region to use for elision in the output type in two ways.
2026 // First (determined here), if `self` is by-reference, then the
2027 // implied output region is the region of the self parameter.
2028 if has_self {
2029 // Look for `self: &'a Self` - also desugared from `&'a self`,
2030 // and if that matches, use it for elision and return early.
2031 let is_self_ty = |def: Def| {
2032 if let Def::SelfTy(..) = def {
2033 return true;
2034 }
2035
2036 // Can't always rely on literal (or implied) `Self` due
2037 // to the way elision rules were originally specified.
2038 let impl_self = impl_self.map(|ty| &ty.node);
2039 if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) = impl_self {
2040 match path.def {
2041 // Whitelist the types that unambiguously always
2042 // result in the same type constructor being used
2043 // (it can't differ between `Self` and `self`).
2044 Def::Struct(_) | Def::Union(_) | Def::Enum(_) | Def::PrimTy(_) => {
2045 return def == path.def
2046 }
2047 _ => {}
2048 }
2049 }
2050
2051 false
2052 };
2053
2054 if let hir::TyKind::Rptr(lifetime_ref, ref mt) = inputs[0].node {
2055 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
2056 if is_self_ty(path.def) {
2057 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
2058 let scope = Scope::Elision {
2059 elide: Elide::Exact(lifetime),
2060 s: self.scope,
2061 };
2062 self.with(scope, |_, this| this.visit_ty(output));
2063 return;
2064 }
2065 }
2066 }
2067 }
2068 }
2069
2070 // Second, if there was exactly one lifetime (either a substitution or a
2071 // reference) in the arguments, then any anonymous regions in the output
2072 // have that lifetime.
2073 let mut possible_implied_output_region = None;
2074 let mut lifetime_count = 0;
2075 let arg_lifetimes = inputs
2076 .iter()
2077 .enumerate()
2078 .skip(has_self as usize)
2079 .map(|(i, input)| {
2080 let mut gather = GatherLifetimes {
2081 map: self.map,
2082 outer_index: ty::INNERMOST,
2083 have_bound_regions: false,
2084 lifetimes: Default::default(),
2085 };
2086 gather.visit_ty(input);
2087
2088 lifetime_count += gather.lifetimes.len();
2089
2090 if lifetime_count == 1 && gather.lifetimes.len() == 1 {
2091 // there's a chance that the unique lifetime of this
2092 // iteration will be the appropriate lifetime for output
2093 // parameters, so lets store it.
2094 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
2095 }
2096
2097 ElisionFailureInfo {
2098 parent: body,
2099 index: i,
2100 lifetime_count: gather.lifetimes.len(),
2101 have_bound_regions: gather.have_bound_regions,
2102 }
2103 })
2104 .collect();
2105
2106 let elide = if lifetime_count == 1 {
2107 Elide::Exact(possible_implied_output_region.unwrap())
2108 } else {
2109 Elide::Error(arg_lifetimes)
2110 };
2111
2112 debug!("visit_fn_like_elision: elide={:?}", elide);
2113
2114 let scope = Scope::Elision {
2115 elide,
2116 s: self.scope,
2117 };
2118 self.with(scope, |_, this| this.visit_ty(output));
2119 debug!("visit_fn_like_elision: exit");
2120
2121 struct GatherLifetimes<'a> {
2122 map: &'a NamedRegionMap,
2123 outer_index: ty::DebruijnIndex,
2124 have_bound_regions: bool,
2125 lifetimes: FxHashSet<Region>,
2126 }
2127
2128 impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
2129 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2130 NestedVisitorMap::None
2131 }
2132
2133 fn visit_ty(&mut self, ty: &hir::Ty) {
2134 if let hir::TyKind::BareFn(_) = ty.node {
2135 self.outer_index.shift_in(1);
2136 }
2137 if let hir::TyKind::TraitObject(ref bounds, ref lifetime) = ty.node {
2138 for bound in bounds {
2139 self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
2140 }
2141
2142 // Stay on the safe side and don't include the object
2143 // lifetime default (which may not end up being used).
2144 if !lifetime.is_elided() {
2145 self.visit_lifetime(lifetime);
2146 }
2147 } else {
2148 intravisit::walk_ty(self, ty);
2149 }
2150 if let hir::TyKind::BareFn(_) = ty.node {
2151 self.outer_index.shift_out(1);
2152 }
2153 }
2154
2155 fn visit_generic_param(&mut self, param: &hir::GenericParam) {
2156 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2157 // FIXME(eddyb) Do we want this? It only makes a difference
2158 // if this `for<'a>` lifetime parameter is never used.
2159 self.have_bound_regions = true;
2160 }
2161
2162 intravisit::walk_generic_param(self, param);
2163 }
2164
2165 fn visit_poly_trait_ref(
2166 &mut self,
2167 trait_ref: &hir::PolyTraitRef,
2168 modifier: hir::TraitBoundModifier,
2169 ) {
2170 self.outer_index.shift_in(1);
2171 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2172 self.outer_index.shift_out(1);
2173 }
2174
2175 fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
2176 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
2177 match lifetime {
2178 Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
2179 if debruijn < self.outer_index =>
2180 {
2181 self.have_bound_regions = true;
2182 }
2183 _ => {
2184 self.lifetimes
2185 .insert(lifetime.shifted_out_to_binder(self.outer_index));
2186 }
2187 }
2188 }
2189 }
2190 }
2191 }
2192
2193 fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
2194 if lifetime_refs.is_empty() {
2195 return;
2196 }
2197
2198 let span = lifetime_refs[0].span;
2199 let mut late_depth = 0;
2200 let mut scope = self.scope;
2201 let error = loop {
2202 match *scope {
2203 // Do not assign any resolution, it will be inferred.
2204 Scope::Body { .. } => return,
2205
2206 Scope::Root => break None,
2207
2208 Scope::Binder { s, .. } => {
2209 late_depth += 1;
2210 scope = s;
2211 }
2212
2213 Scope::Elision { ref elide, .. } => {
2214 let lifetime = match *elide {
2215 Elide::FreshLateAnon(ref counter) => {
2216 for lifetime_ref in lifetime_refs {
2217 let lifetime = Region::late_anon(counter).shifted(late_depth);
2218 self.insert_lifetime(lifetime_ref, lifetime);
2219 }
2220 return;
2221 }
2222 Elide::Exact(l) => l.shifted(late_depth),
2223 Elide::Error(ref e) => break Some(e),
2224 };
2225 for lifetime_ref in lifetime_refs {
2226 self.insert_lifetime(lifetime_ref, lifetime);
2227 }
2228 return;
2229 }
2230
2231 Scope::ObjectLifetimeDefault { s, .. } => {
2232 scope = s;
2233 }
2234 }
2235 };
2236
2237 let mut err = report_missing_lifetime_specifiers(self.tcx.sess, span, lifetime_refs.len());
2238 let mut add_label = true;
2239
2240 if let Some(params) = error {
2241 if lifetime_refs.len() == 1 {
2242 add_label = add_label && self.report_elision_failure(&mut err, params, span);
2243 }
2244 }
2245 if add_label {
2246 add_missing_lifetime_specifiers_label(&mut err, span, lifetime_refs.len());
2247 }
2248
2249 err.emit();
2250 }
2251
2252 fn suggest_lifetime(&self, db: &mut DiagnosticBuilder<'_>, span: Span, msg: &str) -> bool {
2253 match self.tcx.sess.source_map().span_to_snippet(span) {
2254 Ok(ref snippet) => {
2255 let (sugg, applicability) = if snippet == "&" {
2256 ("&'static ".to_owned(), Applicability::MachineApplicable)
2257 } else if snippet == "'_" {
2258 ("'static".to_owned(), Applicability::MachineApplicable)
2259 } else {
2260 (format!("{} + 'static", snippet), Applicability::MaybeIncorrect)
2261 };
2262 db.span_suggestion_with_applicability(span, msg, sugg, applicability);
2263 false
2264 }
2265 Err(_) => {
2266 db.help(msg);
2267 true
2268 }
2269 }
2270 }
2271
2272 fn report_elision_failure(
2273 &mut self,
2274 db: &mut DiagnosticBuilder<'_>,
2275 params: &[ElisionFailureInfo],
2276 span: Span,
2277 ) -> bool {
2278 let mut m = String::new();
2279 let len = params.len();
2280
2281 let elided_params: Vec<_> = params
2282 .iter()
2283 .cloned()
2284 .filter(|info| info.lifetime_count > 0)
2285 .collect();
2286
2287 let elided_len = elided_params.len();
2288
2289 for (i, info) in elided_params.into_iter().enumerate() {
2290 let ElisionFailureInfo {
2291 parent,
2292 index,
2293 lifetime_count: n,
2294 have_bound_regions,
2295 } = info;
2296
2297 let help_name = if let Some(body) = parent {
2298 let arg = &self.tcx.hir.body(body).arguments[index];
2299 format!("`{}`", self.tcx.hir.node_to_pretty_string(arg.pat.id))
2300 } else {
2301 format!("argument {}", index + 1)
2302 };
2303
2304 m.push_str(
2305 &(if n == 1 {
2306 help_name
2307 } else {
2308 format!(
2309 "one of {}'s {} {}lifetimes",
2310 help_name,
2311 n,
2312 if have_bound_regions { "free " } else { "" }
2313 )
2314 })[..],
2315 );
2316
2317 if elided_len == 2 && i == 0 {
2318 m.push_str(" or ");
2319 } else if i + 2 == elided_len {
2320 m.push_str(", or ");
2321 } else if i != elided_len - 1 {
2322 m.push_str(", ");
2323 }
2324 }
2325
2326 if len == 0 {
2327 help!(
2328 db,
2329 "this function's return type contains a borrowed value, but \
2330 there is no value for it to be borrowed from"
2331 );
2332 self.suggest_lifetime(db, span, "consider giving it a 'static lifetime")
2333 } else if elided_len == 0 {
2334 help!(
2335 db,
2336 "this function's return type contains a borrowed value with \
2337 an elided lifetime, but the lifetime cannot be derived from \
2338 the arguments"
2339 );
2340 let msg = "consider giving it an explicit bounded or 'static lifetime";
2341 self.suggest_lifetime(db, span, msg)
2342 } else if elided_len == 1 {
2343 help!(
2344 db,
2345 "this function's return type contains a borrowed value, but \
2346 the signature does not say which {} it is borrowed from",
2347 m
2348 );
2349 true
2350 } else {
2351 help!(
2352 db,
2353 "this function's return type contains a borrowed value, but \
2354 the signature does not say whether it is borrowed from {}",
2355 m
2356 );
2357 true
2358 }
2359 }
2360
2361 fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
2362 let mut late_depth = 0;
2363 let mut scope = self.scope;
2364 let lifetime = loop {
2365 match *scope {
2366 Scope::Binder { s, .. } => {
2367 late_depth += 1;
2368 scope = s;
2369 }
2370
2371 Scope::Root | Scope::Elision { .. } => break Region::Static,
2372
2373 Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
2374
2375 Scope::ObjectLifetimeDefault {
2376 lifetime: Some(l), ..
2377 } => break l,
2378 }
2379 };
2380 self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
2381 }
2382
2383 fn check_lifetime_params(
2384 &mut self,
2385 old_scope: ScopeRef<'_>,
2386 params: &'tcx [hir::GenericParam],
2387 ) {
2388 let lifetimes: Vec<_> = params
2389 .iter()
2390 .filter_map(|param| match param.kind {
2391 GenericParamKind::Lifetime { .. } => Some((param, param.name)),
2392 _ => None,
2393 })
2394 .collect();
2395 for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
2396 if let hir::ParamName::Plain(_) = lifetime_i_name {
2397 let name = lifetime_i_name.ident().name;
2398 if name == keywords::UnderscoreLifetime.name()
2399 || name == keywords::StaticLifetime.name()
2400 {
2401 let mut err = struct_span_err!(
2402 self.tcx.sess,
2403 lifetime_i.span,
2404 E0262,
2405 "invalid lifetime parameter name: `{}`",
2406 lifetime_i.name.ident(),
2407 );
2408 err.span_label(
2409 lifetime_i.span,
2410 format!("{} is a reserved lifetime name", name),
2411 );
2412 err.emit();
2413 }
2414 }
2415
2416 // It is a hard error to shadow a lifetime within the same scope.
2417 for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
2418 if lifetime_i_name == lifetime_j_name {
2419 struct_span_err!(
2420 self.tcx.sess,
2421 lifetime_j.span,
2422 E0263,
2423 "lifetime name `{}` declared twice in the same scope",
2424 lifetime_j.name.ident()
2425 ).span_label(lifetime_j.span, "declared twice")
2426 .span_label(lifetime_i.span, "previous declaration here")
2427 .emit();
2428 }
2429 }
2430
2431 // It is a soft error to shadow a lifetime within a parent scope.
2432 self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
2433
2434 for bound in &lifetime_i.bounds {
2435 match bound {
2436 hir::GenericBound::Outlives(lt) => match lt.name {
2437 hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
2438 lt.span,
2439 "use of `'_` in illegal place, but not caught by lowering",
2440 ),
2441 hir::LifetimeName::Static => {
2442 self.insert_lifetime(lt, Region::Static);
2443 self.tcx
2444 .sess
2445 .struct_span_warn(
2446 lifetime_i.span.to(lt.span),
2447 &format!(
2448 "unnecessary lifetime parameter `{}`",
2449 lifetime_i.name.ident(),
2450 ),
2451 )
2452 .help(&format!(
2453 "you can use the `'static` lifetime directly, in place of `{}`",
2454 lifetime_i.name.ident(),
2455 ))
2456 .emit();
2457 }
2458 hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
2459 self.resolve_lifetime_ref(lt);
2460 }
2461 hir::LifetimeName::Error => {
2462 // No need to do anything, error already reported.
2463 }
2464 },
2465 _ => bug!(),
2466 }
2467 }
2468 }
2469 }
2470
2471 fn check_lifetime_param_for_shadowing(
2472 &self,
2473 mut old_scope: ScopeRef<'_>,
2474 param: &'tcx hir::GenericParam,
2475 ) {
2476 for label in &self.labels_in_fn {
2477 // FIXME (#24278): non-hygienic comparison
2478 if param.name.ident().name == label.name {
2479 signal_shadowing_problem(
2480 self.tcx,
2481 label.name,
2482 original_label(label.span),
2483 shadower_lifetime(&param),
2484 );
2485 return;
2486 }
2487 }
2488
2489 loop {
2490 match *old_scope {
2491 Scope::Body { s, .. }
2492 | Scope::Elision { s, .. }
2493 | Scope::ObjectLifetimeDefault { s, .. } => {
2494 old_scope = s;
2495 }
2496
2497 Scope::Root => {
2498 return;
2499 }
2500
2501 Scope::Binder {
2502 ref lifetimes, s, ..
2503 } => {
2504 if let Some(&def) = lifetimes.get(&param.name.modern()) {
2505 let node_id = self.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
2506
2507 signal_shadowing_problem(
2508 self.tcx,
2509 param.name.ident().name,
2510 original_lifetime(self.tcx.hir.span(node_id)),
2511 shadower_lifetime(&param),
2512 );
2513 return;
2514 }
2515
2516 old_scope = s;
2517 }
2518 }
2519 }
2520 }
2521
2522 /// Returns true if, in the current scope, replacing `'_` would be
2523 /// equivalent to a single-use lifetime.
2524 fn track_lifetime_uses(&self) -> bool {
2525 let mut scope = self.scope;
2526 loop {
2527 match *scope {
2528 Scope::Root => break false,
2529
2530 // Inside of items, it depends on the kind of item.
2531 Scope::Binder {
2532 track_lifetime_uses,
2533 ..
2534 } => break track_lifetime_uses,
2535
2536 // Inside a body, `'_` will use an inference variable,
2537 // should be fine.
2538 Scope::Body { .. } => break true,
2539
2540 // A lifetime only used in a fn argument could as well
2541 // be replaced with `'_`, as that would generate a
2542 // fresh name, too.
2543 Scope::Elision {
2544 elide: Elide::FreshLateAnon(_),
2545 ..
2546 } => break true,
2547
2548 // In the return type or other such place, `'_` is not
2549 // going to make a fresh name, so we cannot
2550 // necessarily replace a single-use lifetime with
2551 // `'_`.
2552 Scope::Elision {
2553 elide: Elide::Exact(_),
2554 ..
2555 } => break false,
2556 Scope::Elision {
2557 elide: Elide::Error(_),
2558 ..
2559 } => break false,
2560
2561 Scope::ObjectLifetimeDefault { s, .. } => scope = s,
2562 }
2563 }
2564 }
2565
2566 fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
2567 if lifetime_ref.id == ast::DUMMY_NODE_ID {
2568 span_bug!(
2569 lifetime_ref.span,
2570 "lifetime reference not renumbered, \
2571 probably a bug in syntax::fold"
2572 );
2573 }
2574
2575 debug!(
2576 "insert_lifetime: {} resolved to {:?} span={:?}",
2577 self.tcx.hir.node_to_string(lifetime_ref.id),
2578 def,
2579 self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
2580 );
2581 self.map.defs.insert(lifetime_ref.id, def);
2582
2583 match def {
2584 Region::LateBoundAnon(..) | Region::Static => {
2585 // These are anonymous lifetimes or lifetimes that are not declared.
2586 }
2587
2588 Region::Free(_, def_id)
2589 | Region::LateBound(_, def_id, _)
2590 | Region::EarlyBound(_, def_id, _) => {
2591 // A lifetime declared by the user.
2592 let track_lifetime_uses = self.track_lifetime_uses();
2593 debug!(
2594 "insert_lifetime: track_lifetime_uses={}",
2595 track_lifetime_uses
2596 );
2597 if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
2598 debug!("insert_lifetime: first use of {:?}", def_id);
2599 self.lifetime_uses
2600 .insert(def_id, LifetimeUseSet::One(lifetime_ref));
2601 } else {
2602 debug!("insert_lifetime: many uses of {:?}", def_id);
2603 self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
2604 }
2605 }
2606 }
2607 }
2608
2609 /// Sometimes we resolve a lifetime, but later find that it is an
2610 /// error (esp. around impl trait). In that case, we remove the
2611 /// entry into `map.defs` so as not to confuse later code.
2612 fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
2613 let old_value = self.map.defs.remove(&lifetime_ref.id);
2614 assert_eq!(old_value, Some(bad_def));
2615 }
2616 }
2617
2618 /// Detects late-bound lifetimes and inserts them into
2619 /// `map.late_bound`.
2620 ///
2621 /// A region declared on a fn is **late-bound** if:
2622 /// - it is constrained by an argument type;
2623 /// - it does not appear in a where-clause.
2624 ///
2625 /// "Constrained" basically means that it appears in any type but
2626 /// not amongst the inputs to a projection. In other words, `<&'a
2627 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
2628 fn insert_late_bound_lifetimes(
2629 map: &mut NamedRegionMap,
2630 decl: &hir::FnDecl,
2631 generics: &hir::Generics,
2632 ) {
2633 debug!(
2634 "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
2635 decl, generics
2636 );
2637
2638 let mut constrained_by_input = ConstrainedCollector::default();
2639 for arg_ty in &decl.inputs {
2640 constrained_by_input.visit_ty(arg_ty);
2641 }
2642
2643 let mut appears_in_output = AllCollector {
2644 regions: Default::default(),
2645 };
2646 intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
2647
2648 debug!(
2649 "insert_late_bound_lifetimes: constrained_by_input={:?}",
2650 constrained_by_input.regions
2651 );
2652
2653 // Walk the lifetimes that appear in where clauses.
2654 //
2655 // Subtle point: because we disallow nested bindings, we can just
2656 // ignore binders here and scrape up all names we see.
2657 let mut appears_in_where_clause = AllCollector {
2658 regions: Default::default(),
2659 };
2660 appears_in_where_clause.visit_generics(generics);
2661
2662 for param in &generics.params {
2663 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2664 if !param.bounds.is_empty() {
2665 // `'a: 'b` means both `'a` and `'b` are referenced
2666 appears_in_where_clause
2667 .regions
2668 .insert(hir::LifetimeName::Param(param.name.modern()));
2669 }
2670 }
2671 }
2672
2673 debug!(
2674 "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
2675 appears_in_where_clause.regions
2676 );
2677
2678 // Late bound regions are those that:
2679 // - appear in the inputs
2680 // - do not appear in the where-clauses
2681 // - are not implicitly captured by `impl Trait`
2682 for param in &generics.params {
2683 match param.kind {
2684 hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
2685
2686 // Types are not late-bound.
2687 hir::GenericParamKind::Type { .. } => continue,
2688 }
2689
2690 let lt_name = hir::LifetimeName::Param(param.name.modern());
2691 // appears in the where clauses? early-bound.
2692 if appears_in_where_clause.regions.contains(&lt_name) {
2693 continue;
2694 }
2695
2696 // does not appear in the inputs, but appears in the return type? early-bound.
2697 if !constrained_by_input.regions.contains(&lt_name)
2698 && appears_in_output.regions.contains(&lt_name)
2699 {
2700 continue;
2701 }
2702
2703 debug!(
2704 "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
2705 param.name.ident(),
2706 param.id
2707 );
2708
2709 let inserted = map.late_bound.insert(param.id);
2710 assert!(inserted, "visited lifetime {:?} twice", param.id);
2711 }
2712
2713 return;
2714
2715 #[derive(Default)]
2716 struct ConstrainedCollector {
2717 regions: FxHashSet<hir::LifetimeName>,
2718 }
2719
2720 impl<'v> Visitor<'v> for ConstrainedCollector {
2721 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2722 NestedVisitorMap::None
2723 }
2724
2725 fn visit_ty(&mut self, ty: &'v hir::Ty) {
2726 match ty.node {
2727 hir::TyKind::Path(hir::QPath::Resolved(Some(_), _))
2728 | hir::TyKind::Path(hir::QPath::TypeRelative(..)) => {
2729 // ignore lifetimes appearing in associated type
2730 // projections, as they are not *constrained*
2731 // (defined above)
2732 }
2733
2734 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
2735 // consider only the lifetimes on the final
2736 // segment; I am not sure it's even currently
2737 // valid to have them elsewhere, but even if it
2738 // is, those would be potentially inputs to
2739 // projections
2740 if let Some(last_segment) = path.segments.last() {
2741 self.visit_path_segment(path.span, last_segment);
2742 }
2743 }
2744
2745 _ => {
2746 intravisit::walk_ty(self, ty);
2747 }
2748 }
2749 }
2750
2751 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2752 self.regions.insert(lifetime_ref.name.modern());
2753 }
2754 }
2755
2756 struct AllCollector {
2757 regions: FxHashSet<hir::LifetimeName>,
2758 }
2759
2760 impl<'v> Visitor<'v> for AllCollector {
2761 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
2762 NestedVisitorMap::None
2763 }
2764
2765 fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
2766 self.regions.insert(lifetime_ref.name.modern());
2767 }
2768 }
2769 }
2770
2771 fn report_missing_lifetime_specifiers(
2772 sess: &Session,
2773 span: Span,
2774 count: usize,
2775 ) -> DiagnosticBuilder<'_> {
2776 struct_span_err!(
2777 sess,
2778 span,
2779 E0106,
2780 "missing lifetime specifier{}",
2781 if count > 1 { "s" } else { "" }
2782 )
2783 }
2784
2785 fn add_missing_lifetime_specifiers_label(
2786 err: &mut DiagnosticBuilder<'_>,
2787 span: Span,
2788 count: usize,
2789 ) {
2790 if count > 1 {
2791 err.span_label(span, format!("expected {} lifetime parameters", count));
2792 } else {
2793 err.span_label(span, "expected lifetime parameter");
2794 };
2795 }