1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and IDs.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. IDs are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! "folding" an existing one), create a new ID using `next_id()`.
17 //! You must ensure that IDs are unique. That means that you should only use the
18 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's ID to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as IDs to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans; don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 #![feature(crate_visibility_modifier)]
34 #![cfg_attr(bootstrap, feature(or_patterns))]
35 #![feature(box_patterns)]
36 #![recursion_limit = "256"]
38 use rustc_ast::node_id::NodeMap;
39 use rustc_ast::token::{self, DelimToken, Nonterminal, Token};
40 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, DelimSpan, TokenStream, TokenTree};
41 use rustc_ast::visit::{self, AssocCtxt, Visitor};
42 use rustc_ast::walk_list;
43 use rustc_ast::{self as ast, *};
44 use rustc_ast_pretty::pprust;
45 use rustc_data_structures::captures::Captures;
46 use rustc_data_structures::fx::FxHashSet;
47 use rustc_data_structures::sync::Lrc;
48 use rustc_errors::struct_span_err;
50 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
51 use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_ID};
52 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
53 use rustc_hir::intravisit;
54 use rustc_hir::{ConstArg, GenericArg, ParamName};
55 use rustc_index::vec::{Idx, IndexVec};
56 use rustc_session::lint::builtin::{BARE_TRAIT_OBJECTS, MISSING_ABI};
57 use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
58 use rustc_session::parse::ParseSess;
59 use rustc_session::Session;
60 use rustc_span::hygiene::ExpnId;
61 use rustc_span::source_map::{respan, DesugaringKind};
62 use rustc_span::symbol::{kw, sym, Ident, Symbol};
64 use rustc_target::spec::abi::Abi;
66 use smallvec::{smallvec, SmallVec};
67 use std::collections::BTreeMap;
69 use tracing::{debug, trace};
71 macro_rules! arena_vec {
72 ($this:expr; $($x:expr),*) => ({
74 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
83 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
85 rustc_hir::arena_types!(rustc_arena::declare_arena, [], 'tcx);
87 struct LoweringContext<'a, 'hir: 'a> {
88 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
91 resolver: &'a mut dyn ResolverAstLowering,
93 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
94 /// if we don't have this function pointer. To avoid that dependency so that
95 /// librustc_middle is independent of the parser, we use dynamic dispatch here.
96 nt_to_tokenstream: NtToTokenstream,
98 /// Used to allocate HIR nodes.
99 arena: &'hir Arena<'hir>,
101 /// The items being lowered are collected here.
102 items: BTreeMap<hir::ItemId, hir::Item<'hir>>,
104 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
105 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
106 foreign_items: BTreeMap<hir::ForeignItemId, hir::ForeignItem<'hir>>,
107 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
108 exported_macros: Vec<hir::MacroDef<'hir>>,
109 non_exported_macro_attrs: Vec<ast::Attribute>,
111 trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
113 modules: BTreeMap<LocalDefId, hir::ModuleItems>,
115 generator_kind: Option<hir::GeneratorKind>,
117 attrs: BTreeMap<hir::HirId, &'hir [Attribute]>,
119 /// When inside an `async` context, this is the `HirId` of the
120 /// `task_context` local bound to the resume argument of the generator.
121 task_context: Option<hir::HirId>,
123 /// Used to get the current `fn`'s def span to point to when using `await`
124 /// outside of an `async fn`.
125 current_item: Option<Span>,
127 catch_scopes: Vec<NodeId>,
128 loop_scopes: Vec<NodeId>,
129 is_in_loop_condition: bool,
130 is_in_trait_impl: bool,
131 is_in_dyn_type: bool,
133 /// What to do when we encounter an "anonymous lifetime
134 /// reference". The term "anonymous" is meant to encompass both
135 /// `'_` lifetimes as well as fully elided cases where nothing is
136 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
137 anonymous_lifetime_mode: AnonymousLifetimeMode,
139 /// Used to create lifetime definitions from in-band lifetime usages.
140 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
141 /// When a named lifetime is encountered in a function or impl header and
142 /// has not been defined
143 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
144 /// to this list. The results of this list are then added to the list of
145 /// lifetime definitions in the corresponding impl or function generics.
146 lifetimes_to_define: Vec<(Span, ParamName)>,
148 /// `true` if in-band lifetimes are being collected. This is used to
149 /// indicate whether or not we're in a place where new lifetimes will result
150 /// in in-band lifetime definitions, such a function or an impl header,
151 /// including implicit lifetimes from `impl_header_lifetime_elision`.
152 is_collecting_in_band_lifetimes: bool,
154 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
155 /// When `is_collecting_in_band_lifetimes` is true, each lifetime is checked
156 /// against this list to see if it is already in-scope, or if a definition
157 /// needs to be created for it.
159 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
161 in_scope_lifetimes: Vec<ParamName>,
163 current_module: LocalDefId,
165 type_def_lifetime_params: DefIdMap<usize>,
167 current_hir_id_owner: Vec<(LocalDefId, u32)>,
168 item_local_id_counters: NodeMap<u32>,
169 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
171 allow_try_trait: Option<Lrc<[Symbol]>>,
172 allow_gen_future: Option<Lrc<[Symbol]>>,
175 pub trait ResolverAstLowering {
176 fn def_key(&mut self, id: DefId) -> DefKey;
178 fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
180 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
182 /// Obtains resolution for a `NodeId` with a single resolution.
183 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
185 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
186 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
188 /// Obtains resolution for a label with the given `NodeId`.
189 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
191 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
192 /// This should only return `None` during testing.
193 fn definitions(&mut self) -> &mut Definitions;
195 fn lint_buffer(&mut self) -> &mut LintBuffer;
197 fn next_node_id(&mut self) -> NodeId;
199 fn trait_map(&self) -> &NodeMap<Vec<hir::TraitCandidate>>;
201 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
203 fn local_def_id(&self, node: NodeId) -> LocalDefId;
208 node_id: ast::NodeId,
215 type NtToTokenstream = fn(&Nonterminal, &ParseSess, CanSynthesizeMissingTokens) -> TokenStream;
217 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
218 /// and if so, what meaning it has.
220 enum ImplTraitContext<'b, 'a> {
221 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
222 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
223 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
225 /// Newly generated parameters should be inserted into the given `Vec`.
226 Universal(&'b mut Vec<hir::GenericParam<'a>>, LocalDefId),
228 /// Treat `impl Trait` as shorthand for a new opaque type.
229 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
230 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
232 ReturnPositionOpaqueTy {
233 /// `DefId` for the parent function, used to look up necessary
234 /// information later.
236 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
237 origin: hir::OpaqueTyOrigin,
239 /// Impl trait in type aliases, consts and statics.
241 /// Set of lifetimes that this opaque type can capture, if it uses
242 /// them. This includes lifetimes bound since we entered this context.
246 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
249 /// Here the inner opaque type captures `'a` because it uses it. It doesn't
250 /// need to capture `'b` because it already inherits the lifetime
251 /// parameter from `A`.
252 // FIXME(impl_trait): but `required_region_bounds` will ICE later
254 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
255 /// Origin: Either OpaqueTyOrigin::Misc or OpaqueTyOrigin::Binding,
256 origin: hir::OpaqueTyOrigin,
258 /// `impl Trait` is not accepted in this position.
259 Disallowed(ImplTraitPosition),
262 /// Position in which `impl Trait` is disallowed.
263 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
264 enum ImplTraitPosition {
265 /// Disallowed in `let` / `const` / `static` bindings.
268 /// All other positions.
272 impl<'a> ImplTraitContext<'_, 'a> {
274 fn disallowed() -> Self {
275 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
278 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
279 use self::ImplTraitContext::*;
281 Universal(params, parent) => Universal(params, *parent),
282 ReturnPositionOpaqueTy { fn_def_id, origin } => {
283 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
285 OtherOpaqueTy { capturable_lifetimes, origin } => {
286 OtherOpaqueTy { capturable_lifetimes, origin: *origin }
288 Disallowed(pos) => Disallowed(*pos),
293 pub fn lower_crate<'a, 'hir>(
296 resolver: &'a mut dyn ResolverAstLowering,
297 nt_to_tokenstream: NtToTokenstream,
298 arena: &'hir Arena<'hir>,
299 ) -> hir::Crate<'hir> {
300 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
307 items: BTreeMap::new(),
308 trait_items: BTreeMap::new(),
309 impl_items: BTreeMap::new(),
310 foreign_items: BTreeMap::new(),
311 bodies: BTreeMap::new(),
312 trait_impls: BTreeMap::new(),
313 modules: BTreeMap::new(),
314 attrs: BTreeMap::default(),
315 exported_macros: Vec::new(),
316 non_exported_macro_attrs: Vec::new(),
317 catch_scopes: Vec::new(),
318 loop_scopes: Vec::new(),
319 is_in_loop_condition: false,
320 is_in_trait_impl: false,
321 is_in_dyn_type: false,
322 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
323 type_def_lifetime_params: Default::default(),
324 current_module: CRATE_DEF_ID,
325 current_hir_id_owner: vec![(CRATE_DEF_ID, 0)],
326 item_local_id_counters: Default::default(),
327 node_id_to_hir_id: IndexVec::new(),
328 generator_kind: None,
331 lifetimes_to_define: Vec::new(),
332 is_collecting_in_band_lifetimes: false,
333 in_scope_lifetimes: Vec::new(),
334 allow_try_trait: Some([sym::try_trait][..].into()),
335 allow_gen_future: Some([sym::gen_future][..].into()),
340 #[derive(Copy, Clone, PartialEq)]
342 /// Any path in a type context.
344 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
346 /// The `module::Type` in `module::Type::method` in an expression.
350 enum ParenthesizedGenericArgs {
355 /// What to do when we encounter an **anonymous** lifetime
356 /// reference. Anonymous lifetime references come in two flavors. You
357 /// have implicit, or fully elided, references to lifetimes, like the
358 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
359 /// or `Ref<'_, T>`. These often behave the same, but not always:
361 /// - certain usages of implicit references are deprecated, like
362 /// `Ref<T>`, and we sometimes just give hard errors in those cases
364 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
365 /// the same as `Box<dyn Foo + '_>`.
367 /// We describe the effects of the various modes in terms of three cases:
369 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
370 /// of a `&` (e.g., the missing lifetime in something like `&T`)
371 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
372 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
373 /// elided bounds follow special rules. Note that this only covers
374 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
375 /// '_>` is a case of "modern" elision.
376 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
377 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
378 /// non-deprecated equivalent.
380 /// Currently, the handling of lifetime elision is somewhat spread out
381 /// between HIR lowering and -- as described below -- the
382 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
383 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
384 /// everything into HIR lowering.
385 #[derive(Copy, Clone, Debug)]
386 enum AnonymousLifetimeMode {
387 /// For **Modern** cases, create a new anonymous region parameter
388 /// and reference that.
390 /// For **Dyn Bound** cases, pass responsibility to
391 /// `resolve_lifetime` code.
393 /// For **Deprecated** cases, report an error.
396 /// Give a hard error when either `&` or `'_` is written. Used to
397 /// rule out things like `where T: Foo<'_>`. Does not imply an
398 /// error on default object bounds (e.g., `Box<dyn Foo>`).
401 /// Pass responsibility to `resolve_lifetime` code for all cases.
405 struct TokenStreamLowering<'a> {
406 parse_sess: &'a ParseSess,
407 synthesize_tokens: CanSynthesizeMissingTokens,
408 nt_to_tokenstream: NtToTokenstream,
411 impl<'a> TokenStreamLowering<'a> {
412 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
413 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
416 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
418 TokenTree::Token(token) => self.lower_token(token),
419 TokenTree::Delimited(span, delim, tts) => {
420 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
425 fn lower_token(&mut self, token: Token) -> TokenStream {
427 token::Interpolated(nt) => {
428 let tts = (self.nt_to_tokenstream)(&nt, self.parse_sess, self.synthesize_tokens);
429 TokenTree::Delimited(
430 DelimSpan::from_single(token.span),
432 self.lower_token_stream(tts),
436 _ => TokenTree::Token(token).into(),
441 impl<'a, 'hir> LoweringContext<'a, 'hir> {
442 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
443 /// Full-crate AST visitor that inserts into a fresh
444 /// `LoweringContext` any information that may be
445 /// needed from arbitrary locations in the crate,
446 /// e.g., the number of lifetime generic parameters
447 /// declared for every type and trait definition.
448 struct MiscCollector<'tcx, 'lowering, 'hir> {
449 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
452 impl MiscCollector<'_, '_, '_> {
453 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree) {
455 UseTreeKind::Simple(_, id1, id2) => {
456 for &id in &[id1, id2] {
457 self.lctx.allocate_hir_id_counter(id);
460 UseTreeKind::Glob => (),
461 UseTreeKind::Nested(ref trees) => {
462 for &(ref use_tree, id) in trees {
463 self.lctx.allocate_hir_id_counter(id);
464 self.allocate_use_tree_hir_id_counters(use_tree);
471 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
472 fn visit_item(&mut self, item: &'tcx Item) {
473 self.lctx.allocate_hir_id_counter(item.id);
476 ItemKind::Struct(_, ref generics)
477 | ItemKind::Union(_, ref generics)
478 | ItemKind::Enum(_, ref generics)
479 | ItemKind::TyAlias(box TyAliasKind(_, ref generics, ..))
480 | ItemKind::Trait(box TraitKind(_, _, ref generics, ..)) => {
481 let def_id = self.lctx.resolver.local_def_id(item.id);
486 matches!(param.kind, ast::GenericParamKind::Lifetime { .. })
489 self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
491 ItemKind::Use(ref use_tree) => {
492 self.allocate_use_tree_hir_id_counters(use_tree);
497 visit::walk_item(self, item);
500 fn visit_assoc_item(&mut self, item: &'tcx AssocItem, ctxt: AssocCtxt) {
501 self.lctx.allocate_hir_id_counter(item.id);
502 visit::walk_assoc_item(self, item, ctxt);
505 fn visit_foreign_item(&mut self, item: &'tcx ForeignItem) {
506 self.lctx.allocate_hir_id_counter(item.id);
507 visit::walk_foreign_item(self, item);
510 fn visit_ty(&mut self, t: &'tcx Ty) {
512 // Mirrors the case in visit::walk_ty
513 TyKind::BareFn(ref f) => {
514 walk_list!(self, visit_generic_param, &f.generic_params);
515 // Mirrors visit::walk_fn_decl
516 for parameter in &f.decl.inputs {
517 // We don't lower the ids of argument patterns
518 self.visit_pat(¶meter.pat);
519 self.visit_ty(¶meter.ty)
521 self.visit_fn_ret_ty(&f.decl.output)
523 TyKind::ImplTrait(def_node_id, _) => {
524 self.lctx.allocate_hir_id_counter(def_node_id);
525 visit::walk_ty(self, t);
527 _ => visit::walk_ty(self, t),
532 self.lower_node_id(CRATE_NODE_ID);
533 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
535 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
536 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
538 let module = self.lower_mod(&c.items, c.span);
539 self.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
540 let body_ids = body_ids(&self.bodies);
542 c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
548 .filter_map(|(&k, v)| {
549 self.node_id_to_hir_id.get(k).and_then(|id| id.as_ref()).map(|id| (*id, v.clone()))
553 let mut def_id_to_hir_id = IndexVec::default();
555 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
556 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
557 if def_id_to_hir_id.len() <= def_id.index() {
558 def_id_to_hir_id.resize(def_id.index() + 1, None);
560 def_id_to_hir_id[def_id] = hir_id;
564 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
566 #[cfg(debug_assertions)]
567 for (&id, attrs) in self.attrs.iter() {
568 // Verify that we do not store empty slices in the map.
569 if attrs.is_empty() {
570 panic!("Stored empty attributes for {:?}", id);
575 item: hir::CrateItem { module, span: c.span },
576 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
577 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
579 trait_items: self.trait_items,
580 impl_items: self.impl_items,
581 foreign_items: self.foreign_items,
584 trait_impls: self.trait_impls,
585 modules: self.modules,
592 fn insert_item(&mut self, item: hir::Item<'hir>) -> hir::ItemId {
593 let id = hir::ItemId { def_id: item.def_id };
594 self.items.insert(id, item);
595 self.modules.entry(self.current_module).or_default().items.insert(id);
599 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
600 // Set up the counter if needed.
601 self.item_local_id_counters.entry(owner).or_insert(0);
602 // Always allocate the first `HirId` for the owner itself.
603 let lowered = self.lower_node_id_with_owner(owner, owner);
604 debug_assert_eq!(lowered.local_id.as_u32(), 0);
608 fn lower_node_id_generic(
611 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
613 assert_ne!(ast_node_id, DUMMY_NODE_ID);
615 let min_size = ast_node_id.as_usize() + 1;
617 if min_size > self.node_id_to_hir_id.len() {
618 self.node_id_to_hir_id.resize(min_size, None);
621 if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] {
624 // Generate a new `HirId`.
625 let hir_id = alloc_hir_id(self);
626 self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
632 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
634 .item_local_id_counters
635 .insert(owner, HIR_ID_COUNTER_LOCKED)
636 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
637 let def_id = self.resolver.local_def_id(owner);
638 self.current_hir_id_owner.push((def_id, counter));
640 let (new_def_id, new_counter) = self.current_hir_id_owner.pop().unwrap();
642 debug_assert!(def_id == new_def_id);
643 debug_assert!(new_counter >= counter);
645 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
646 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
650 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
651 /// the `LoweringContext`'s `NodeId => HirId` map.
652 /// Take care not to call this method if the resulting `HirId` is then not
653 /// actually used in the HIR, as that would trigger an assertion in the
654 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
655 /// properly. Calling the method twice with the same `NodeId` is fine though.
656 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
657 self.lower_node_id_generic(ast_node_id, |this| {
658 let &mut (owner, ref mut local_id_counter) =
659 this.current_hir_id_owner.last_mut().unwrap();
660 let local_id = *local_id_counter;
661 *local_id_counter += 1;
662 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
666 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
667 self.lower_node_id_generic(ast_node_id, |this| {
668 let local_id_counter = this
669 .item_local_id_counters
671 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
672 let local_id = *local_id_counter;
674 // We want to be sure not to modify the counter in the map while it
675 // is also on the stack. Otherwise we'll get lost updates when writing
676 // back from the stack to the map.
677 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
679 *local_id_counter += 1;
680 let owner = this.resolver.opt_local_def_id(owner).expect(
681 "you forgot to call `create_def` or are lowering node-IDs \
682 that do not belong to the current owner",
685 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
689 fn next_id(&mut self) -> hir::HirId {
690 let node_id = self.resolver.next_node_id();
691 self.lower_node_id(node_id)
694 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
696 self.lower_node_id_generic(id, |_| {
697 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
702 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
703 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
704 if pr.unresolved_segments() != 0 {
705 panic!("path not fully resolved: {:?}", pr);
711 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
712 self.resolver.get_import_res(id).present_items()
715 fn diagnostic(&self) -> &rustc_errors::Handler {
716 self.sess.diagnostic()
719 /// Reuses the span but adds information like the kind of the desugaring and features that are
720 /// allowed inside this span.
721 fn mark_span_with_reason(
723 reason: DesugaringKind,
725 allow_internal_unstable: Option<Lrc<[Symbol]>>,
727 span.mark_with_reason(allow_internal_unstable, reason, self.sess.edition())
730 fn with_anonymous_lifetime_mode<R>(
732 anonymous_lifetime_mode: AnonymousLifetimeMode,
733 op: impl FnOnce(&mut Self) -> R,
736 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
737 anonymous_lifetime_mode,
739 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
740 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
741 let result = op(self);
742 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
744 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
745 old_anonymous_lifetime_mode
750 /// Creates a new `hir::GenericParam` for every new lifetime and
751 /// type parameter encountered while evaluating `f`. Definitions
752 /// are created with the parent provided. If no `parent_id` is
753 /// provided, no definitions will be returned.
755 /// Presuming that in-band lifetimes are enabled, then
756 /// `self.anonymous_lifetime_mode` will be updated to match the
757 /// parameter while `f` is running (and restored afterwards).
758 fn collect_in_band_defs<T>(
760 parent_def_id: LocalDefId,
761 anonymous_lifetime_mode: AnonymousLifetimeMode,
762 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
763 ) -> (Vec<hir::GenericParam<'hir>>, T) {
764 assert!(!self.is_collecting_in_band_lifetimes);
765 assert!(self.lifetimes_to_define.is_empty());
766 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
768 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
769 self.is_collecting_in_band_lifetimes = true;
771 let (in_band_ty_params, res) = f(self);
773 self.is_collecting_in_band_lifetimes = false;
774 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
776 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
778 let params = lifetimes_to_define
780 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
781 .chain(in_band_ty_params.into_iter())
787 /// Converts a lifetime into a new generic parameter.
788 fn lifetime_to_generic_param(
792 parent_def_id: LocalDefId,
793 ) -> hir::GenericParam<'hir> {
794 let node_id = self.resolver.next_node_id();
796 // Get the name we'll use to make the def-path. Note
797 // that collisions are ok here and this shouldn't
798 // really show up for end-user.
799 let (str_name, kind) = match hir_name {
800 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
801 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
802 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
805 // Add a definition for the in-band lifetime def.
806 self.resolver.create_def(
809 DefPathData::LifetimeNs(str_name),
815 hir_id: self.lower_node_id(node_id),
819 pure_wrt_drop: false,
820 kind: hir::GenericParamKind::Lifetime { kind },
824 /// When there is a reference to some lifetime `'a`, and in-band
825 /// lifetimes are enabled, then we want to push that lifetime into
826 /// the vector of names to define later. In that case, it will get
827 /// added to the appropriate generics.
828 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
829 if !self.is_collecting_in_band_lifetimes {
833 if !self.sess.features_untracked().in_band_lifetimes {
837 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
841 let hir_name = ParamName::Plain(ident);
843 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
844 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
849 self.lifetimes_to_define.push((ident.span, hir_name));
852 /// When we have either an elided or `'_` lifetime in an impl
853 /// header, we convert it to an in-band lifetime.
854 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
855 assert!(self.is_collecting_in_band_lifetimes);
856 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
857 let hir_name = ParamName::Fresh(index);
858 self.lifetimes_to_define.push((span, hir_name));
862 // Evaluates `f` with the lifetimes in `params` in-scope.
863 // This is used to track which lifetimes have already been defined, and
864 // which are new in-band lifetimes that need to have a definition created
866 fn with_in_scope_lifetime_defs<T>(
868 params: &[GenericParam],
869 f: impl FnOnce(&mut Self) -> T,
871 let old_len = self.in_scope_lifetimes.len();
872 let lt_def_names = params.iter().filter_map(|param| match param.kind {
873 GenericParamKind::Lifetime { .. } => {
874 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
878 self.in_scope_lifetimes.extend(lt_def_names);
882 self.in_scope_lifetimes.truncate(old_len);
886 /// Appends in-band lifetime defs and argument-position `impl
887 /// Trait` defs to the existing set of generics.
889 /// Presuming that in-band lifetimes are enabled, then
890 /// `self.anonymous_lifetime_mode` will be updated to match the
891 /// parameter while `f` is running (and restored afterwards).
892 fn add_in_band_defs<T>(
895 parent_def_id: LocalDefId,
896 anonymous_lifetime_mode: AnonymousLifetimeMode,
897 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
898 ) -> (hir::Generics<'hir>, T) {
899 let (in_band_defs, (mut lowered_generics, res)) =
900 self.with_in_scope_lifetime_defs(&generics.params, |this| {
901 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
902 let mut params = Vec::new();
903 // Note: it is necessary to lower generics *before* calling `f`.
904 // When lowering `async fn`, there's a final step when lowering
905 // the return type that assumes that all in-scope lifetimes have
906 // already been added to either `in_scope_lifetimes` or
907 // `lifetimes_to_define`. If we swapped the order of these two,
908 // in-band-lifetimes introduced by generics or where-clauses
909 // wouldn't have been added yet.
910 let generics = this.lower_generics_mut(
912 ImplTraitContext::Universal(
914 this.current_hir_id_owner.last().unwrap().0,
917 let res = f(this, &mut params);
918 (params, (generics, res))
922 lowered_generics.params.extend(in_band_defs);
924 let lowered_generics = lowered_generics.into_generics(self.arena);
925 (lowered_generics, res)
928 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
929 let was_in_dyn_type = self.is_in_dyn_type;
930 self.is_in_dyn_type = in_scope;
932 let result = f(self);
934 self.is_in_dyn_type = was_in_dyn_type;
939 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
940 let was_in_loop_condition = self.is_in_loop_condition;
941 self.is_in_loop_condition = false;
943 let catch_scopes = mem::take(&mut self.catch_scopes);
944 let loop_scopes = mem::take(&mut self.loop_scopes);
946 self.catch_scopes = catch_scopes;
947 self.loop_scopes = loop_scopes;
949 self.is_in_loop_condition = was_in_loop_condition;
954 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
955 if attrs.is_empty() {
958 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
959 debug_assert!(!ret.is_empty());
960 self.attrs.insert(id, ret);
965 fn lower_attr(&self, attr: &Attribute) -> Attribute {
966 // Note that we explicitly do not walk the path. Since we don't really
967 // lower attributes (we use the AST version) there is nowhere to keep
968 // the `HirId`s. We don't actually need HIR version of attributes anyway.
969 // Tokens are also not needed after macro expansion and parsing.
970 let kind = match attr.kind {
971 AttrKind::Normal(ref item, _) => AttrKind::Normal(
973 path: item.path.clone(),
974 args: self.lower_mac_args(&item.args),
979 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
982 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
985 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
986 if let Some(&a) = self.attrs.get(&target_id) {
987 debug_assert!(!a.is_empty());
988 self.attrs.insert(id, a);
992 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
994 MacArgs::Empty => MacArgs::Empty,
995 MacArgs::Delimited(dspan, delim, ref tokens) => {
996 // This is either a non-key-value attribute, or a `macro_rules!` body.
997 // We either not have any nonterminals present (in the case of an attribute),
998 // or have tokens available for all nonterminals in the case of a nested
999 // `macro_rules`: e.g:
1002 // macro_rules! outer {
1004 // macro_rules! inner {
1011 // In both cases, we don't want to synthesize any tokens
1015 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
1018 // This is an inert key-value attribute - it will never be visible to macros
1019 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
1020 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
1021 MacArgs::Eq(eq_span, ref token) => {
1022 // In valid code the value is always representable as a single literal token.
1023 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
1024 if tokens.len() != 1 {
1026 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
1028 match tokens.into_trees().next() {
1029 Some(TokenTree::Token(token)) => token,
1030 Some(TokenTree::Delimited(_, delim, tokens)) => {
1031 if delim != token::NoDelim {
1032 sess.diagnostic().delay_span_bug(
1034 "unexpected delimiter in key-value attribute's value",
1037 unwrap_single_token(sess, tokens, span)
1039 None => Token::dummy(),
1043 let tokens = TokenStreamLowering {
1044 parse_sess: &self.sess.parse_sess,
1045 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
1046 nt_to_tokenstream: self.nt_to_tokenstream,
1048 .lower_token(token.clone());
1049 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
1054 fn lower_token_stream(
1056 tokens: TokenStream,
1057 synthesize_tokens: CanSynthesizeMissingTokens,
1059 TokenStreamLowering {
1060 parse_sess: &self.sess.parse_sess,
1062 nt_to_tokenstream: self.nt_to_tokenstream,
1064 .lower_token_stream(tokens)
1067 /// Given an associated type constraint like one of these:
1070 /// T: Iterator<Item: Debug>
1072 /// T: Iterator<Item = Debug>
1076 /// returns a `hir::TypeBinding` representing `Item`.
1077 fn lower_assoc_ty_constraint(
1079 constraint: &AssocTyConstraint,
1080 mut itctx: ImplTraitContext<'_, 'hir>,
1081 ) -> hir::TypeBinding<'hir> {
1082 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1084 // lower generic arguments of identifier in constraint
1085 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
1086 let gen_args_ctor = match gen_args {
1087 GenericArgs::AngleBracketed(ref data) => {
1088 self.lower_angle_bracketed_parameter_data(
1090 ParamMode::Explicit,
1095 GenericArgs::Parenthesized(ref data) => {
1096 let mut err = self.sess.struct_span_err(
1098 "parenthesized generic arguments cannot be used in associated type constraints"
1100 // FIXME: try to write a suggestion here
1102 self.lower_angle_bracketed_parameter_data(
1103 &data.as_angle_bracketed_args(),
1104 ParamMode::Explicit,
1110 self.arena.alloc(gen_args_ctor.into_generic_args(&self.arena))
1112 self.arena.alloc(hir::GenericArgs::none())
1115 let kind = match constraint.kind {
1116 AssocTyConstraintKind::Equality { ref ty } => {
1117 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1119 AssocTyConstraintKind::Bound { ref bounds } => {
1120 let mut capturable_lifetimes;
1121 let mut parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1122 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1123 let (desugar_to_impl_trait, itctx) = match itctx {
1124 // We are in the return position:
1126 // fn foo() -> impl Iterator<Item: Debug>
1130 // fn foo() -> impl Iterator<Item = impl Debug>
1131 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1132 | ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx),
1134 // We are in the argument position, but within a dyn type:
1136 // fn foo(x: dyn Iterator<Item: Debug>)
1140 // fn foo(x: dyn Iterator<Item = impl Debug>)
1141 ImplTraitContext::Universal(_, parent) if self.is_in_dyn_type => {
1142 parent_def_id = parent;
1146 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1147 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1148 // "impl trait context" to permit `impl Debug` in this position (it desugars
1149 // then to an opaque type).
1151 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1152 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1153 capturable_lifetimes = FxHashSet::default();
1156 ImplTraitContext::OtherOpaqueTy {
1157 capturable_lifetimes: &mut capturable_lifetimes,
1158 origin: hir::OpaqueTyOrigin::Misc,
1163 // We are in the parameter position, but not within a dyn type:
1165 // fn foo(x: impl Iterator<Item: Debug>)
1167 // so we leave it as is and this gets expanded in astconv to a bound like
1168 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1170 _ => (false, itctx),
1173 if desugar_to_impl_trait {
1174 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1175 // constructing the HIR for `impl bounds...` and then lowering that.
1177 let impl_trait_node_id = self.resolver.next_node_id();
1178 self.resolver.create_def(
1181 DefPathData::ImplTrait,
1186 self.with_dyn_type_scope(false, |this| {
1187 let node_id = this.resolver.next_node_id();
1188 let ty = this.lower_ty(
1191 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1192 span: constraint.span,
1198 hir::TypeBindingKind::Equality { ty }
1201 // Desugar `AssocTy: Bounds` into a type binding where the
1202 // later desugars into a trait predicate.
1203 let bounds = self.lower_param_bounds(bounds, itctx);
1205 hir::TypeBindingKind::Constraint { bounds }
1211 hir_id: self.lower_node_id(constraint.id),
1212 ident: constraint.ident,
1215 span: constraint.span,
1219 fn lower_generic_arg(
1221 arg: &ast::GenericArg,
1222 itctx: ImplTraitContext<'_, 'hir>,
1223 ) -> hir::GenericArg<'hir> {
1225 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1226 ast::GenericArg::Type(ty) => {
1227 // We parse const arguments as path types as we cannot distinguish them during
1228 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1229 // type and value namespaces. If we resolved the path in the value namespace, we
1230 // transform it into a generic const argument.
1231 if let TyKind::Path(ref qself, ref path) = ty.kind {
1232 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1233 let res = partial_res.base_res();
1234 if !res.matches_ns(Namespace::TypeNS) {
1236 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1240 // Construct a AnonConst where the expr is the "ty"'s path.
1242 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1243 let node_id = self.resolver.next_node_id();
1245 // Add a definition for the in-band const def.
1246 self.resolver.create_def(
1249 DefPathData::AnonConst,
1254 let path_expr = Expr {
1256 kind: ExprKind::Path(qself.clone(), path.clone()),
1258 attrs: AttrVec::new(),
1262 let ct = self.with_new_scopes(|this| hir::AnonConst {
1263 hir_id: this.lower_node_id(node_id),
1264 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1266 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1270 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1272 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1273 value: self.lower_anon_const(&ct),
1274 span: ct.value.span,
1279 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1280 self.arena.alloc(self.lower_ty_direct(t, itctx))
1286 qself: &Option<QSelf>,
1288 param_mode: ParamMode,
1289 itctx: ImplTraitContext<'_, 'hir>,
1290 ) -> hir::Ty<'hir> {
1291 let id = self.lower_node_id(t.id);
1292 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1293 let ty = self.ty_path(id, t.span, qpath);
1294 if let hir::TyKind::TraitObject(..) = ty.kind {
1295 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1300 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1301 hir::Ty { hir_id: self.next_id(), kind, span }
1304 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1305 self.ty(span, hir::TyKind::Tup(tys))
1308 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1309 let kind = match t.kind {
1310 TyKind::Infer => hir::TyKind::Infer,
1311 TyKind::Err => hir::TyKind::Err,
1312 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1313 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1314 TyKind::Rptr(ref region, ref mt) => {
1315 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1316 let lifetime = match *region {
1317 Some(ref lt) => self.lower_lifetime(lt),
1318 None => self.elided_ref_lifetime(span),
1320 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1322 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1323 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1324 let span = this.sess.source_map().next_point(t.span.shrink_to_lo());
1325 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1326 generic_params: this.lower_generic_params(
1328 &NodeMap::default(),
1329 ImplTraitContext::disallowed(),
1331 unsafety: this.lower_unsafety(f.unsafety),
1332 abi: this.lower_extern(f.ext, span, t.id),
1333 decl: this.lower_fn_decl(&f.decl, None, false, None),
1334 param_names: this.lower_fn_params_to_names(&f.decl),
1338 TyKind::Never => hir::TyKind::Never,
1339 TyKind::Tup(ref tys) => {
1340 hir::TyKind::Tup(self.arena.alloc_from_iter(
1341 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1344 TyKind::Paren(ref ty) => {
1345 return self.lower_ty_direct(ty, itctx);
1347 TyKind::Path(ref qself, ref path) => {
1348 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1350 TyKind::ImplicitSelf => {
1351 let res = self.expect_full_res(t.id);
1352 let res = self.lower_res(res);
1353 hir::TyKind::Path(hir::QPath::Resolved(
1355 self.arena.alloc(hir::Path {
1357 segments: arena_vec![self; hir::PathSegment::from_ident(
1358 Ident::with_dummy_span(kw::SelfUpper)
1364 TyKind::Array(ref ty, ref length) => {
1365 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1367 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1368 TyKind::TraitObject(ref bounds, kind) => {
1369 let mut lifetime_bound = None;
1370 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1372 this.arena.alloc_from_iter(bounds.iter().filter_map(
1373 |bound| match *bound {
1374 GenericBound::Trait(
1376 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1377 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1378 // `?const ?Bound` will cause an error during AST validation
1379 // anyways, so treat it like `?Bound` as compilation proceeds.
1380 GenericBound::Trait(
1382 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1384 GenericBound::Outlives(ref lifetime) => {
1385 if lifetime_bound.is_none() {
1386 lifetime_bound = Some(this.lower_lifetime(lifetime));
1392 let lifetime_bound =
1393 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1394 (bounds, lifetime_bound)
1396 if kind != TraitObjectSyntax::Dyn {
1397 self.maybe_lint_bare_trait(t.span, t.id, false);
1399 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1401 TyKind::ImplTrait(def_node_id, ref bounds) => {
1404 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1405 .lower_opaque_impl_trait(
1411 |this| this.lower_param_bounds(bounds, itctx),
1413 ImplTraitContext::OtherOpaqueTy { ref capturable_lifetimes, origin } => {
1414 // Reset capturable lifetimes, any nested impl trait
1415 // types will inherit lifetimes from this opaque type,
1416 // so don't need to capture them again.
1417 let nested_itctx = ImplTraitContext::OtherOpaqueTy {
1418 capturable_lifetimes: &mut FxHashSet::default(),
1421 self.lower_opaque_impl_trait(
1426 Some(capturable_lifetimes),
1427 |this| this.lower_param_bounds(bounds, nested_itctx),
1430 ImplTraitContext::Universal(in_band_ty_params, parent_def_id) => {
1431 // Add a definition for the in-band `Param`.
1432 let def_id = self.resolver.local_def_id(def_node_id);
1434 self.allocate_hir_id_counter(def_node_id);
1436 let hir_bounds = self.with_hir_id_owner(def_node_id, |this| {
1437 this.lower_param_bounds(
1439 ImplTraitContext::Universal(in_band_ty_params, parent_def_id),
1442 // Set the name to `impl Bound1 + Bound2`.
1443 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1444 in_band_ty_params.push(hir::GenericParam {
1445 hir_id: self.lower_node_id(def_node_id),
1446 name: ParamName::Plain(ident),
1447 pure_wrt_drop: false,
1450 kind: hir::GenericParamKind::Type {
1452 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1456 hir::TyKind::Path(hir::QPath::Resolved(
1458 self.arena.alloc(hir::Path {
1460 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1461 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1465 ImplTraitContext::Disallowed(pos) => {
1466 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1467 "bindings or function and inherent method return types"
1469 "function and inherent method return types"
1471 let mut err = struct_span_err!(
1475 "`impl Trait` not allowed outside of {}",
1478 if pos == ImplTraitPosition::Binding && self.sess.is_nightly_build() {
1480 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1481 attributes to enable",
1489 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1490 TyKind::CVarArgs => {
1491 self.sess.delay_span_bug(
1493 "`TyKind::CVarArgs` should have been handled elsewhere",
1499 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1502 fn lower_opaque_impl_trait(
1505 fn_def_id: Option<DefId>,
1506 origin: hir::OpaqueTyOrigin,
1507 opaque_ty_node_id: NodeId,
1508 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1509 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1510 ) -> hir::TyKind<'hir> {
1512 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1513 fn_def_id, opaque_ty_node_id, span,
1516 // Make sure we know that some funky desugaring has been going on here.
1517 // This is a first: there is code in other places like for loop
1518 // desugaring that explicitly states that we don't want to track that.
1519 // Not tracking it makes lints in rustc and clippy very fragile, as
1520 // frequently opened issues show.
1521 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1523 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1525 self.allocate_hir_id_counter(opaque_ty_node_id);
1527 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1529 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1533 capturable_lifetimes,
1536 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1538 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1540 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1541 let opaque_ty_item = hir::OpaqueTy {
1542 generics: hir::Generics {
1543 params: lifetime_defs,
1544 where_clause: hir::WhereClause { predicates: &[], span },
1548 impl_trait_fn: fn_def_id,
1552 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1553 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
1555 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1556 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1560 /// Registers a new opaque type with the proper `NodeId`s and
1561 /// returns the lowered node-ID for the opaque type.
1562 fn generate_opaque_type(
1564 opaque_ty_id: LocalDefId,
1565 opaque_ty_item: hir::OpaqueTy<'hir>,
1567 opaque_ty_span: Span,
1569 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1570 // Generate an `type Foo = impl Trait;` declaration.
1571 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1572 let opaque_ty_item = hir::Item {
1573 def_id: opaque_ty_id,
1574 ident: Ident::invalid(),
1575 kind: opaque_ty_item_kind,
1576 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1577 span: opaque_ty_span,
1580 // Insert the item into the global item list. This usually happens
1581 // automatically for all AST items. But this opaque type item
1582 // does not actually exist in the AST.
1583 self.insert_item(opaque_ty_item);
1586 fn lifetimes_from_impl_trait_bounds(
1588 opaque_ty_id: NodeId,
1589 parent_def_id: LocalDefId,
1590 bounds: hir::GenericBounds<'hir>,
1591 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
1592 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1594 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1595 parent_def_id={:?}, \
1597 opaque_ty_id, parent_def_id, bounds,
1600 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1601 // appear in the bounds, excluding lifetimes that are created within the bounds.
1602 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1603 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1604 context: &'r mut LoweringContext<'a, 'hir>,
1606 opaque_ty_id: NodeId,
1607 collect_elided_lifetimes: bool,
1608 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1609 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1610 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1611 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1612 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
1615 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1616 type Map = intravisit::ErasedMap<'v>;
1618 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1619 intravisit::NestedVisitorMap::None
1622 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1623 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1624 if parameters.parenthesized {
1625 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1626 self.collect_elided_lifetimes = false;
1627 intravisit::walk_generic_args(self, span, parameters);
1628 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1630 intravisit::walk_generic_args(self, span, parameters);
1634 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1635 // Don't collect elided lifetimes used inside of `fn()` syntax.
1636 if let hir::TyKind::BareFn(_) = t.kind {
1637 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1638 self.collect_elided_lifetimes = false;
1640 // Record the "stack height" of `for<'a>` lifetime bindings
1641 // to be able to later fully undo their introduction.
1642 let old_len = self.currently_bound_lifetimes.len();
1643 intravisit::walk_ty(self, t);
1644 self.currently_bound_lifetimes.truncate(old_len);
1646 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1648 intravisit::walk_ty(self, t)
1652 fn visit_poly_trait_ref(
1654 trait_ref: &'v hir::PolyTraitRef<'v>,
1655 modifier: hir::TraitBoundModifier,
1657 // Record the "stack height" of `for<'a>` lifetime bindings
1658 // to be able to later fully undo their introduction.
1659 let old_len = self.currently_bound_lifetimes.len();
1660 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1661 self.currently_bound_lifetimes.truncate(old_len);
1664 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1665 // Record the introduction of 'a in `for<'a> ...`.
1666 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1667 // Introduce lifetimes one at a time so that we can handle
1668 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1669 let lt_name = hir::LifetimeName::Param(param.name);
1670 self.currently_bound_lifetimes.push(lt_name);
1673 intravisit::walk_generic_param(self, param);
1676 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1677 let name = match lifetime.name {
1678 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1679 if self.collect_elided_lifetimes {
1680 // Use `'_` for both implicit and underscore lifetimes in
1681 // `type Foo<'_> = impl SomeTrait<'_>;`.
1682 hir::LifetimeName::Underscore
1687 hir::LifetimeName::Param(_) => lifetime.name,
1689 // Refers to some other lifetime that is "in
1690 // scope" within the type.
1691 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1693 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1696 if !self.currently_bound_lifetimes.contains(&name)
1697 && !self.already_defined_lifetimes.contains(&name)
1698 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
1700 self.already_defined_lifetimes.insert(name);
1702 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1703 hir_id: self.context.next_id(),
1704 span: lifetime.span,
1708 let def_node_id = self.context.resolver.next_node_id();
1710 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1711 self.context.resolver.create_def(
1714 DefPathData::LifetimeNs(name.ident().name),
1719 let (name, kind) = match name {
1720 hir::LifetimeName::Underscore => (
1721 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1722 hir::LifetimeParamKind::Elided,
1724 hir::LifetimeName::Param(param_name) => {
1725 (param_name, hir::LifetimeParamKind::Explicit)
1727 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1730 self.output_lifetime_params.push(hir::GenericParam {
1733 span: lifetime.span,
1734 pure_wrt_drop: false,
1736 kind: hir::GenericParamKind::Lifetime { kind },
1742 let mut lifetime_collector = ImplTraitLifetimeCollector {
1744 parent: parent_def_id,
1746 collect_elided_lifetimes: true,
1747 currently_bound_lifetimes: Vec::new(),
1748 already_defined_lifetimes: FxHashSet::default(),
1749 output_lifetimes: Vec::new(),
1750 output_lifetime_params: Vec::new(),
1751 lifetimes_to_include,
1754 for bound in bounds {
1755 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1758 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1762 self.arena.alloc_from_iter(output_lifetimes),
1763 self.arena.alloc_from_iter(output_lifetime_params),
1767 fn lower_local(&mut self, l: &Local) -> hir::Local<'hir> {
1768 let ty = l.ty.as_ref().map(|t| {
1769 let mut capturable_lifetimes;
1772 if self.sess.features_untracked().impl_trait_in_bindings {
1773 capturable_lifetimes = FxHashSet::default();
1774 ImplTraitContext::OtherOpaqueTy {
1775 capturable_lifetimes: &mut capturable_lifetimes,
1776 origin: hir::OpaqueTyOrigin::Binding,
1779 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1783 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1784 let hir_id = self.lower_node_id(l.id);
1785 self.lower_attrs(hir_id, &l.attrs);
1789 pat: self.lower_pat(&l.pat),
1792 source: hir::LocalSource::Normal,
1796 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1797 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1798 // as they are not explicit in HIR/Ty function signatures.
1799 // (instead, the `c_variadic` flag is set to `true`)
1800 let mut inputs = &decl.inputs[..];
1801 if decl.c_variadic() {
1802 inputs = &inputs[..inputs.len() - 1];
1804 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1805 PatKind::Ident(_, ident, _) => ident,
1806 _ => Ident::new(kw::Empty, param.pat.span),
1810 // Lowers a function declaration.
1812 // `decl`: the unlowered (AST) function declaration.
1813 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1814 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1815 // `make_ret_async` is also `Some`.
1816 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1817 // This guards against trait declarations and implementations where `impl Trait` is
1819 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1820 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1821 // return type `impl Trait` item.
1825 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1826 impl_trait_return_allow: bool,
1827 make_ret_async: Option<NodeId>,
1828 ) -> &'hir hir::FnDecl<'hir> {
1832 in_band_ty_params: {:?}, \
1833 impl_trait_return_allow: {}, \
1834 make_ret_async: {:?})",
1835 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1837 let lt_mode = if make_ret_async.is_some() {
1838 // In `async fn`, argument-position elided lifetimes
1839 // must be transformed into fresh generic parameters so that
1840 // they can be applied to the opaque `impl Trait` return type.
1841 AnonymousLifetimeMode::CreateParameter
1843 self.anonymous_lifetime_mode
1846 let c_variadic = decl.c_variadic();
1848 // Remember how many lifetimes were already around so that we can
1849 // only look at the lifetime parameters introduced by the arguments.
1850 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1851 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1852 // as they are not explicit in HIR/Ty function signatures.
1853 // (instead, the `c_variadic` flag is set to `true`)
1854 let mut inputs = &decl.inputs[..];
1856 inputs = &inputs[..inputs.len() - 1];
1858 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1859 if let Some((_, ibty)) = &mut in_band_ty_params {
1860 this.lower_ty_direct(
1862 ImplTraitContext::Universal(
1864 this.current_hir_id_owner.last().unwrap().0,
1868 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1873 let output = if let Some(ret_id) = make_ret_async {
1874 self.lower_async_fn_ret_ty(
1876 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1881 FnRetTy::Ty(ref ty) => {
1882 let context = match in_band_ty_params {
1883 Some((def_id, _)) if impl_trait_return_allow => {
1884 ImplTraitContext::ReturnPositionOpaqueTy {
1886 origin: hir::OpaqueTyOrigin::FnReturn,
1889 _ => ImplTraitContext::disallowed(),
1891 hir::FnRetTy::Return(self.lower_ty(ty, context))
1893 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(span),
1897 self.arena.alloc(hir::FnDecl {
1901 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1902 use BindingMode::{ByRef, ByValue};
1903 let is_mutable_pat = matches!(
1905 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1909 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1910 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1911 // Given we are only considering `ImplicitSelf` types, we needn't consider
1912 // the case where we have a mutable pattern to a reference as that would
1913 // no longer be an `ImplicitSelf`.
1914 TyKind::Rptr(_, ref mt)
1915 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1917 hir::ImplicitSelfKind::MutRef
1919 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1920 hir::ImplicitSelfKind::ImmRef
1922 _ => hir::ImplicitSelfKind::None,
1928 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1929 // combined with the following definition of `OpaqueTy`:
1931 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1933 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1934 // `output`: unlowered output type (`T` in `-> T`)
1935 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1936 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1937 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1938 fn lower_async_fn_ret_ty(
1942 opaque_ty_node_id: NodeId,
1943 ) -> hir::FnRetTy<'hir> {
1945 "lower_async_fn_ret_ty(\
1948 opaque_ty_node_id={:?})",
1949 output, fn_def_id, opaque_ty_node_id,
1952 let span = output.span();
1954 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1956 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1958 self.allocate_hir_id_counter(opaque_ty_node_id);
1960 // When we create the opaque type for this async fn, it is going to have
1961 // to capture all the lifetimes involved in the signature (including in the
1962 // return type). This is done by introducing lifetime parameters for:
1964 // - all the explicitly declared lifetimes from the impl and function itself;
1965 // - all the elided lifetimes in the fn arguments;
1966 // - all the elided lifetimes in the return type.
1968 // So for example in this snippet:
1971 // impl<'a> Foo<'a> {
1972 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1973 // // ^ '0 ^ '1 ^ '2
1974 // // elided lifetimes used below
1979 // we would create an opaque type like:
1982 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1985 // and we would then desugar `bar` to the equivalent of:
1988 // impl<'a> Foo<'a> {
1989 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1993 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1994 // this is because the elided lifetimes from the return type
1995 // should be figured out using the ordinary elision rules, and
1996 // this desugaring achieves that.
1998 // The variable `input_lifetimes_count` tracks the number of
1999 // lifetime parameters to the opaque type *not counting* those
2000 // lifetimes elided in the return type. This includes those
2001 // that are explicitly declared (`in_scope_lifetimes`) and
2002 // those elided lifetimes we found in the arguments (current
2003 // content of `lifetimes_to_define`). Next, we will process
2004 // the return type, which will cause `lifetimes_to_define` to
2006 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2008 let lifetime_params = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2009 // We have to be careful to get elision right here. The
2010 // idea is that we create a lifetime parameter for each
2011 // lifetime in the return type. So, given a return type
2012 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2013 // Future<Output = &'1 [ &'2 u32 ]>`.
2015 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2016 // hence the elision takes place at the fn site.
2017 let future_bound = this
2018 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
2019 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
2022 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2024 // Calculate all the lifetimes that should be captured
2025 // by the opaque type. This should include all in-scope
2026 // lifetime parameters, including those defined in-band.
2028 // Note: this must be done after lowering the output type,
2029 // as the output type may introduce new in-band lifetimes.
2030 let lifetime_params: Vec<(Span, ParamName)> = this
2034 .map(|name| (name.ident().span, name))
2035 .chain(this.lifetimes_to_define.iter().cloned())
2038 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2039 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2040 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2042 let generic_params =
2043 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
2044 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
2047 let opaque_ty_item = hir::OpaqueTy {
2048 generics: hir::Generics {
2049 params: generic_params,
2050 where_clause: hir::WhereClause { predicates: &[], span },
2053 bounds: arena_vec![this; future_bound],
2054 impl_trait_fn: Some(fn_def_id),
2055 origin: hir::OpaqueTyOrigin::AsyncFn,
2058 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
2059 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
2064 // As documented above on the variable
2065 // `input_lifetimes_count`, we need to create the lifetime
2066 // arguments to our opaque type. Continuing with our example,
2067 // we're creating the type arguments for the return type:
2070 // Bar<'a, 'b, '0, '1, '_>
2073 // For the "input" lifetime parameters, we wish to create
2074 // references to the parameters themselves, including the
2075 // "implicit" ones created from parameter types (`'a`, `'b`,
2078 // For the "output" lifetime parameters, we just want to
2080 let mut generic_args = Vec::with_capacity(lifetime_params.len());
2081 generic_args.extend(lifetime_params[..input_lifetimes_count].iter().map(
2082 |&(span, hir_name)| {
2083 // Input lifetime like `'a` or `'1`:
2084 GenericArg::Lifetime(hir::Lifetime {
2085 hir_id: self.next_id(),
2087 name: hir::LifetimeName::Param(hir_name),
2091 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
2092 // Output lifetime like `'_`.
2093 GenericArg::Lifetime(hir::Lifetime {
2094 hir_id: self.next_id(),
2096 name: hir::LifetimeName::Implicit,
2098 let generic_args = self.arena.alloc_from_iter(generic_args);
2100 // Create the `Foo<...>` reference itself. Note that the `type
2101 // Foo = impl Trait` is, internally, created as a child of the
2102 // async fn, so the *type parameters* are inherited. It's
2103 // only the lifetime parameters that we must supply.
2105 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
2106 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2107 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2110 /// Transforms `-> T` into `Future<Output = T>`.
2111 fn lower_async_fn_output_type_to_future_bound(
2116 ) -> hir::GenericBound<'hir> {
2117 // Compute the `T` in `Future<Output = T>` from the return type.
2118 let output_ty = match output {
2119 FnRetTy::Ty(ty) => {
2120 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2121 // `impl Future` opaque type that `async fn` implicitly
2123 let context = ImplTraitContext::ReturnPositionOpaqueTy {
2125 origin: hir::OpaqueTyOrigin::FnReturn,
2127 self.lower_ty(ty, context)
2129 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2133 let future_args = self.arena.alloc(hir::GenericArgs {
2135 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2136 parenthesized: false,
2139 hir::GenericBound::LangItemTrait(
2140 // ::std::future::Future<future_params>
2141 hir::LangItem::Future,
2148 fn lower_param_bound(
2151 itctx: ImplTraitContext<'_, 'hir>,
2152 ) -> hir::GenericBound<'hir> {
2154 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2155 self.lower_poly_trait_ref(ty, itctx),
2156 self.lower_trait_bound_modifier(modifier),
2158 GenericBound::Outlives(ref lifetime) => {
2159 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2164 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2165 let span = l.ident.span;
2167 ident if ident.name == kw::StaticLifetime => {
2168 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2170 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2171 AnonymousLifetimeMode::CreateParameter => {
2172 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2173 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2176 AnonymousLifetimeMode::PassThrough => {
2177 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2180 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2183 self.maybe_collect_in_band_lifetime(ident);
2184 let param_name = ParamName::Plain(ident);
2185 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2190 fn new_named_lifetime(
2194 name: hir::LifetimeName,
2195 ) -> hir::Lifetime {
2196 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2199 fn lower_generic_params_mut<'s>(
2201 params: &'s [GenericParam],
2202 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2203 mut itctx: ImplTraitContext<'s, 'hir>,
2204 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2207 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2210 fn lower_generic_params(
2212 params: &[GenericParam],
2213 add_bounds: &NodeMap<Vec<GenericBound>>,
2214 itctx: ImplTraitContext<'_, 'hir>,
2215 ) -> &'hir [hir::GenericParam<'hir>] {
2216 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2219 fn lower_generic_param(
2221 param: &GenericParam,
2222 add_bounds: &NodeMap<Vec<GenericBound>>,
2223 mut itctx: ImplTraitContext<'_, 'hir>,
2224 ) -> hir::GenericParam<'hir> {
2225 let mut bounds: Vec<_> = self
2226 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2227 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2230 let (name, kind) = match param.kind {
2231 GenericParamKind::Lifetime => {
2232 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2233 self.is_collecting_in_band_lifetimes = false;
2236 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2237 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2239 let param_name = match lt.name {
2240 hir::LifetimeName::Param(param_name) => param_name,
2241 hir::LifetimeName::Implicit
2242 | hir::LifetimeName::Underscore
2243 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2244 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2245 self.sess.diagnostic().span_bug(
2247 "object-lifetime-default should not occur here",
2250 hir::LifetimeName::Error => ParamName::Error,
2254 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2256 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2260 GenericParamKind::Type { ref default, .. } => {
2261 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2262 if !add_bounds.is_empty() {
2263 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2264 bounds.extend(params);
2267 let kind = hir::GenericParamKind::Type {
2268 default: default.as_ref().map(|x| {
2271 ImplTraitContext::OtherOpaqueTy {
2272 capturable_lifetimes: &mut FxHashSet::default(),
2273 origin: hir::OpaqueTyOrigin::Misc,
2280 .filter(|attr| self.sess.check_name(attr, sym::rustc_synthetic))
2281 .map(|_| hir::SyntheticTyParamKind::FromAttr)
2285 (hir::ParamName::Plain(param.ident), kind)
2287 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2289 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2290 this.lower_ty(&ty, ImplTraitContext::disallowed())
2292 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2294 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty, default })
2298 let hir_id = self.lower_node_id(param.id);
2299 self.lower_attrs(hir_id, ¶m.attrs);
2303 span: param.ident.span,
2304 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
2305 bounds: self.arena.alloc_from_iter(bounds),
2313 itctx: ImplTraitContext<'_, 'hir>,
2314 ) -> hir::TraitRef<'hir> {
2315 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2316 hir::QPath::Resolved(None, path) => path,
2317 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2319 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2322 fn lower_poly_trait_ref(
2325 mut itctx: ImplTraitContext<'_, 'hir>,
2326 ) -> hir::PolyTraitRef<'hir> {
2327 let bound_generic_params = self.lower_generic_params(
2328 &p.bound_generic_params,
2329 &NodeMap::default(),
2333 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2334 // Any impl Trait types defined within this scope can capture
2335 // lifetimes bound on this predicate.
2336 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
2337 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
2338 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
2342 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2343 capturable_lifetimes.extend(lt_def_names.clone());
2346 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2348 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2349 for param in lt_def_names {
2350 capturable_lifetimes.remove(¶m);
2356 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
2359 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2360 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2363 fn lower_param_bounds(
2365 bounds: &[GenericBound],
2366 itctx: ImplTraitContext<'_, 'hir>,
2367 ) -> hir::GenericBounds<'hir> {
2368 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2371 fn lower_param_bounds_mut<'s>(
2373 bounds: &'s [GenericBound],
2374 mut itctx: ImplTraitContext<'s, 'hir>,
2375 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2376 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2379 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2380 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2383 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
2384 let (stmts, expr) = match &*b.stmts {
2385 [stmts @ .., Stmt { kind: StmtKind::Expr(e), .. }] => (stmts, Some(&*e)),
2386 stmts => (stmts, None),
2388 let stmts = self.arena.alloc_from_iter(stmts.iter().flat_map(|stmt| self.lower_stmt(stmt)));
2389 let expr = expr.map(|e| self.lower_expr(e));
2390 let rules = self.lower_block_check_mode(&b.rules);
2391 let hir_id = self.lower_node_id(b.id);
2393 hir::Block { hir_id, stmts, expr, rules, span: b.span, targeted_by_break }
2396 /// Lowers a block directly to an expression, presuming that it
2397 /// has no attributes and is not targeted by a `break`.
2398 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2399 let block = self.lower_block(b, false);
2400 self.expr_block(block, AttrVec::new())
2403 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2404 self.with_new_scopes(|this| hir::AnonConst {
2405 hir_id: this.lower_node_id(c.id),
2406 body: this.lower_const_body(c.value.span, Some(&c.value)),
2410 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2411 let (hir_id, kind) = match s.kind {
2412 StmtKind::Local(ref l) => {
2413 let l = self.lower_local(l);
2414 let hir_id = self.lower_node_id(s.id);
2415 self.alias_attrs(hir_id, l.hir_id);
2416 return smallvec![hir::Stmt {
2418 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2422 StmtKind::Item(ref it) => {
2423 // Can only use the ID once.
2424 let mut id = Some(s.id);
2431 .map(|id| self.lower_node_id(id))
2432 .unwrap_or_else(|| self.next_id());
2434 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2438 StmtKind::Expr(ref e) => {
2439 let e = self.lower_expr(e);
2440 let hir_id = self.lower_node_id(s.id);
2441 self.alias_attrs(hir_id, e.hir_id);
2442 (hir_id, hir::StmtKind::Expr(e))
2444 StmtKind::Semi(ref e) => {
2445 let e = self.lower_expr(e);
2446 let hir_id = self.lower_node_id(s.id);
2447 self.alias_attrs(hir_id, e.hir_id);
2448 (hir_id, hir::StmtKind::Semi(e))
2450 StmtKind::Empty => return smallvec![],
2451 StmtKind::MacCall(..) => panic!("shouldn't exist here"),
2453 smallvec![hir::Stmt { hir_id, kind, span: s.span }]
2456 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2458 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2459 BlockCheckMode::Unsafe(u) => {
2460 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2465 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2467 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2468 UserProvided => hir::UnsafeSource::UserProvided,
2472 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2474 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2475 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2477 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2478 // placeholder for compilation to proceed.
2479 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2480 hir::TraitBoundModifier::Maybe
2485 // Helper methods for building HIR.
2487 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2488 hir::Stmt { span, kind, hir_id: self.next_id() }
2491 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2492 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2497 attrs: Option<&'hir [Attribute]>,
2499 init: Option<&'hir hir::Expr<'hir>>,
2500 pat: &'hir hir::Pat<'hir>,
2501 source: hir::LocalSource,
2502 ) -> hir::Stmt<'hir> {
2503 let hir_id = self.next_id();
2504 if let Some(a) = attrs {
2505 debug_assert!(!a.is_empty());
2506 self.attrs.insert(hir_id, a);
2508 let local = hir::Local { hir_id, init, pat, source, span, ty: None };
2509 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2512 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2513 self.block_all(expr.span, &[], Some(expr))
2519 stmts: &'hir [hir::Stmt<'hir>],
2520 expr: Option<&'hir hir::Expr<'hir>>,
2521 ) -> &'hir hir::Block<'hir> {
2522 let blk = hir::Block {
2525 hir_id: self.next_id(),
2526 rules: hir::BlockCheckMode::DefaultBlock,
2528 targeted_by_break: false,
2530 self.arena.alloc(blk)
2533 /// Constructs a `true` or `false` literal pattern.
2534 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2535 let expr = self.expr_bool(span, val);
2536 self.pat(span, hir::PatKind::Lit(expr))
2539 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2540 let field = self.single_pat_field(span, pat);
2541 self.pat_lang_item_variant(span, hir::LangItem::ResultOk, field)
2544 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2545 let field = self.single_pat_field(span, pat);
2546 self.pat_lang_item_variant(span, hir::LangItem::ResultErr, field)
2549 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2550 let field = self.single_pat_field(span, pat);
2551 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2554 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2555 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2558 fn single_pat_field(
2561 pat: &'hir hir::Pat<'hir>,
2562 ) -> &'hir [hir::PatField<'hir>] {
2563 let field = hir::PatField {
2564 hir_id: self.next_id(),
2565 ident: Ident::new(sym::integer(0), span),
2566 is_shorthand: false,
2570 arena_vec![self; field]
2573 fn pat_lang_item_variant(
2576 lang_item: hir::LangItem,
2577 fields: &'hir [hir::PatField<'hir>],
2578 ) -> &'hir hir::Pat<'hir> {
2579 let qpath = hir::QPath::LangItem(lang_item, span);
2580 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2583 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2584 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2587 fn pat_ident_binding_mode(
2591 bm: hir::BindingAnnotation,
2592 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2593 let hir_id = self.next_id();
2596 self.arena.alloc(hir::Pat {
2598 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2600 default_binding_modes: true,
2606 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2607 self.pat(span, hir::PatKind::Wild)
2610 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2611 self.arena.alloc(hir::Pat {
2612 hir_id: self.next_id(),
2615 default_binding_modes: true,
2619 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2620 self.arena.alloc(hir::Pat {
2621 hir_id: self.next_id(),
2624 default_binding_modes: false,
2630 mut hir_id: hir::HirId,
2632 qpath: hir::QPath<'hir>,
2633 ) -> hir::Ty<'hir> {
2634 let kind = match qpath {
2635 hir::QPath::Resolved(None, path) => {
2636 // Turn trait object paths into `TyKind::TraitObject` instead.
2638 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2639 let principal = hir::PolyTraitRef {
2640 bound_generic_params: &[],
2641 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2645 // The original ID is taken by the `PolyTraitRef`,
2646 // so the `Ty` itself needs a different one.
2647 hir_id = self.next_id();
2648 hir::TyKind::TraitObject(
2649 arena_vec![self; principal],
2650 self.elided_dyn_bound(span),
2651 TraitObjectSyntax::None,
2654 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2657 _ => hir::TyKind::Path(qpath),
2660 hir::Ty { hir_id, kind, span }
2663 /// Invoked to create the lifetime argument for a type `&T`
2664 /// with no explicit lifetime.
2665 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2666 match self.anonymous_lifetime_mode {
2667 // Intercept when we are in an impl header or async fn and introduce an in-band
2669 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2671 AnonymousLifetimeMode::CreateParameter => {
2672 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2674 hir_id: self.next_id(),
2676 name: hir::LifetimeName::Param(fresh_name),
2680 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2682 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2686 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2687 /// return a "error lifetime".
2688 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2689 let (id, msg, label) = match id {
2690 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2693 self.resolver.next_node_id(),
2694 "`&` without an explicit lifetime name cannot be used here",
2695 "explicit lifetime name needed here",
2699 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2700 err.span_label(span, label);
2703 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2706 /// Invoked to create the lifetime argument(s) for a path like
2707 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2708 /// sorts of cases are deprecated. This may therefore report a warning or an
2709 /// error, depending on the mode.
2710 fn elided_path_lifetimes<'s>(
2714 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2715 (0..count).map(move |_| self.elided_path_lifetime(span))
2718 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2719 match self.anonymous_lifetime_mode {
2720 AnonymousLifetimeMode::CreateParameter => {
2721 // We should have emitted E0726 when processing this path above
2723 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2724 let id = self.resolver.next_node_id();
2725 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2727 // `PassThrough` is the normal case.
2728 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2729 // is unsuitable here, as these can occur from missing lifetime parameters in a
2730 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2731 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2732 // later, at which point a suitable error will be emitted.
2733 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2734 self.new_implicit_lifetime(span)
2739 /// Invoked to create the lifetime argument(s) for an elided trait object
2740 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2741 /// when the bound is written, even if it is written with `'_` like in
2742 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2743 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2744 match self.anonymous_lifetime_mode {
2745 // NB. We intentionally ignore the create-parameter mode here.
2746 // and instead "pass through" to resolve-lifetimes, which will apply
2747 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2748 // do not act like other elided lifetimes. In other words, given this:
2750 // impl Foo for Box<dyn Debug>
2752 // we do not introduce a fresh `'_` to serve as the bound, but instead
2753 // ultimately translate to the equivalent of:
2755 // impl Foo for Box<dyn Debug + 'static>
2757 // `resolve_lifetime` has the code to make that happen.
2758 AnonymousLifetimeMode::CreateParameter => {}
2760 AnonymousLifetimeMode::ReportError => {
2761 // ReportError applies to explicit use of `'_`.
2764 // This is the normal case.
2765 AnonymousLifetimeMode::PassThrough => {}
2768 let r = hir::Lifetime {
2769 hir_id: self.next_id(),
2771 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2773 debug!("elided_dyn_bound: r={:?}", r);
2777 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2778 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
2781 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2782 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2783 // call site which do not have a macro backtrace. See #61963.
2784 let is_macro_callsite = self
2787 .span_to_snippet(span)
2788 .map(|snippet| snippet.starts_with("#["))
2790 if !is_macro_callsite {
2791 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2795 "trait objects without an explicit `dyn` are deprecated",
2796 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2801 fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId, default: Abi) {
2802 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2803 // call site which do not have a macro backtrace. See #61963.
2804 let is_macro_callsite = self
2807 .span_to_snippet(span)
2808 .map(|snippet| snippet.starts_with("#["))
2810 if !is_macro_callsite {
2811 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2815 "extern declarations without an explicit ABI are deprecated",
2816 BuiltinLintDiagnostics::MissingAbi(span, default),
2822 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2823 // Sorting by span ensures that we get things in order within a
2824 // file, and also puts the files in a sensible order.
2825 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2826 body_ids.sort_by_key(|b| bodies[b].value.span);
2830 /// Helper struct for delayed construction of GenericArgs.
2831 struct GenericArgsCtor<'hir> {
2832 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2833 bindings: &'hir [hir::TypeBinding<'hir>],
2834 parenthesized: bool,
2837 impl<'hir> GenericArgsCtor<'hir> {
2838 fn is_empty(&self) -> bool {
2839 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2842 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2844 args: arena.alloc_from_iter(self.args),
2845 bindings: self.bindings,
2846 parenthesized: self.parenthesized,