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), then you 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 #![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 /// When inside an `async` context, this is the `HirId` of the
118 /// `task_context` local bound to the resume argument of the generator.
119 task_context: Option<hir::HirId>,
121 /// Used to get the current `fn`'s def span to point to when using `await`
122 /// outside of an `async fn`.
123 current_item: Option<Span>,
125 catch_scopes: Vec<NodeId>,
126 loop_scopes: Vec<NodeId>,
127 is_in_loop_condition: bool,
128 is_in_trait_impl: bool,
129 is_in_dyn_type: bool,
131 /// What to do when we encounter either an "anonymous lifetime
132 /// reference". The term "anonymous" is meant to encompass both
133 /// `'_` lifetimes as well as fully elided cases where nothing is
134 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
135 anonymous_lifetime_mode: AnonymousLifetimeMode,
137 /// Used to create lifetime definitions from in-band lifetime usages.
138 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
139 /// When a named lifetime is encountered in a function or impl header and
140 /// has not been defined
141 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
142 /// to this list. The results of this list are then added to the list of
143 /// lifetime definitions in the corresponding impl or function generics.
144 lifetimes_to_define: Vec<(Span, ParamName)>,
146 /// `true` if in-band lifetimes are being collected. This is used to
147 /// indicate whether or not we're in a place where new lifetimes will result
148 /// in in-band lifetime definitions, such a function or an impl header,
149 /// including implicit lifetimes from `impl_header_lifetime_elision`.
150 is_collecting_in_band_lifetimes: bool,
152 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
153 /// When `is_collecting_in_band_lifetimes` is true, each lifetime is checked
154 /// against this list to see if it is already in-scope, or if a definition
155 /// needs to be created for it.
157 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
159 in_scope_lifetimes: Vec<ParamName>,
161 current_module: LocalDefId,
163 type_def_lifetime_params: DefIdMap<usize>,
165 current_hir_id_owner: Vec<(LocalDefId, u32)>,
166 item_local_id_counters: NodeMap<u32>,
167 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
169 allow_try_trait: Option<Lrc<[Symbol]>>,
170 allow_gen_future: Option<Lrc<[Symbol]>>,
173 pub trait ResolverAstLowering {
174 fn def_key(&mut self, id: DefId) -> DefKey;
176 fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
178 fn item_attrs(&self, def_id: DefId, sess: &Session) -> Vec<ast::Attribute>;
180 /// Obtains resolution for a `NodeId` with a single resolution.
181 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
183 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
184 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
186 /// Obtains resolution for a label with the given `NodeId`.
187 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
189 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
190 /// This should only return `None` during testing.
191 fn definitions(&mut self) -> &mut Definitions;
193 fn lint_buffer(&mut self) -> &mut LintBuffer;
195 fn next_node_id(&mut self) -> NodeId;
197 fn trait_map(&self) -> &NodeMap<Vec<hir::TraitCandidate>>;
199 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
201 fn local_def_id(&self, node: NodeId) -> LocalDefId;
206 node_id: ast::NodeId,
213 type NtToTokenstream = fn(&Nonterminal, &ParseSess, CanSynthesizeMissingTokens) -> TokenStream;
215 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
216 /// and if so, what meaning it has.
218 enum ImplTraitContext<'b, 'a> {
219 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
220 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
221 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
223 /// Newly generated parameters should be inserted into the given `Vec`.
224 Universal(&'b mut Vec<hir::GenericParam<'a>>),
226 /// Treat `impl Trait` as shorthand for a new opaque type.
227 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
228 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
230 ReturnPositionOpaqueTy {
231 /// `DefId` for the parent function, used to look up necessary
232 /// information later.
234 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
235 origin: hir::OpaqueTyOrigin,
237 /// Impl trait in type aliases, consts and statics.
239 /// Set of lifetimes that this opaque type can capture, if it uses
240 /// them. This includes lifetimes bound since we entered this context.
243 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
245 /// the inner opaque type captures `'a` because it uses it. It doesn't
246 /// need to capture `'b` because it already inherits the lifetime
247 /// parameter from `A`.
248 // FIXME(impl_trait): but `required_region_bounds` will ICE later
250 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
251 /// Origin: Either OpaqueTyOrigin::Misc or OpaqueTyOrigin::Binding,
252 origin: hir::OpaqueTyOrigin,
254 /// `impl Trait` is not accepted in this position.
255 Disallowed(ImplTraitPosition),
258 /// Position in which `impl Trait` is disallowed.
259 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
260 enum ImplTraitPosition {
261 /// Disallowed in `let` / `const` / `static` bindings.
264 /// All other positions.
268 impl<'a> ImplTraitContext<'_, 'a> {
270 fn disallowed() -> Self {
271 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
274 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
275 use self::ImplTraitContext::*;
277 Universal(params) => Universal(params),
278 ReturnPositionOpaqueTy { fn_def_id, origin } => {
279 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
281 OtherOpaqueTy { capturable_lifetimes, origin } => {
282 OtherOpaqueTy { capturable_lifetimes, origin: *origin }
284 Disallowed(pos) => Disallowed(*pos),
289 pub fn lower_crate<'a, 'hir>(
292 resolver: &'a mut dyn ResolverAstLowering,
293 nt_to_tokenstream: NtToTokenstream,
294 arena: &'hir Arena<'hir>,
295 ) -> hir::Crate<'hir> {
296 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
303 items: BTreeMap::new(),
304 trait_items: BTreeMap::new(),
305 impl_items: BTreeMap::new(),
306 foreign_items: BTreeMap::new(),
307 bodies: BTreeMap::new(),
308 trait_impls: BTreeMap::new(),
309 modules: BTreeMap::new(),
310 exported_macros: Vec::new(),
311 non_exported_macro_attrs: Vec::new(),
312 catch_scopes: Vec::new(),
313 loop_scopes: Vec::new(),
314 is_in_loop_condition: false,
315 is_in_trait_impl: false,
316 is_in_dyn_type: false,
317 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
318 type_def_lifetime_params: Default::default(),
319 current_module: CRATE_DEF_ID,
320 current_hir_id_owner: vec![(CRATE_DEF_ID, 0)],
321 item_local_id_counters: Default::default(),
322 node_id_to_hir_id: IndexVec::new(),
323 generator_kind: None,
326 lifetimes_to_define: Vec::new(),
327 is_collecting_in_band_lifetimes: false,
328 in_scope_lifetimes: Vec::new(),
329 allow_try_trait: Some([sym::try_trait][..].into()),
330 allow_gen_future: Some([sym::gen_future][..].into()),
335 #[derive(Copy, Clone, PartialEq)]
337 /// Any path in a type context.
339 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
341 /// The `module::Type` in `module::Type::method` in an expression.
345 enum ParenthesizedGenericArgs {
350 /// What to do when we encounter an **anonymous** lifetime
351 /// reference. Anonymous lifetime references come in two flavors. You
352 /// have implicit, or fully elided, references to lifetimes, like the
353 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
354 /// or `Ref<'_, T>`. These often behave the same, but not always:
356 /// - certain usages of implicit references are deprecated, like
357 /// `Ref<T>`, and we sometimes just give hard errors in those cases
359 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
360 /// the same as `Box<dyn Foo + '_>`.
362 /// We describe the effects of the various modes in terms of three cases:
364 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
365 /// of a `&` (e.g., the missing lifetime in something like `&T`)
366 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
367 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
368 /// elided bounds follow special rules. Note that this only covers
369 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
370 /// '_>` is a case of "modern" elision.
371 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
372 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
373 /// non-deprecated equivalent.
375 /// Currently, the handling of lifetime elision is somewhat spread out
376 /// between HIR lowering and -- as described below -- the
377 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
378 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
379 /// everything into HIR lowering.
380 #[derive(Copy, Clone, Debug)]
381 enum AnonymousLifetimeMode {
382 /// For **Modern** cases, create a new anonymous region parameter
383 /// and reference that.
385 /// For **Dyn Bound** cases, pass responsibility to
386 /// `resolve_lifetime` code.
388 /// For **Deprecated** cases, report an error.
391 /// Give a hard error when either `&` or `'_` is written. Used to
392 /// rule out things like `where T: Foo<'_>`. Does not imply an
393 /// error on default object bounds (e.g., `Box<dyn Foo>`).
396 /// Pass responsibility to `resolve_lifetime` code for all cases.
400 struct TokenStreamLowering<'a> {
401 parse_sess: &'a ParseSess,
402 synthesize_tokens: CanSynthesizeMissingTokens,
403 nt_to_tokenstream: NtToTokenstream,
406 impl<'a> TokenStreamLowering<'a> {
407 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
408 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
411 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
413 TokenTree::Token(token) => self.lower_token(token),
414 TokenTree::Delimited(span, delim, tts) => {
415 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
420 fn lower_token(&mut self, token: Token) -> TokenStream {
422 token::Interpolated(nt) => {
423 let tts = (self.nt_to_tokenstream)(&nt, self.parse_sess, self.synthesize_tokens);
424 TokenTree::Delimited(
425 DelimSpan::from_single(token.span),
427 self.lower_token_stream(tts),
431 _ => TokenTree::Token(token).into(),
436 struct ImplTraitTypeIdVisitor<'a> {
437 ids: &'a mut SmallVec<[NodeId; 1]>,
440 impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
441 fn visit_ty(&mut self, ty: &Ty) {
443 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
445 TyKind::ImplTrait(id, _) => self.ids.push(id),
448 visit::walk_ty(self, ty);
451 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
452 if let Some(ref p) = path_segment.args {
453 if let GenericArgs::Parenthesized(_) = **p {
457 visit::walk_path_segment(self, path_span, path_segment)
461 impl<'a, 'hir> LoweringContext<'a, 'hir> {
462 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
463 /// Full-crate AST visitor that inserts into a fresh
464 /// `LoweringContext` any information that may be
465 /// needed from arbitrary locations in the crate,
466 /// e.g., the number of lifetime generic parameters
467 /// declared for every type and trait definition.
468 struct MiscCollector<'tcx, 'lowering, 'hir> {
469 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
472 impl MiscCollector<'_, '_, '_> {
473 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: LocalDefId) {
475 UseTreeKind::Simple(_, id1, id2) => {
476 for &id in &[id1, id2] {
477 self.lctx.resolver.create_def(
484 self.lctx.allocate_hir_id_counter(id);
487 UseTreeKind::Glob => (),
488 UseTreeKind::Nested(ref trees) => {
489 for &(ref use_tree, id) in trees {
490 let hir_id = self.lctx.allocate_hir_id_counter(id);
491 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
498 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
499 fn visit_item(&mut self, item: &'tcx Item) {
500 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
503 ItemKind::Struct(_, ref generics)
504 | ItemKind::Union(_, ref generics)
505 | ItemKind::Enum(_, ref generics)
506 | ItemKind::TyAlias(box TyAliasKind(_, ref generics, ..))
507 | ItemKind::Trait(box TraitKind(_, _, ref generics, ..)) => {
508 let def_id = self.lctx.resolver.local_def_id(item.id);
513 matches!(param.kind, ast::GenericParamKind::Lifetime { .. })
516 self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
518 ItemKind::Use(ref use_tree) => {
519 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
524 visit::walk_item(self, item);
527 fn visit_assoc_item(&mut self, item: &'tcx AssocItem, ctxt: AssocCtxt) {
528 self.lctx.allocate_hir_id_counter(item.id);
529 visit::walk_assoc_item(self, item, ctxt);
532 fn visit_foreign_item(&mut self, item: &'tcx ForeignItem) {
533 self.lctx.allocate_hir_id_counter(item.id);
534 visit::walk_foreign_item(self, item);
537 fn visit_ty(&mut self, t: &'tcx Ty) {
539 // Mirrors the case in visit::walk_ty
540 TyKind::BareFn(ref f) => {
541 walk_list!(self, visit_generic_param, &f.generic_params);
542 // Mirrors visit::walk_fn_decl
543 for parameter in &f.decl.inputs {
544 // We don't lower the ids of argument patterns
545 self.visit_pat(¶meter.pat);
546 self.visit_ty(¶meter.ty)
548 self.visit_fn_ret_ty(&f.decl.output)
550 TyKind::ImplTrait(def_node_id, _) => {
551 self.lctx.allocate_hir_id_counter(def_node_id);
552 visit::walk_ty(self, t);
554 _ => visit::walk_ty(self, t),
559 self.lower_node_id(CRATE_NODE_ID);
560 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
562 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
563 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
565 let module = self.lower_mod(&c.items, c.span);
566 let attrs = self.lower_attrs(&c.attrs);
567 let body_ids = body_ids(&self.bodies);
569 c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
575 .filter_map(|(&k, v)| {
576 self.node_id_to_hir_id.get(k).and_then(|id| id.as_ref()).map(|id| (*id, v.clone()))
580 let mut def_id_to_hir_id = IndexVec::default();
582 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
583 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
584 if def_id_to_hir_id.len() <= def_id.index() {
585 def_id_to_hir_id.resize(def_id.index() + 1, None);
587 def_id_to_hir_id[def_id] = hir_id;
591 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
594 item: hir::CrateItem { module, attrs, span: c.span },
595 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
596 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
598 trait_items: self.trait_items,
599 impl_items: self.impl_items,
600 foreign_items: self.foreign_items,
603 trait_impls: self.trait_impls,
604 modules: self.modules,
610 fn insert_item(&mut self, item: hir::Item<'hir>) -> hir::ItemId {
611 let id = hir::ItemId { def_id: item.def_id };
612 self.items.insert(id, item);
613 self.modules.entry(self.current_module).or_default().items.insert(id);
617 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
618 // Set up the counter if needed.
619 self.item_local_id_counters.entry(owner).or_insert(0);
620 // Always allocate the first `HirId` for the owner itself.
621 let lowered = self.lower_node_id_with_owner(owner, owner);
622 debug_assert_eq!(lowered.local_id.as_u32(), 0);
626 fn lower_node_id_generic(
629 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
631 assert_ne!(ast_node_id, DUMMY_NODE_ID);
633 let min_size = ast_node_id.as_usize() + 1;
635 if min_size > self.node_id_to_hir_id.len() {
636 self.node_id_to_hir_id.resize(min_size, None);
639 if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] {
642 // Generate a new `HirId`.
643 let hir_id = alloc_hir_id(self);
644 self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
650 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
652 .item_local_id_counters
653 .insert(owner, HIR_ID_COUNTER_LOCKED)
654 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
655 let def_id = self.resolver.local_def_id(owner);
656 self.current_hir_id_owner.push((def_id, counter));
658 let (new_def_id, new_counter) = self.current_hir_id_owner.pop().unwrap();
660 debug_assert!(def_id == new_def_id);
661 debug_assert!(new_counter >= counter);
663 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
664 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
668 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
669 /// the `LoweringContext`'s `NodeId => HirId` map.
670 /// Take care not to call this method if the resulting `HirId` is then not
671 /// actually used in the HIR, as that would trigger an assertion in the
672 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
673 /// properly. Calling the method twice with the same `NodeId` is fine though.
674 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
675 self.lower_node_id_generic(ast_node_id, |this| {
676 let &mut (owner, ref mut local_id_counter) =
677 this.current_hir_id_owner.last_mut().unwrap();
678 let local_id = *local_id_counter;
679 *local_id_counter += 1;
680 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
684 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
685 self.lower_node_id_generic(ast_node_id, |this| {
686 let local_id_counter = this
687 .item_local_id_counters
689 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
690 let local_id = *local_id_counter;
692 // We want to be sure not to modify the counter in the map while it
693 // is also on the stack. Otherwise we'll get lost updates when writing
694 // back from the stack to the map.
695 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
697 *local_id_counter += 1;
698 let owner = this.resolver.opt_local_def_id(owner).expect(
699 "you forgot to call `create_def` or are lowering node-IDs \
700 that do not belong to the current owner",
703 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
707 fn next_id(&mut self) -> hir::HirId {
708 let node_id = self.resolver.next_node_id();
709 self.lower_node_id(node_id)
712 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
714 self.lower_node_id_generic(id, |_| {
715 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
720 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
721 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
722 if pr.unresolved_segments() != 0 {
723 panic!("path not fully resolved: {:?}", pr);
729 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
730 self.resolver.get_import_res(id).present_items()
733 fn diagnostic(&self) -> &rustc_errors::Handler {
734 self.sess.diagnostic()
737 /// Reuses the span but adds information like the kind of the desugaring and features that are
738 /// allowed inside this span.
739 fn mark_span_with_reason(
741 reason: DesugaringKind,
743 allow_internal_unstable: Option<Lrc<[Symbol]>>,
745 span.mark_with_reason(allow_internal_unstable, reason, self.sess.edition())
748 fn with_anonymous_lifetime_mode<R>(
750 anonymous_lifetime_mode: AnonymousLifetimeMode,
751 op: impl FnOnce(&mut Self) -> R,
754 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
755 anonymous_lifetime_mode,
757 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
758 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
759 let result = op(self);
760 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
762 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
763 old_anonymous_lifetime_mode
768 /// Creates a new `hir::GenericParam` for every new lifetime and
769 /// type parameter encountered while evaluating `f`. Definitions
770 /// are created with the parent provided. If no `parent_id` is
771 /// provided, no definitions will be returned.
773 /// Presuming that in-band lifetimes are enabled, then
774 /// `self.anonymous_lifetime_mode` will be updated to match the
775 /// parameter while `f` is running (and restored afterwards).
776 fn collect_in_band_defs<T>(
778 parent_def_id: LocalDefId,
779 anonymous_lifetime_mode: AnonymousLifetimeMode,
780 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
781 ) -> (Vec<hir::GenericParam<'hir>>, T) {
782 assert!(!self.is_collecting_in_band_lifetimes);
783 assert!(self.lifetimes_to_define.is_empty());
784 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
786 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
787 self.is_collecting_in_band_lifetimes = true;
789 let (in_band_ty_params, res) = f(self);
791 self.is_collecting_in_band_lifetimes = false;
792 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
794 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
796 let params = lifetimes_to_define
798 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
799 .chain(in_band_ty_params.into_iter())
805 /// Converts a lifetime into a new generic parameter.
806 fn lifetime_to_generic_param(
810 parent_def_id: LocalDefId,
811 ) -> hir::GenericParam<'hir> {
812 let node_id = self.resolver.next_node_id();
814 // Get the name we'll use to make the def-path. Note
815 // that collisions are ok here and this shouldn't
816 // really show up for end-user.
817 let (str_name, kind) = match hir_name {
818 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
819 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
820 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
823 // Add a definition for the in-band lifetime def.
824 self.resolver.create_def(
827 DefPathData::LifetimeNs(str_name),
833 hir_id: self.lower_node_id(node_id),
838 pure_wrt_drop: false,
839 kind: hir::GenericParamKind::Lifetime { kind },
843 /// When there is a reference to some lifetime `'a`, and in-band
844 /// lifetimes are enabled, then we want to push that lifetime into
845 /// the vector of names to define later. In that case, it will get
846 /// added to the appropriate generics.
847 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
848 if !self.is_collecting_in_band_lifetimes {
852 if !self.sess.features_untracked().in_band_lifetimes {
856 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
860 let hir_name = ParamName::Plain(ident);
862 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
863 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
868 self.lifetimes_to_define.push((ident.span, hir_name));
871 /// When we have either an elided or `'_` lifetime in an impl
872 /// header, we convert it to an in-band lifetime.
873 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
874 assert!(self.is_collecting_in_band_lifetimes);
875 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
876 let hir_name = ParamName::Fresh(index);
877 self.lifetimes_to_define.push((span, hir_name));
881 // Evaluates `f` with the lifetimes in `params` in-scope.
882 // This is used to track which lifetimes have already been defined, and
883 // which are new in-band lifetimes that need to have a definition created
885 fn with_in_scope_lifetime_defs<T>(
887 params: &[GenericParam],
888 f: impl FnOnce(&mut Self) -> T,
890 let old_len = self.in_scope_lifetimes.len();
891 let lt_def_names = params.iter().filter_map(|param| match param.kind {
892 GenericParamKind::Lifetime { .. } => {
893 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
897 self.in_scope_lifetimes.extend(lt_def_names);
901 self.in_scope_lifetimes.truncate(old_len);
905 /// Appends in-band lifetime defs and argument-position `impl
906 /// Trait` defs to the existing set of generics.
908 /// Presuming that in-band lifetimes are enabled, then
909 /// `self.anonymous_lifetime_mode` will be updated to match the
910 /// parameter while `f` is running (and restored afterwards).
911 fn add_in_band_defs<T>(
914 parent_def_id: LocalDefId,
915 anonymous_lifetime_mode: AnonymousLifetimeMode,
916 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
917 ) -> (hir::Generics<'hir>, T) {
918 let (in_band_defs, (mut lowered_generics, res)) =
919 self.with_in_scope_lifetime_defs(&generics.params, |this| {
920 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
921 let mut params = Vec::new();
922 // Note: it is necessary to lower generics *before* calling `f`.
923 // When lowering `async fn`, there's a final step when lowering
924 // the return type that assumes that all in-scope lifetimes have
925 // already been added to either `in_scope_lifetimes` or
926 // `lifetimes_to_define`. If we swapped the order of these two,
927 // in-band-lifetimes introduced by generics or where-clauses
928 // wouldn't have been added yet.
930 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
931 let res = f(this, &mut params);
932 (params, (generics, res))
936 lowered_generics.params.extend(in_band_defs);
938 let lowered_generics = lowered_generics.into_generics(self.arena);
939 (lowered_generics, res)
942 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
943 let was_in_dyn_type = self.is_in_dyn_type;
944 self.is_in_dyn_type = in_scope;
946 let result = f(self);
948 self.is_in_dyn_type = was_in_dyn_type;
953 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
954 let was_in_loop_condition = self.is_in_loop_condition;
955 self.is_in_loop_condition = false;
957 let catch_scopes = mem::take(&mut self.catch_scopes);
958 let loop_scopes = mem::take(&mut self.loop_scopes);
960 self.catch_scopes = catch_scopes;
961 self.loop_scopes = loop_scopes;
963 self.is_in_loop_condition = was_in_loop_condition;
968 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
969 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
972 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
973 // Note that we explicitly do not walk the path. Since we don't really
974 // lower attributes (we use the AST version) there is nowhere to keep
975 // the `HirId`s. We don't actually need HIR version of attributes anyway.
976 // Tokens are also not needed after macro expansion and parsing.
977 let kind = match attr.kind {
978 AttrKind::Normal(ref item, _) => AttrKind::Normal(
980 path: item.path.clone(),
981 args: self.lower_mac_args(&item.args),
986 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
989 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
992 fn lower_mac_args(&mut 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 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1122 let (desugar_to_impl_trait, itctx) = match itctx {
1123 // We are in the return position:
1125 // fn foo() -> impl Iterator<Item: Debug>
1129 // fn foo() -> impl Iterator<Item = impl Debug>
1130 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1131 | ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx),
1133 // We are in the argument position, but within a dyn type:
1135 // fn foo(x: dyn Iterator<Item: Debug>)
1139 // fn foo(x: dyn Iterator<Item = impl Debug>)
1140 ImplTraitContext::Universal(..) if self.is_in_dyn_type => (true, itctx),
1142 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1143 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1144 // "impl trait context" to permit `impl Debug` in this position (it desugars
1145 // then to an opaque type).
1147 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1148 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1149 capturable_lifetimes = FxHashSet::default();
1152 ImplTraitContext::OtherOpaqueTy {
1153 capturable_lifetimes: &mut capturable_lifetimes,
1154 origin: hir::OpaqueTyOrigin::Misc,
1159 // We are in the parameter position, but not within a dyn type:
1161 // fn foo(x: impl Iterator<Item: Debug>)
1163 // so we leave it as is and this gets expanded in astconv to a bound like
1164 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1166 _ => (false, itctx),
1169 if desugar_to_impl_trait {
1170 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1171 // constructing the HIR for `impl bounds...` and then lowering that.
1173 let impl_trait_node_id = self.resolver.next_node_id();
1174 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1175 self.resolver.create_def(
1178 DefPathData::ImplTrait,
1183 self.with_dyn_type_scope(false, |this| {
1184 let node_id = this.resolver.next_node_id();
1185 let ty = this.lower_ty(
1188 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1189 span: constraint.span,
1195 hir::TypeBindingKind::Equality { ty }
1198 // Desugar `AssocTy: Bounds` into a type binding where the
1199 // later desugars into a trait predicate.
1200 let bounds = self.lower_param_bounds(bounds, itctx);
1202 hir::TypeBindingKind::Constraint { bounds }
1208 hir_id: self.lower_node_id(constraint.id),
1209 ident: constraint.ident,
1212 span: constraint.span,
1216 fn lower_generic_arg(
1218 arg: &ast::GenericArg,
1219 itctx: ImplTraitContext<'_, 'hir>,
1220 ) -> hir::GenericArg<'hir> {
1222 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1223 ast::GenericArg::Type(ty) => {
1224 // We parse const arguments as path types as we cannot distinguish them during
1225 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1226 // type and value namespaces. If we resolved the path in the value namespace, we
1227 // transform it into a generic const argument.
1228 if let TyKind::Path(ref qself, ref path) = ty.kind {
1229 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1230 let res = partial_res.base_res();
1231 if !res.matches_ns(Namespace::TypeNS) {
1233 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1237 // Construct a AnonConst where the expr is the "ty"'s path.
1239 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1240 let node_id = self.resolver.next_node_id();
1242 // Add a definition for the in-band const def.
1243 self.resolver.create_def(
1246 DefPathData::AnonConst,
1251 let path_expr = Expr {
1253 kind: ExprKind::Path(qself.clone(), path.clone()),
1255 attrs: AttrVec::new(),
1259 let ct = self.with_new_scopes(|this| hir::AnonConst {
1260 hir_id: this.lower_node_id(node_id),
1261 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1263 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1267 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1269 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1270 value: self.lower_anon_const(&ct),
1271 span: ct.value.span,
1276 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1277 self.arena.alloc(self.lower_ty_direct(t, itctx))
1283 qself: &Option<QSelf>,
1285 param_mode: ParamMode,
1286 itctx: ImplTraitContext<'_, 'hir>,
1287 ) -> hir::Ty<'hir> {
1288 let id = self.lower_node_id(t.id);
1289 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1290 let ty = self.ty_path(id, t.span, qpath);
1291 if let hir::TyKind::TraitObject(..) = ty.kind {
1292 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1297 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1298 hir::Ty { hir_id: self.next_id(), kind, span }
1301 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1302 self.ty(span, hir::TyKind::Tup(tys))
1305 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1306 let kind = match t.kind {
1307 TyKind::Infer => hir::TyKind::Infer,
1308 TyKind::Err => hir::TyKind::Err,
1309 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1310 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1311 TyKind::Rptr(ref region, ref mt) => {
1312 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1313 let lifetime = match *region {
1314 Some(ref lt) => self.lower_lifetime(lt),
1315 None => self.elided_ref_lifetime(span),
1317 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1319 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1320 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1321 let span = this.sess.source_map().next_point(t.span.shrink_to_lo());
1322 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1323 generic_params: this.lower_generic_params(
1325 &NodeMap::default(),
1326 ImplTraitContext::disallowed(),
1328 unsafety: this.lower_unsafety(f.unsafety),
1329 abi: this.lower_extern(f.ext, span, t.id),
1330 decl: this.lower_fn_decl(&f.decl, None, false, None),
1331 param_names: this.lower_fn_params_to_names(&f.decl),
1335 TyKind::Never => hir::TyKind::Never,
1336 TyKind::Tup(ref tys) => {
1337 hir::TyKind::Tup(self.arena.alloc_from_iter(
1338 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1341 TyKind::Paren(ref ty) => {
1342 return self.lower_ty_direct(ty, itctx);
1344 TyKind::Path(ref qself, ref path) => {
1345 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1347 TyKind::ImplicitSelf => {
1348 let res = self.expect_full_res(t.id);
1349 let res = self.lower_res(res);
1350 hir::TyKind::Path(hir::QPath::Resolved(
1352 self.arena.alloc(hir::Path {
1354 segments: arena_vec![self; hir::PathSegment::from_ident(
1355 Ident::with_dummy_span(kw::SelfUpper)
1361 TyKind::Array(ref ty, ref length) => {
1362 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1364 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1365 TyKind::TraitObject(ref bounds, kind) => {
1366 let mut lifetime_bound = None;
1367 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1369 this.arena.alloc_from_iter(bounds.iter().filter_map(
1370 |bound| match *bound {
1371 GenericBound::Trait(
1373 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1374 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1375 // `?const ?Bound` will cause an error during AST validation
1376 // anyways, so treat it like `?Bound` as compilation proceeds.
1377 GenericBound::Trait(
1379 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1381 GenericBound::Outlives(ref lifetime) => {
1382 if lifetime_bound.is_none() {
1383 lifetime_bound = Some(this.lower_lifetime(lifetime));
1389 let lifetime_bound =
1390 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1391 (bounds, lifetime_bound)
1393 if kind != TraitObjectSyntax::Dyn {
1394 self.maybe_lint_bare_trait(t.span, t.id, false);
1396 hir::TyKind::TraitObject(bounds, lifetime_bound)
1398 TyKind::ImplTrait(def_node_id, ref bounds) => {
1401 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1402 .lower_opaque_impl_trait(
1408 |this| this.lower_param_bounds(bounds, itctx),
1410 ImplTraitContext::OtherOpaqueTy { ref capturable_lifetimes, origin } => {
1411 // Reset capturable lifetimes, any nested impl trait
1412 // types will inherit lifetimes from this opaque type,
1413 // so don't need to capture them again.
1414 let nested_itctx = ImplTraitContext::OtherOpaqueTy {
1415 capturable_lifetimes: &mut FxHashSet::default(),
1418 self.lower_opaque_impl_trait(
1423 Some(capturable_lifetimes),
1424 |this| this.lower_param_bounds(bounds, nested_itctx),
1427 ImplTraitContext::Universal(in_band_ty_params) => {
1428 // Add a definition for the in-band `Param`.
1429 let def_id = self.resolver.local_def_id(def_node_id);
1431 self.allocate_hir_id_counter(def_node_id);
1433 let hir_bounds = self.with_hir_id_owner(def_node_id, |this| {
1434 this.lower_param_bounds(
1436 ImplTraitContext::Universal(in_band_ty_params),
1439 // Set the name to `impl Bound1 + Bound2`.
1440 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1441 in_band_ty_params.push(hir::GenericParam {
1442 hir_id: self.lower_node_id(def_node_id),
1443 name: ParamName::Plain(ident),
1444 pure_wrt_drop: false,
1448 kind: hir::GenericParamKind::Type {
1450 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1454 hir::TyKind::Path(hir::QPath::Resolved(
1456 self.arena.alloc(hir::Path {
1458 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1459 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1463 ImplTraitContext::Disallowed(pos) => {
1464 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1465 "bindings or function and inherent method return types"
1467 "function and inherent method return types"
1469 let mut err = struct_span_err!(
1473 "`impl Trait` not allowed outside of {}",
1476 if pos == ImplTraitPosition::Binding && self.sess.is_nightly_build() {
1478 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1479 attributes to enable",
1487 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1488 TyKind::CVarArgs => {
1489 self.sess.delay_span_bug(
1491 "`TyKind::CVarArgs` should have been handled elsewhere",
1497 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1500 fn lower_opaque_impl_trait(
1503 fn_def_id: Option<DefId>,
1504 origin: hir::OpaqueTyOrigin,
1505 opaque_ty_node_id: NodeId,
1506 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1507 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1508 ) -> hir::TyKind<'hir> {
1510 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1511 fn_def_id, opaque_ty_node_id, span,
1514 // Make sure we know that some funky desugaring has been going on here.
1515 // This is a first: there is code in other places like for loop
1516 // desugaring that explicitly states that we don't want to track that.
1517 // Not tracking it makes lints in rustc and clippy very fragile, as
1518 // frequently opened issues show.
1519 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1521 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1523 self.allocate_hir_id_counter(opaque_ty_node_id);
1525 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1527 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1531 capturable_lifetimes,
1534 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1536 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1538 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1539 let opaque_ty_item = hir::OpaqueTy {
1540 generics: hir::Generics {
1541 params: lifetime_defs,
1542 where_clause: hir::WhereClause { predicates: &[], span },
1546 impl_trait_fn: fn_def_id,
1550 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1551 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
1553 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1554 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1558 /// Registers a new opaque type with the proper `NodeId`s and
1559 /// returns the lowered node-ID for the opaque type.
1560 fn generate_opaque_type(
1562 opaque_ty_id: LocalDefId,
1563 opaque_ty_item: hir::OpaqueTy<'hir>,
1565 opaque_ty_span: Span,
1567 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1568 // Generate an `type Foo = impl Trait;` declaration.
1569 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1570 let opaque_ty_item = hir::Item {
1571 def_id: opaque_ty_id,
1572 ident: Ident::invalid(),
1573 attrs: Default::default(),
1574 kind: opaque_ty_item_kind,
1575 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1576 span: opaque_ty_span,
1579 // Insert the item into the global item list. This usually happens
1580 // automatically for all AST items. But this opaque type item
1581 // does not actually exist in the AST.
1582 self.insert_item(opaque_ty_item);
1585 fn lifetimes_from_impl_trait_bounds(
1587 opaque_ty_id: NodeId,
1588 parent_def_id: LocalDefId,
1589 bounds: hir::GenericBounds<'hir>,
1590 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
1591 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1593 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1594 parent_def_id={:?}, \
1596 opaque_ty_id, parent_def_id, bounds,
1599 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1600 // appear in the bounds, excluding lifetimes that are created within the bounds.
1601 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1602 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1603 context: &'r mut LoweringContext<'a, 'hir>,
1605 opaque_ty_id: NodeId,
1606 collect_elided_lifetimes: bool,
1607 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1608 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1609 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1610 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1611 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
1614 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1615 type Map = intravisit::ErasedMap<'v>;
1617 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1618 intravisit::NestedVisitorMap::None
1621 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1622 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1623 if parameters.parenthesized {
1624 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1625 self.collect_elided_lifetimes = false;
1626 intravisit::walk_generic_args(self, span, parameters);
1627 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1629 intravisit::walk_generic_args(self, span, parameters);
1633 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1634 // Don't collect elided lifetimes used inside of `fn()` syntax.
1635 if let hir::TyKind::BareFn(_) = t.kind {
1636 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1637 self.collect_elided_lifetimes = false;
1639 // Record the "stack height" of `for<'a>` lifetime bindings
1640 // to be able to later fully undo their introduction.
1641 let old_len = self.currently_bound_lifetimes.len();
1642 intravisit::walk_ty(self, t);
1643 self.currently_bound_lifetimes.truncate(old_len);
1645 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1647 intravisit::walk_ty(self, t)
1651 fn visit_poly_trait_ref(
1653 trait_ref: &'v hir::PolyTraitRef<'v>,
1654 modifier: hir::TraitBoundModifier,
1656 // Record the "stack height" of `for<'a>` lifetime bindings
1657 // to be able to later fully undo their introduction.
1658 let old_len = self.currently_bound_lifetimes.len();
1659 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1660 self.currently_bound_lifetimes.truncate(old_len);
1663 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1664 // Record the introduction of 'a in `for<'a> ...`.
1665 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1666 // Introduce lifetimes one at a time so that we can handle
1667 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1668 let lt_name = hir::LifetimeName::Param(param.name);
1669 self.currently_bound_lifetimes.push(lt_name);
1672 intravisit::walk_generic_param(self, param);
1675 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1676 let name = match lifetime.name {
1677 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1678 if self.collect_elided_lifetimes {
1679 // Use `'_` for both implicit and underscore lifetimes in
1680 // `type Foo<'_> = impl SomeTrait<'_>;`.
1681 hir::LifetimeName::Underscore
1686 hir::LifetimeName::Param(_) => lifetime.name,
1688 // Refers to some other lifetime that is "in
1689 // scope" within the type.
1690 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1692 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1695 if !self.currently_bound_lifetimes.contains(&name)
1696 && !self.already_defined_lifetimes.contains(&name)
1697 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
1699 self.already_defined_lifetimes.insert(name);
1701 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1702 hir_id: self.context.next_id(),
1703 span: lifetime.span,
1707 let def_node_id = self.context.resolver.next_node_id();
1709 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1710 self.context.resolver.create_def(
1713 DefPathData::LifetimeNs(name.ident().name),
1718 let (name, kind) = match name {
1719 hir::LifetimeName::Underscore => (
1720 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1721 hir::LifetimeParamKind::Elided,
1723 hir::LifetimeName::Param(param_name) => {
1724 (param_name, hir::LifetimeParamKind::Explicit)
1726 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1729 self.output_lifetime_params.push(hir::GenericParam {
1732 span: lifetime.span,
1733 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>, SmallVec<[NodeId; 1]>) {
1768 let mut ids = SmallVec::<[NodeId; 1]>::new();
1769 if self.sess.features_untracked().impl_trait_in_bindings {
1770 if let Some(ref ty) = l.ty {
1771 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1772 visitor.visit_ty(ty);
1775 let ty = l.ty.as_ref().map(|t| {
1776 let mut capturable_lifetimes;
1779 if self.sess.features_untracked().impl_trait_in_bindings {
1780 capturable_lifetimes = FxHashSet::default();
1781 ImplTraitContext::OtherOpaqueTy {
1782 capturable_lifetimes: &mut capturable_lifetimes,
1783 origin: hir::OpaqueTyOrigin::Binding,
1786 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1790 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1793 hir_id: self.lower_node_id(l.id),
1795 pat: self.lower_pat(&l.pat),
1798 attrs: l.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
1799 source: hir::LocalSource::Normal,
1805 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1806 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1807 // as they are not explicit in HIR/Ty function signatures.
1808 // (instead, the `c_variadic` flag is set to `true`)
1809 let mut inputs = &decl.inputs[..];
1810 if decl.c_variadic() {
1811 inputs = &inputs[..inputs.len() - 1];
1813 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1814 PatKind::Ident(_, ident, _) => ident,
1815 _ => Ident::new(kw::Empty, param.pat.span),
1819 // Lowers a function declaration.
1821 // `decl`: the unlowered (AST) function declaration.
1822 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1823 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1824 // `make_ret_async` is also `Some`.
1825 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1826 // This guards against trait declarations and implementations where `impl Trait` is
1828 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1829 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1830 // return type `impl Trait` item.
1834 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1835 impl_trait_return_allow: bool,
1836 make_ret_async: Option<NodeId>,
1837 ) -> &'hir hir::FnDecl<'hir> {
1841 in_band_ty_params: {:?}, \
1842 impl_trait_return_allow: {}, \
1843 make_ret_async: {:?})",
1844 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1846 let lt_mode = if make_ret_async.is_some() {
1847 // In `async fn`, argument-position elided lifetimes
1848 // must be transformed into fresh generic parameters so that
1849 // they can be applied to the opaque `impl Trait` return type.
1850 AnonymousLifetimeMode::CreateParameter
1852 self.anonymous_lifetime_mode
1855 let c_variadic = decl.c_variadic();
1857 // Remember how many lifetimes were already around so that we can
1858 // only look at the lifetime parameters introduced by the arguments.
1859 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1860 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1861 // as they are not explicit in HIR/Ty function signatures.
1862 // (instead, the `c_variadic` flag is set to `true`)
1863 let mut inputs = &decl.inputs[..];
1865 inputs = &inputs[..inputs.len() - 1];
1867 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1868 if let Some((_, ibty)) = &mut in_band_ty_params {
1869 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
1871 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1876 let output = if let Some(ret_id) = make_ret_async {
1877 self.lower_async_fn_ret_ty(
1879 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1884 FnRetTy::Ty(ref ty) => {
1885 let context = match in_band_ty_params {
1886 Some((def_id, _)) if impl_trait_return_allow => {
1887 ImplTraitContext::ReturnPositionOpaqueTy {
1889 origin: hir::OpaqueTyOrigin::FnReturn,
1892 _ => ImplTraitContext::disallowed(),
1894 hir::FnRetTy::Return(self.lower_ty(ty, context))
1896 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(span),
1900 self.arena.alloc(hir::FnDecl {
1904 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1905 use BindingMode::{ByRef, ByValue};
1906 let is_mutable_pat = matches!(
1908 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1912 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1913 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1914 // Given we are only considering `ImplicitSelf` types, we needn't consider
1915 // the case where we have a mutable pattern to a reference as that would
1916 // no longer be an `ImplicitSelf`.
1917 TyKind::Rptr(_, ref mt)
1918 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1920 hir::ImplicitSelfKind::MutRef
1922 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1923 hir::ImplicitSelfKind::ImmRef
1925 _ => hir::ImplicitSelfKind::None,
1931 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1932 // combined with the following definition of `OpaqueTy`:
1934 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1936 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1937 // `output`: unlowered output type (`T` in `-> T`)
1938 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1939 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1940 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1941 fn lower_async_fn_ret_ty(
1945 opaque_ty_node_id: NodeId,
1946 ) -> hir::FnRetTy<'hir> {
1948 "lower_async_fn_ret_ty(\
1951 opaque_ty_node_id={:?})",
1952 output, fn_def_id, opaque_ty_node_id,
1955 let span = output.span();
1957 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1959 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1961 self.allocate_hir_id_counter(opaque_ty_node_id);
1963 // When we create the opaque type for this async fn, it is going to have
1964 // to capture all the lifetimes involved in the signature (including in the
1965 // return type). This is done by introducing lifetime parameters for:
1967 // - all the explicitly declared lifetimes from the impl and function itself;
1968 // - all the elided lifetimes in the fn arguments;
1969 // - all the elided lifetimes in the return type.
1971 // So for example in this snippet:
1974 // impl<'a> Foo<'a> {
1975 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1976 // // ^ '0 ^ '1 ^ '2
1977 // // elided lifetimes used below
1982 // we would create an opaque type like:
1985 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1988 // and we would then desugar `bar` to the equivalent of:
1991 // impl<'a> Foo<'a> {
1992 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1996 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1997 // this is because the elided lifetimes from the return type
1998 // should be figured out using the ordinary elision rules, and
1999 // this desugaring achieves that.
2001 // The variable `input_lifetimes_count` tracks the number of
2002 // lifetime parameters to the opaque type *not counting* those
2003 // lifetimes elided in the return type. This includes those
2004 // that are explicitly declared (`in_scope_lifetimes`) and
2005 // those elided lifetimes we found in the arguments (current
2006 // content of `lifetimes_to_define`). Next, we will process
2007 // the return type, which will cause `lifetimes_to_define` to
2009 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2011 let lifetime_params = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2012 // We have to be careful to get elision right here. The
2013 // idea is that we create a lifetime parameter for each
2014 // lifetime in the return type. So, given a return type
2015 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2016 // Future<Output = &'1 [ &'2 u32 ]>`.
2018 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2019 // hence the elision takes place at the fn site.
2020 let future_bound = this
2021 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
2022 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
2025 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2027 // Calculate all the lifetimes that should be captured
2028 // by the opaque type. This should include all in-scope
2029 // lifetime parameters, including those defined in-band.
2031 // Note: this must be done after lowering the output type,
2032 // as the output type may introduce new in-band lifetimes.
2033 let lifetime_params: Vec<(Span, ParamName)> = this
2037 .map(|name| (name.ident().span, name))
2038 .chain(this.lifetimes_to_define.iter().cloned())
2041 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2042 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2043 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2045 let generic_params =
2046 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
2047 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
2050 let opaque_ty_item = hir::OpaqueTy {
2051 generics: hir::Generics {
2052 params: generic_params,
2053 where_clause: hir::WhereClause { predicates: &[], span },
2056 bounds: arena_vec![this; future_bound],
2057 impl_trait_fn: Some(fn_def_id),
2058 origin: hir::OpaqueTyOrigin::AsyncFn,
2061 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
2062 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
2067 // As documented above on the variable
2068 // `input_lifetimes_count`, we need to create the lifetime
2069 // arguments to our opaque type. Continuing with our example,
2070 // we're creating the type arguments for the return type:
2073 // Bar<'a, 'b, '0, '1, '_>
2076 // For the "input" lifetime parameters, we wish to create
2077 // references to the parameters themselves, including the
2078 // "implicit" ones created from parameter types (`'a`, `'b`,
2081 // For the "output" lifetime parameters, we just want to
2083 let mut generic_args = Vec::with_capacity(lifetime_params.len());
2084 generic_args.extend(lifetime_params[..input_lifetimes_count].iter().map(
2085 |&(span, hir_name)| {
2086 // Input lifetime like `'a` or `'1`:
2087 GenericArg::Lifetime(hir::Lifetime {
2088 hir_id: self.next_id(),
2090 name: hir::LifetimeName::Param(hir_name),
2094 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
2095 // Output lifetime like `'_`.
2096 GenericArg::Lifetime(hir::Lifetime {
2097 hir_id: self.next_id(),
2099 name: hir::LifetimeName::Implicit,
2101 let generic_args = self.arena.alloc_from_iter(generic_args);
2103 // Create the `Foo<...>` reference itself. Note that the `type
2104 // Foo = impl Trait` is, internally, created as a child of the
2105 // async fn, so the *type parameters* are inherited. It's
2106 // only the lifetime parameters that we must supply.
2108 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
2109 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2110 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2113 /// Transforms `-> T` into `Future<Output = T>`
2114 fn lower_async_fn_output_type_to_future_bound(
2119 ) -> hir::GenericBound<'hir> {
2120 // Compute the `T` in `Future<Output = T>` from the return type.
2121 let output_ty = match output {
2122 FnRetTy::Ty(ty) => {
2123 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2124 // `impl Future` opaque type that `async fn` implicitly
2126 let context = ImplTraitContext::ReturnPositionOpaqueTy {
2128 origin: hir::OpaqueTyOrigin::FnReturn,
2130 self.lower_ty(ty, context)
2132 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2136 let future_args = self.arena.alloc(hir::GenericArgs {
2138 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2139 parenthesized: false,
2142 hir::GenericBound::LangItemTrait(
2143 // ::std::future::Future<future_params>
2144 hir::LangItem::Future,
2151 fn lower_param_bound(
2154 itctx: ImplTraitContext<'_, 'hir>,
2155 ) -> hir::GenericBound<'hir> {
2157 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2158 self.lower_poly_trait_ref(ty, itctx),
2159 self.lower_trait_bound_modifier(modifier),
2161 GenericBound::Outlives(ref lifetime) => {
2162 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2167 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2168 let span = l.ident.span;
2170 ident if ident.name == kw::StaticLifetime => {
2171 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2173 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2174 AnonymousLifetimeMode::CreateParameter => {
2175 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2176 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2179 AnonymousLifetimeMode::PassThrough => {
2180 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2183 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2186 self.maybe_collect_in_band_lifetime(ident);
2187 let param_name = ParamName::Plain(ident);
2188 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2193 fn new_named_lifetime(
2197 name: hir::LifetimeName,
2198 ) -> hir::Lifetime {
2199 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2202 fn lower_generic_params_mut<'s>(
2204 params: &'s [GenericParam],
2205 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2206 mut itctx: ImplTraitContext<'s, 'hir>,
2207 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2210 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2213 fn lower_generic_params(
2215 params: &[GenericParam],
2216 add_bounds: &NodeMap<Vec<GenericBound>>,
2217 itctx: ImplTraitContext<'_, 'hir>,
2218 ) -> &'hir [hir::GenericParam<'hir>] {
2219 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2222 fn lower_generic_param(
2224 param: &GenericParam,
2225 add_bounds: &NodeMap<Vec<GenericBound>>,
2226 mut itctx: ImplTraitContext<'_, 'hir>,
2227 ) -> hir::GenericParam<'hir> {
2228 let mut bounds: Vec<_> = self
2229 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2230 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2233 let (name, kind) = match param.kind {
2234 GenericParamKind::Lifetime => {
2235 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2236 self.is_collecting_in_band_lifetimes = false;
2239 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2240 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2242 let param_name = match lt.name {
2243 hir::LifetimeName::Param(param_name) => param_name,
2244 hir::LifetimeName::Implicit
2245 | hir::LifetimeName::Underscore
2246 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2247 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2248 self.sess.diagnostic().span_bug(
2250 "object-lifetime-default should not occur here",
2253 hir::LifetimeName::Error => ParamName::Error,
2257 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2259 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2263 GenericParamKind::Type { ref default, .. } => {
2264 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2265 if !add_bounds.is_empty() {
2266 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2267 bounds.extend(params);
2270 let kind = hir::GenericParamKind::Type {
2271 default: default.as_ref().map(|x| {
2274 ImplTraitContext::OtherOpaqueTy {
2275 capturable_lifetimes: &mut FxHashSet::default(),
2276 origin: hir::OpaqueTyOrigin::Misc,
2283 .filter(|attr| self.sess.check_name(attr, sym::rustc_synthetic))
2284 .map(|_| hir::SyntheticTyParamKind::FromAttr)
2288 (hir::ParamName::Plain(param.ident), kind)
2290 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2292 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2293 this.lower_ty(&ty, ImplTraitContext::disallowed())
2295 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2297 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty, default })
2302 hir_id: self.lower_node_id(param.id),
2304 span: param.ident.span,
2305 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
2306 attrs: self.lower_attrs(¶m.attrs),
2307 bounds: self.arena.alloc_from_iter(bounds),
2315 itctx: ImplTraitContext<'_, 'hir>,
2316 ) -> hir::TraitRef<'hir> {
2317 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2318 hir::QPath::Resolved(None, path) => path,
2319 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2321 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2324 fn lower_poly_trait_ref(
2327 mut itctx: ImplTraitContext<'_, 'hir>,
2328 ) -> hir::PolyTraitRef<'hir> {
2329 let bound_generic_params = self.lower_generic_params(
2330 &p.bound_generic_params,
2331 &NodeMap::default(),
2335 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2336 // Any impl Trait types defined within this scope can capture
2337 // lifetimes bound on this predicate.
2338 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
2339 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
2340 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
2344 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2345 capturable_lifetimes.extend(lt_def_names.clone());
2348 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2350 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2351 for param in lt_def_names {
2352 capturable_lifetimes.remove(¶m);
2358 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
2361 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2362 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2365 fn lower_param_bounds(
2367 bounds: &[GenericBound],
2368 itctx: ImplTraitContext<'_, 'hir>,
2369 ) -> hir::GenericBounds<'hir> {
2370 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2373 fn lower_param_bounds_mut<'s>(
2375 bounds: &'s [GenericBound],
2376 mut itctx: ImplTraitContext<'s, 'hir>,
2377 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2378 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2381 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2382 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2385 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
2386 let mut expr: Option<&'hir _> = None;
2388 let stmts = self.arena.alloc_from_iter(
2392 .filter_map(|(index, stmt)| {
2393 if index == b.stmts.len() - 1 {
2394 if let StmtKind::Expr(ref e) = stmt.kind {
2395 expr = Some(self.lower_expr(e));
2398 Some(self.lower_stmt(stmt))
2401 Some(self.lower_stmt(stmt))
2406 let rules = self.lower_block_check_mode(&b.rules);
2407 let hir_id = self.lower_node_id(b.id);
2409 hir::Block { hir_id, stmts, expr, rules, span: b.span, targeted_by_break }
2412 /// Lowers a block directly to an expression, presuming that it
2413 /// has no attributes and is not targeted by a `break`.
2414 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2415 let block = self.lower_block(b, false);
2416 self.expr_block(block, AttrVec::new())
2419 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2420 self.with_new_scopes(|this| hir::AnonConst {
2421 hir_id: this.lower_node_id(c.id),
2422 body: this.lower_const_body(c.value.span, Some(&c.value)),
2426 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2427 let kind = match s.kind {
2428 StmtKind::Local(ref l) => {
2429 let (l, item_ids) = self.lower_local(l);
2430 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
2433 let item_id = hir::ItemId {
2434 // All the items that `lower_local` finds are `impl Trait` types.
2435 def_id: self.lower_node_id(item_id).expect_owner(),
2437 self.stmt(s.span, hir::StmtKind::Item(item_id))
2442 hir_id: self.lower_node_id(s.id),
2443 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2449 StmtKind::Item(ref it) => {
2450 // Can only use the ID once.
2451 let mut id = Some(s.id);
2458 .map(|id| self.lower_node_id(id))
2459 .unwrap_or_else(|| self.next_id());
2461 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2465 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2466 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
2467 StmtKind::Empty => return smallvec![],
2468 StmtKind::MacCall(..) => panic!("shouldn't exist here"),
2470 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
2473 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2475 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2476 BlockCheckMode::Unsafe(u) => {
2477 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2482 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2484 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2485 UserProvided => hir::UnsafeSource::UserProvided,
2489 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2491 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2492 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2494 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2495 // placeholder for compilation to proceed.
2496 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2497 hir::TraitBoundModifier::Maybe
2502 // Helper methods for building HIR.
2504 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2505 hir::Stmt { span, kind, hir_id: self.next_id() }
2508 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2509 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2516 init: Option<&'hir hir::Expr<'hir>>,
2517 pat: &'hir hir::Pat<'hir>,
2518 source: hir::LocalSource,
2519 ) -> hir::Stmt<'hir> {
2520 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2521 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2524 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2525 self.block_all(expr.span, &[], Some(expr))
2531 stmts: &'hir [hir::Stmt<'hir>],
2532 expr: Option<&'hir hir::Expr<'hir>>,
2533 ) -> &'hir hir::Block<'hir> {
2534 let blk = hir::Block {
2537 hir_id: self.next_id(),
2538 rules: hir::BlockCheckMode::DefaultBlock,
2540 targeted_by_break: false,
2542 self.arena.alloc(blk)
2545 /// Constructs a `true` or `false` literal pattern.
2546 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2547 let expr = self.expr_bool(span, val);
2548 self.pat(span, hir::PatKind::Lit(expr))
2551 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2552 let field = self.single_pat_field(span, pat);
2553 self.pat_lang_item_variant(span, hir::LangItem::ResultOk, field)
2556 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2557 let field = self.single_pat_field(span, pat);
2558 self.pat_lang_item_variant(span, hir::LangItem::ResultErr, field)
2561 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2562 let field = self.single_pat_field(span, pat);
2563 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2566 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2567 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2570 fn single_pat_field(
2573 pat: &'hir hir::Pat<'hir>,
2574 ) -> &'hir [hir::FieldPat<'hir>] {
2575 let field = hir::FieldPat {
2576 hir_id: self.next_id(),
2577 ident: Ident::new(sym::integer(0), span),
2578 is_shorthand: false,
2582 arena_vec![self; field]
2585 fn pat_lang_item_variant(
2588 lang_item: hir::LangItem,
2589 fields: &'hir [hir::FieldPat<'hir>],
2590 ) -> &'hir hir::Pat<'hir> {
2591 let qpath = hir::QPath::LangItem(lang_item, span);
2592 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2595 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2596 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2599 fn pat_ident_binding_mode(
2603 bm: hir::BindingAnnotation,
2604 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2605 let hir_id = self.next_id();
2608 self.arena.alloc(hir::Pat {
2610 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2612 default_binding_modes: true,
2618 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2619 self.pat(span, hir::PatKind::Wild)
2622 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2623 self.arena.alloc(hir::Pat {
2624 hir_id: self.next_id(),
2627 default_binding_modes: true,
2631 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2632 self.arena.alloc(hir::Pat {
2633 hir_id: self.next_id(),
2636 default_binding_modes: false,
2642 mut hir_id: hir::HirId,
2644 qpath: hir::QPath<'hir>,
2645 ) -> hir::Ty<'hir> {
2646 let kind = match qpath {
2647 hir::QPath::Resolved(None, path) => {
2648 // Turn trait object paths into `TyKind::TraitObject` instead.
2650 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2651 let principal = hir::PolyTraitRef {
2652 bound_generic_params: &[],
2653 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2657 // The original ID is taken by the `PolyTraitRef`,
2658 // so the `Ty` itself needs a different one.
2659 hir_id = self.next_id();
2660 hir::TyKind::TraitObject(
2661 arena_vec![self; principal],
2662 self.elided_dyn_bound(span),
2665 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2668 _ => hir::TyKind::Path(qpath),
2671 hir::Ty { hir_id, kind, span }
2674 /// Invoked to create the lifetime argument for a type `&T`
2675 /// with no explicit lifetime.
2676 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2677 match self.anonymous_lifetime_mode {
2678 // Intercept when we are in an impl header or async fn and introduce an in-band
2680 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2682 AnonymousLifetimeMode::CreateParameter => {
2683 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2685 hir_id: self.next_id(),
2687 name: hir::LifetimeName::Param(fresh_name),
2691 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2693 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2697 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2698 /// return a "error lifetime".
2699 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2700 let (id, msg, label) = match id {
2701 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2704 self.resolver.next_node_id(),
2705 "`&` without an explicit lifetime name cannot be used here",
2706 "explicit lifetime name needed here",
2710 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2711 err.span_label(span, label);
2714 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2717 /// Invoked to create the lifetime argument(s) for a path like
2718 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2719 /// sorts of cases are deprecated. This may therefore report a warning or an
2720 /// error, depending on the mode.
2721 fn elided_path_lifetimes<'s>(
2725 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2726 (0..count).map(move |_| self.elided_path_lifetime(span))
2729 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2730 match self.anonymous_lifetime_mode {
2731 AnonymousLifetimeMode::CreateParameter => {
2732 // We should have emitted E0726 when processing this path above
2734 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2735 let id = self.resolver.next_node_id();
2736 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2738 // `PassThrough` is the normal case.
2739 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2740 // is unsuitable here, as these can occur from missing lifetime parameters in a
2741 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2742 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2743 // later, at which point a suitable error will be emitted.
2744 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2745 self.new_implicit_lifetime(span)
2750 /// Invoked to create the lifetime argument(s) for an elided trait object
2751 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2752 /// when the bound is written, even if it is written with `'_` like in
2753 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2754 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2755 match self.anonymous_lifetime_mode {
2756 // NB. We intentionally ignore the create-parameter mode here.
2757 // and instead "pass through" to resolve-lifetimes, which will apply
2758 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2759 // do not act like other elided lifetimes. In other words, given this:
2761 // impl Foo for Box<dyn Debug>
2763 // we do not introduce a fresh `'_` to serve as the bound, but instead
2764 // ultimately translate to the equivalent of:
2766 // impl Foo for Box<dyn Debug + 'static>
2768 // `resolve_lifetime` has the code to make that happen.
2769 AnonymousLifetimeMode::CreateParameter => {}
2771 AnonymousLifetimeMode::ReportError => {
2772 // ReportError applies to explicit use of `'_`.
2775 // This is the normal case.
2776 AnonymousLifetimeMode::PassThrough => {}
2779 let r = hir::Lifetime {
2780 hir_id: self.next_id(),
2782 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2784 debug!("elided_dyn_bound: r={:?}", r);
2788 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2789 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
2792 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2793 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2794 // call site which do not have a macro backtrace. See #61963.
2795 let is_macro_callsite = self
2798 .span_to_snippet(span)
2799 .map(|snippet| snippet.starts_with("#["))
2801 if !is_macro_callsite {
2802 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2806 "trait objects without an explicit `dyn` are deprecated",
2807 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2812 fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId, default: Abi) {
2813 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2814 // call site which do not have a macro backtrace. See #61963.
2815 let is_macro_callsite = self
2818 .span_to_snippet(span)
2819 .map(|snippet| snippet.starts_with("#["))
2821 if !is_macro_callsite {
2822 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2826 "extern declarations without an explicit ABI are deprecated",
2827 BuiltinLintDiagnostics::MissingAbi(span, default),
2832 fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> {
2833 if let Some(_local_def_id) = def_id.as_local() {
2834 // FIXME: This doesn't actually work, items doesn't include everything?
2835 //self.items[&hir::ItemId { def_id: local_def_id }].attrs.into()
2838 self.resolver.item_attrs(def_id, self.sess)
2843 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2844 // Sorting by span ensures that we get things in order within a
2845 // file, and also puts the files in a sensible order.
2846 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2847 body_ids.sort_by_key(|b| bodies[b].value.span);
2851 /// Helper struct for delayed construction of GenericArgs.
2852 struct GenericArgsCtor<'hir> {
2853 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2854 bindings: &'hir [hir::TypeBinding<'hir>],
2855 parenthesized: bool,
2858 impl<'hir> GenericArgsCtor<'hir> {
2859 fn is_empty(&self) -> bool {
2860 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2863 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2865 args: arena.alloc_from_iter(self.args),
2866 bindings: self.bindings,
2867 parenthesized: self.parenthesized,