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 /// Obtains resolution for a `NodeId` with a single resolution.
179 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
181 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
182 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
184 /// Obtains resolution for a label with the given `NodeId`.
185 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
187 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
188 /// This should only return `None` during testing.
189 fn definitions(&mut self) -> &mut Definitions;
191 fn lint_buffer(&mut self) -> &mut LintBuffer;
193 fn next_node_id(&mut self) -> NodeId;
195 fn trait_map(&self) -> &NodeMap<Vec<hir::TraitCandidate>>;
197 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
199 fn local_def_id(&self, node: NodeId) -> LocalDefId;
204 node_id: ast::NodeId,
211 type NtToTokenstream = fn(&Nonterminal, &ParseSess, CanSynthesizeMissingTokens) -> TokenStream;
213 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
214 /// and if so, what meaning it has.
216 enum ImplTraitContext<'b, 'a> {
217 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
218 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
219 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
221 /// Newly generated parameters should be inserted into the given `Vec`.
222 Universal(&'b mut Vec<hir::GenericParam<'a>>),
224 /// Treat `impl Trait` as shorthand for a new opaque type.
225 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
226 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
228 ReturnPositionOpaqueTy {
229 /// `DefId` for the parent function, used to look up necessary
230 /// information later.
232 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
233 origin: hir::OpaqueTyOrigin,
235 /// Impl trait in type aliases, consts and statics.
237 /// Set of lifetimes that this opaque type can capture, if it uses
238 /// them. This includes lifetimes bound since we entered this context.
241 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
243 /// the inner opaque type captures `'a` because it uses it. It doesn't
244 /// need to capture `'b` because it already inherits the lifetime
245 /// parameter from `A`.
246 // FIXME(impl_trait): but `required_region_bounds` will ICE later
248 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
249 /// Origin: Either OpaqueTyOrigin::Misc or OpaqueTyOrigin::Binding,
250 origin: hir::OpaqueTyOrigin,
252 /// `impl Trait` is not accepted in this position.
253 Disallowed(ImplTraitPosition),
256 /// Position in which `impl Trait` is disallowed.
257 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
258 enum ImplTraitPosition {
259 /// Disallowed in `let` / `const` / `static` bindings.
262 /// All other positions.
266 impl<'a> ImplTraitContext<'_, 'a> {
268 fn disallowed() -> Self {
269 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
272 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
273 use self::ImplTraitContext::*;
275 Universal(params) => Universal(params),
276 ReturnPositionOpaqueTy { fn_def_id, origin } => {
277 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
279 OtherOpaqueTy { capturable_lifetimes, origin } => {
280 OtherOpaqueTy { capturable_lifetimes, origin: *origin }
282 Disallowed(pos) => Disallowed(*pos),
287 pub fn lower_crate<'a, 'hir>(
290 resolver: &'a mut dyn ResolverAstLowering,
291 nt_to_tokenstream: NtToTokenstream,
292 arena: &'hir Arena<'hir>,
293 ) -> hir::Crate<'hir> {
294 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
301 items: BTreeMap::new(),
302 trait_items: BTreeMap::new(),
303 impl_items: BTreeMap::new(),
304 foreign_items: BTreeMap::new(),
305 bodies: BTreeMap::new(),
306 trait_impls: BTreeMap::new(),
307 modules: BTreeMap::new(),
308 exported_macros: Vec::new(),
309 non_exported_macro_attrs: Vec::new(),
310 catch_scopes: Vec::new(),
311 loop_scopes: Vec::new(),
312 is_in_loop_condition: false,
313 is_in_trait_impl: false,
314 is_in_dyn_type: false,
315 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
316 type_def_lifetime_params: Default::default(),
317 current_module: CRATE_DEF_ID,
318 current_hir_id_owner: vec![(CRATE_DEF_ID, 0)],
319 item_local_id_counters: Default::default(),
320 node_id_to_hir_id: IndexVec::new(),
321 generator_kind: None,
324 lifetimes_to_define: Vec::new(),
325 is_collecting_in_band_lifetimes: false,
326 in_scope_lifetimes: Vec::new(),
327 allow_try_trait: Some([sym::try_trait][..].into()),
328 allow_gen_future: Some([sym::gen_future][..].into()),
333 #[derive(Copy, Clone, PartialEq)]
335 /// Any path in a type context.
337 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
339 /// The `module::Type` in `module::Type::method` in an expression.
343 enum ParenthesizedGenericArgs {
348 /// What to do when we encounter an **anonymous** lifetime
349 /// reference. Anonymous lifetime references come in two flavors. You
350 /// have implicit, or fully elided, references to lifetimes, like the
351 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
352 /// or `Ref<'_, T>`. These often behave the same, but not always:
354 /// - certain usages of implicit references are deprecated, like
355 /// `Ref<T>`, and we sometimes just give hard errors in those cases
357 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
358 /// the same as `Box<dyn Foo + '_>`.
360 /// We describe the effects of the various modes in terms of three cases:
362 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
363 /// of a `&` (e.g., the missing lifetime in something like `&T`)
364 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
365 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
366 /// elided bounds follow special rules. Note that this only covers
367 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
368 /// '_>` is a case of "modern" elision.
369 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
370 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
371 /// non-deprecated equivalent.
373 /// Currently, the handling of lifetime elision is somewhat spread out
374 /// between HIR lowering and -- as described below -- the
375 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
376 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
377 /// everything into HIR lowering.
378 #[derive(Copy, Clone, Debug)]
379 enum AnonymousLifetimeMode {
380 /// For **Modern** cases, create a new anonymous region parameter
381 /// and reference that.
383 /// For **Dyn Bound** cases, pass responsibility to
384 /// `resolve_lifetime` code.
386 /// For **Deprecated** cases, report an error.
389 /// Give a hard error when either `&` or `'_` is written. Used to
390 /// rule out things like `where T: Foo<'_>`. Does not imply an
391 /// error on default object bounds (e.g., `Box<dyn Foo>`).
394 /// Pass responsibility to `resolve_lifetime` code for all cases.
398 struct TokenStreamLowering<'a> {
399 parse_sess: &'a ParseSess,
400 synthesize_tokens: CanSynthesizeMissingTokens,
401 nt_to_tokenstream: NtToTokenstream,
404 impl<'a> TokenStreamLowering<'a> {
405 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
406 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
409 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
411 TokenTree::Token(token) => self.lower_token(token),
412 TokenTree::Delimited(span, delim, tts) => {
413 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
418 fn lower_token(&mut self, token: Token) -> TokenStream {
420 token::Interpolated(nt) => {
421 let tts = (self.nt_to_tokenstream)(&nt, self.parse_sess, self.synthesize_tokens);
422 TokenTree::Delimited(
423 DelimSpan::from_single(token.span),
425 self.lower_token_stream(tts),
429 _ => TokenTree::Token(token).into(),
434 struct ImplTraitTypeIdVisitor<'a> {
435 ids: &'a mut SmallVec<[NodeId; 1]>,
438 impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
439 fn visit_ty(&mut self, ty: &Ty) {
441 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
443 TyKind::ImplTrait(id, _) => self.ids.push(id),
446 visit::walk_ty(self, ty);
449 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
450 if let Some(ref p) = path_segment.args {
451 if let GenericArgs::Parenthesized(_) = **p {
455 visit::walk_path_segment(self, path_span, path_segment)
459 impl<'a, 'hir> LoweringContext<'a, 'hir> {
460 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
461 /// Full-crate AST visitor that inserts into a fresh
462 /// `LoweringContext` any information that may be
463 /// needed from arbitrary locations in the crate,
464 /// e.g., the number of lifetime generic parameters
465 /// declared for every type and trait definition.
466 struct MiscCollector<'tcx, 'lowering, 'hir> {
467 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
470 impl MiscCollector<'_, '_, '_> {
471 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: LocalDefId) {
473 UseTreeKind::Simple(_, id1, id2) => {
474 for &id in &[id1, id2] {
475 self.lctx.resolver.create_def(
482 self.lctx.allocate_hir_id_counter(id);
485 UseTreeKind::Glob => (),
486 UseTreeKind::Nested(ref trees) => {
487 for &(ref use_tree, id) in trees {
488 let hir_id = self.lctx.allocate_hir_id_counter(id);
489 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
496 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
497 fn visit_item(&mut self, item: &'tcx Item) {
498 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
501 ItemKind::Struct(_, ref generics)
502 | ItemKind::Union(_, ref generics)
503 | ItemKind::Enum(_, ref generics)
504 | ItemKind::TyAlias(box TyAliasKind(_, ref generics, ..))
505 | ItemKind::Trait(box TraitKind(_, _, ref generics, ..)) => {
506 let def_id = self.lctx.resolver.local_def_id(item.id);
511 matches!(param.kind, ast::GenericParamKind::Lifetime { .. })
514 self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
516 ItemKind::Use(ref use_tree) => {
517 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
522 visit::walk_item(self, item);
525 fn visit_assoc_item(&mut self, item: &'tcx AssocItem, ctxt: AssocCtxt) {
526 self.lctx.allocate_hir_id_counter(item.id);
527 visit::walk_assoc_item(self, item, ctxt);
530 fn visit_foreign_item(&mut self, item: &'tcx ForeignItem) {
531 self.lctx.allocate_hir_id_counter(item.id);
532 visit::walk_foreign_item(self, item);
535 fn visit_ty(&mut self, t: &'tcx Ty) {
537 // Mirrors the case in visit::walk_ty
538 TyKind::BareFn(ref f) => {
539 walk_list!(self, visit_generic_param, &f.generic_params);
540 // Mirrors visit::walk_fn_decl
541 for parameter in &f.decl.inputs {
542 // We don't lower the ids of argument patterns
543 self.visit_pat(¶meter.pat);
544 self.visit_ty(¶meter.ty)
546 self.visit_fn_ret_ty(&f.decl.output)
548 TyKind::ImplTrait(def_node_id, _) => {
549 self.lctx.allocate_hir_id_counter(def_node_id);
550 visit::walk_ty(self, t);
552 _ => visit::walk_ty(self, t),
557 self.lower_node_id(CRATE_NODE_ID);
558 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
560 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
561 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
563 let module = self.lower_mod(&c.module);
564 let attrs = self.lower_attrs(&c.attrs);
565 let body_ids = body_ids(&self.bodies);
567 c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
573 .filter_map(|(&k, v)| {
574 self.node_id_to_hir_id.get(k).and_then(|id| id.as_ref()).map(|id| (*id, v.clone()))
578 let mut def_id_to_hir_id = IndexVec::default();
580 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
581 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
582 if def_id_to_hir_id.len() <= def_id.index() {
583 def_id_to_hir_id.resize(def_id.index() + 1, None);
585 def_id_to_hir_id[def_id] = hir_id;
589 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
592 item: hir::CrateItem { module, attrs, span: c.span },
593 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
594 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
596 trait_items: self.trait_items,
597 impl_items: self.impl_items,
598 foreign_items: self.foreign_items,
601 trait_impls: self.trait_impls,
602 modules: self.modules,
608 fn insert_item(&mut self, item: hir::Item<'hir>) -> hir::ItemId {
609 let id = hir::ItemId { def_id: item.def_id };
610 self.items.insert(id, item);
611 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
615 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
616 // Set up the counter if needed.
617 self.item_local_id_counters.entry(owner).or_insert(0);
618 // Always allocate the first `HirId` for the owner itself.
619 let lowered = self.lower_node_id_with_owner(owner, owner);
620 debug_assert_eq!(lowered.local_id.as_u32(), 0);
624 fn lower_node_id_generic(
627 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
629 assert_ne!(ast_node_id, DUMMY_NODE_ID);
631 let min_size = ast_node_id.as_usize() + 1;
633 if min_size > self.node_id_to_hir_id.len() {
634 self.node_id_to_hir_id.resize(min_size, None);
637 if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] {
640 // Generate a new `HirId`.
641 let hir_id = alloc_hir_id(self);
642 self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
648 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
650 .item_local_id_counters
651 .insert(owner, HIR_ID_COUNTER_LOCKED)
652 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
653 let def_id = self.resolver.local_def_id(owner);
654 self.current_hir_id_owner.push((def_id, counter));
656 let (new_def_id, new_counter) = self.current_hir_id_owner.pop().unwrap();
658 debug_assert!(def_id == new_def_id);
659 debug_assert!(new_counter >= counter);
661 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
662 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
666 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
667 /// the `LoweringContext`'s `NodeId => HirId` map.
668 /// Take care not to call this method if the resulting `HirId` is then not
669 /// actually used in the HIR, as that would trigger an assertion in the
670 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
671 /// properly. Calling the method twice with the same `NodeId` is fine though.
672 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
673 self.lower_node_id_generic(ast_node_id, |this| {
674 let &mut (owner, ref mut local_id_counter) =
675 this.current_hir_id_owner.last_mut().unwrap();
676 let local_id = *local_id_counter;
677 *local_id_counter += 1;
678 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
682 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
683 self.lower_node_id_generic(ast_node_id, |this| {
684 let local_id_counter = this
685 .item_local_id_counters
687 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
688 let local_id = *local_id_counter;
690 // We want to be sure not to modify the counter in the map while it
691 // is also on the stack. Otherwise we'll get lost updates when writing
692 // back from the stack to the map.
693 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
695 *local_id_counter += 1;
696 let owner = this.resolver.opt_local_def_id(owner).expect(
697 "you forgot to call `create_def` or are lowering node-IDs \
698 that do not belong to the current owner",
701 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
705 fn next_id(&mut self) -> hir::HirId {
706 let node_id = self.resolver.next_node_id();
707 self.lower_node_id(node_id)
710 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
712 self.lower_node_id_generic(id, |_| {
713 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
718 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
719 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
720 if pr.unresolved_segments() != 0 {
721 panic!("path not fully resolved: {:?}", pr);
727 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
728 self.resolver.get_import_res(id).present_items()
731 fn diagnostic(&self) -> &rustc_errors::Handler {
732 self.sess.diagnostic()
735 /// Reuses the span but adds information like the kind of the desugaring and features that are
736 /// allowed inside this span.
737 fn mark_span_with_reason(
739 reason: DesugaringKind,
741 allow_internal_unstable: Option<Lrc<[Symbol]>>,
743 span.mark_with_reason(allow_internal_unstable, reason, self.sess.edition())
746 fn with_anonymous_lifetime_mode<R>(
748 anonymous_lifetime_mode: AnonymousLifetimeMode,
749 op: impl FnOnce(&mut Self) -> R,
752 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
753 anonymous_lifetime_mode,
755 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
756 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
757 let result = op(self);
758 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
760 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
761 old_anonymous_lifetime_mode
766 /// Creates a new `hir::GenericParam` for every new lifetime and
767 /// type parameter encountered while evaluating `f`. Definitions
768 /// are created with the parent provided. If no `parent_id` is
769 /// provided, no definitions will be returned.
771 /// Presuming that in-band lifetimes are enabled, then
772 /// `self.anonymous_lifetime_mode` will be updated to match the
773 /// parameter while `f` is running (and restored afterwards).
774 fn collect_in_band_defs<T>(
776 parent_def_id: LocalDefId,
777 anonymous_lifetime_mode: AnonymousLifetimeMode,
778 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
779 ) -> (Vec<hir::GenericParam<'hir>>, T) {
780 assert!(!self.is_collecting_in_band_lifetimes);
781 assert!(self.lifetimes_to_define.is_empty());
782 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
784 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
785 self.is_collecting_in_band_lifetimes = true;
787 let (in_band_ty_params, res) = f(self);
789 self.is_collecting_in_band_lifetimes = false;
790 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
792 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
794 let params = lifetimes_to_define
796 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
797 .chain(in_band_ty_params.into_iter())
803 /// Converts a lifetime into a new generic parameter.
804 fn lifetime_to_generic_param(
808 parent_def_id: LocalDefId,
809 ) -> hir::GenericParam<'hir> {
810 let node_id = self.resolver.next_node_id();
812 // Get the name we'll use to make the def-path. Note
813 // that collisions are ok here and this shouldn't
814 // really show up for end-user.
815 let (str_name, kind) = match hir_name {
816 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
817 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
818 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
821 // Add a definition for the in-band lifetime def.
822 self.resolver.create_def(
825 DefPathData::LifetimeNs(str_name),
831 hir_id: self.lower_node_id(node_id),
836 pure_wrt_drop: false,
837 kind: hir::GenericParamKind::Lifetime { kind },
841 /// When there is a reference to some lifetime `'a`, and in-band
842 /// lifetimes are enabled, then we want to push that lifetime into
843 /// the vector of names to define later. In that case, it will get
844 /// added to the appropriate generics.
845 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
846 if !self.is_collecting_in_band_lifetimes {
850 if !self.sess.features_untracked().in_band_lifetimes {
854 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
858 let hir_name = ParamName::Plain(ident);
860 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
861 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
866 self.lifetimes_to_define.push((ident.span, hir_name));
869 /// When we have either an elided or `'_` lifetime in an impl
870 /// header, we convert it to an in-band lifetime.
871 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
872 assert!(self.is_collecting_in_band_lifetimes);
873 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
874 let hir_name = ParamName::Fresh(index);
875 self.lifetimes_to_define.push((span, hir_name));
879 // Evaluates `f` with the lifetimes in `params` in-scope.
880 // This is used to track which lifetimes have already been defined, and
881 // which are new in-band lifetimes that need to have a definition created
883 fn with_in_scope_lifetime_defs<T>(
885 params: &[GenericParam],
886 f: impl FnOnce(&mut Self) -> T,
888 let old_len = self.in_scope_lifetimes.len();
889 let lt_def_names = params.iter().filter_map(|param| match param.kind {
890 GenericParamKind::Lifetime { .. } => {
891 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
895 self.in_scope_lifetimes.extend(lt_def_names);
899 self.in_scope_lifetimes.truncate(old_len);
903 /// Appends in-band lifetime defs and argument-position `impl
904 /// Trait` defs to the existing set of generics.
906 /// Presuming that in-band lifetimes are enabled, then
907 /// `self.anonymous_lifetime_mode` will be updated to match the
908 /// parameter while `f` is running (and restored afterwards).
909 fn add_in_band_defs<T>(
912 parent_def_id: LocalDefId,
913 anonymous_lifetime_mode: AnonymousLifetimeMode,
914 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
915 ) -> (hir::Generics<'hir>, T) {
916 let (in_band_defs, (mut lowered_generics, res)) =
917 self.with_in_scope_lifetime_defs(&generics.params, |this| {
918 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
919 let mut params = Vec::new();
920 // Note: it is necessary to lower generics *before* calling `f`.
921 // When lowering `async fn`, there's a final step when lowering
922 // the return type that assumes that all in-scope lifetimes have
923 // already been added to either `in_scope_lifetimes` or
924 // `lifetimes_to_define`. If we swapped the order of these two,
925 // in-band-lifetimes introduced by generics or where-clauses
926 // wouldn't have been added yet.
928 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
929 let res = f(this, &mut params);
930 (params, (generics, res))
934 lowered_generics.params.extend(in_band_defs);
936 let lowered_generics = lowered_generics.into_generics(self.arena);
937 (lowered_generics, res)
940 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
941 let was_in_dyn_type = self.is_in_dyn_type;
942 self.is_in_dyn_type = in_scope;
944 let result = f(self);
946 self.is_in_dyn_type = was_in_dyn_type;
951 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
952 let was_in_loop_condition = self.is_in_loop_condition;
953 self.is_in_loop_condition = false;
955 let catch_scopes = mem::take(&mut self.catch_scopes);
956 let loop_scopes = mem::take(&mut self.loop_scopes);
958 self.catch_scopes = catch_scopes;
959 self.loop_scopes = loop_scopes;
961 self.is_in_loop_condition = was_in_loop_condition;
966 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
967 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
970 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
971 // Note that we explicitly do not walk the path. Since we don't really
972 // lower attributes (we use the AST version) there is nowhere to keep
973 // the `HirId`s. We don't actually need HIR version of attributes anyway.
974 // Tokens are also not needed after macro expansion and parsing.
975 let kind = match attr.kind {
976 AttrKind::Normal(ref item, _) => AttrKind::Normal(
978 path: item.path.clone(),
979 args: self.lower_mac_args(&item.args),
984 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
987 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
990 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
992 MacArgs::Empty => MacArgs::Empty,
993 MacArgs::Delimited(dspan, delim, ref tokens) => {
994 // This is either a non-key-value attribute, or a `macro_rules!` body.
995 // We either not have any nonterminals present (in the case of an attribute),
996 // or have tokens available for all nonterminals in the case of a nested
997 // `macro_rules`: e.g:
1000 // macro_rules! outer {
1002 // macro_rules! inner {
1009 // In both cases, we don't want to synthesize any tokens
1013 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
1016 // This is an inert key-value attribute - it will never be visible to macros
1017 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
1018 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
1019 MacArgs::Eq(eq_span, ref token) => {
1020 // In valid code the value is always representable as a single literal token.
1021 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
1022 if tokens.len() != 1 {
1024 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
1026 match tokens.into_trees().next() {
1027 Some(TokenTree::Token(token)) => token,
1028 Some(TokenTree::Delimited(_, delim, tokens)) => {
1029 if delim != token::NoDelim {
1030 sess.diagnostic().delay_span_bug(
1032 "unexpected delimiter in key-value attribute's value",
1035 unwrap_single_token(sess, tokens, span)
1037 None => Token::dummy(),
1041 let tokens = TokenStreamLowering {
1042 parse_sess: &self.sess.parse_sess,
1043 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
1044 nt_to_tokenstream: self.nt_to_tokenstream,
1046 .lower_token(token.clone());
1047 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
1052 fn lower_token_stream(
1054 tokens: TokenStream,
1055 synthesize_tokens: CanSynthesizeMissingTokens,
1057 TokenStreamLowering {
1058 parse_sess: &self.sess.parse_sess,
1060 nt_to_tokenstream: self.nt_to_tokenstream,
1062 .lower_token_stream(tokens)
1065 /// Given an associated type constraint like one of these:
1068 /// T: Iterator<Item: Debug>
1070 /// T: Iterator<Item = Debug>
1074 /// returns a `hir::TypeBinding` representing `Item`.
1075 fn lower_assoc_ty_constraint(
1077 constraint: &AssocTyConstraint,
1078 mut itctx: ImplTraitContext<'_, 'hir>,
1079 ) -> hir::TypeBinding<'hir> {
1080 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1082 // lower generic arguments of identifier in constraint
1083 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
1084 let gen_args_ctor = match gen_args {
1085 GenericArgs::AngleBracketed(ref data) => {
1086 self.lower_angle_bracketed_parameter_data(
1088 ParamMode::Explicit,
1093 GenericArgs::Parenthesized(ref data) => {
1094 let mut err = self.sess.struct_span_err(
1096 "parenthesized generic arguments cannot be used in associated type constraints"
1098 // FIXME: try to write a suggestion here
1100 self.lower_angle_bracketed_parameter_data(
1101 &data.as_angle_bracketed_args(),
1102 ParamMode::Explicit,
1108 self.arena.alloc(gen_args_ctor.into_generic_args(&self.arena))
1110 self.arena.alloc(hir::GenericArgs::none())
1113 let kind = match constraint.kind {
1114 AssocTyConstraintKind::Equality { ref ty } => {
1115 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1117 AssocTyConstraintKind::Bound { ref bounds } => {
1118 let mut capturable_lifetimes;
1119 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1120 let (desugar_to_impl_trait, itctx) = match itctx {
1121 // We are in the return position:
1123 // fn foo() -> impl Iterator<Item: Debug>
1127 // fn foo() -> impl Iterator<Item = impl Debug>
1128 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1129 | ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx),
1131 // We are in the argument position, but within a dyn type:
1133 // fn foo(x: dyn Iterator<Item: Debug>)
1137 // fn foo(x: dyn Iterator<Item = impl Debug>)
1138 ImplTraitContext::Universal(..) if self.is_in_dyn_type => (true, itctx),
1140 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1141 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1142 // "impl trait context" to permit `impl Debug` in this position (it desugars
1143 // then to an opaque type).
1145 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1146 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1147 capturable_lifetimes = FxHashSet::default();
1150 ImplTraitContext::OtherOpaqueTy {
1151 capturable_lifetimes: &mut capturable_lifetimes,
1152 origin: hir::OpaqueTyOrigin::Misc,
1157 // We are in the parameter position, but not within a dyn type:
1159 // fn foo(x: impl Iterator<Item: Debug>)
1161 // so we leave it as is and this gets expanded in astconv to a bound like
1162 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1164 _ => (false, itctx),
1167 if desugar_to_impl_trait {
1168 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1169 // constructing the HIR for `impl bounds...` and then lowering that.
1171 let impl_trait_node_id = self.resolver.next_node_id();
1172 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1173 self.resolver.create_def(
1176 DefPathData::ImplTrait,
1181 self.with_dyn_type_scope(false, |this| {
1182 let node_id = this.resolver.next_node_id();
1183 let ty = this.lower_ty(
1186 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1187 span: constraint.span,
1193 hir::TypeBindingKind::Equality { ty }
1196 // Desugar `AssocTy: Bounds` into a type binding where the
1197 // later desugars into a trait predicate.
1198 let bounds = self.lower_param_bounds(bounds, itctx);
1200 hir::TypeBindingKind::Constraint { bounds }
1206 hir_id: self.lower_node_id(constraint.id),
1207 ident: constraint.ident,
1210 span: constraint.span,
1214 fn lower_generic_arg(
1216 arg: &ast::GenericArg,
1217 itctx: ImplTraitContext<'_, 'hir>,
1218 ) -> hir::GenericArg<'hir> {
1220 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1221 ast::GenericArg::Type(ty) => {
1222 // We parse const arguments as path types as we cannot distinguish them during
1223 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1224 // type and value namespaces. If we resolved the path in the value namespace, we
1225 // transform it into a generic const argument.
1226 if let TyKind::Path(ref qself, ref path) = ty.kind {
1227 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1228 let res = partial_res.base_res();
1229 if !res.matches_ns(Namespace::TypeNS) {
1231 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1235 // Construct a AnonConst where the expr is the "ty"'s path.
1237 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1238 let node_id = self.resolver.next_node_id();
1240 // Add a definition for the in-band const def.
1241 self.resolver.create_def(
1244 DefPathData::AnonConst,
1249 let path_expr = Expr {
1251 kind: ExprKind::Path(qself.clone(), path.clone()),
1253 attrs: AttrVec::new(),
1257 let ct = self.with_new_scopes(|this| hir::AnonConst {
1258 hir_id: this.lower_node_id(node_id),
1259 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1261 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1265 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1267 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1268 value: self.lower_anon_const(&ct),
1269 span: ct.value.span,
1274 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1275 self.arena.alloc(self.lower_ty_direct(t, itctx))
1281 qself: &Option<QSelf>,
1283 param_mode: ParamMode,
1284 itctx: ImplTraitContext<'_, 'hir>,
1285 ) -> hir::Ty<'hir> {
1286 let id = self.lower_node_id(t.id);
1287 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1288 let ty = self.ty_path(id, t.span, qpath);
1289 if let hir::TyKind::TraitObject(..) = ty.kind {
1290 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1295 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1296 hir::Ty { hir_id: self.next_id(), kind, span }
1299 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1300 self.ty(span, hir::TyKind::Tup(tys))
1303 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1304 let kind = match t.kind {
1305 TyKind::Infer => hir::TyKind::Infer,
1306 TyKind::Err => hir::TyKind::Err,
1307 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1308 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1309 TyKind::Rptr(ref region, ref mt) => {
1310 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1311 let lifetime = match *region {
1312 Some(ref lt) => self.lower_lifetime(lt),
1313 None => self.elided_ref_lifetime(span),
1315 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1317 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1318 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1319 let span = this.sess.source_map().next_point(t.span.shrink_to_lo());
1320 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1321 generic_params: this.lower_generic_params(
1323 &NodeMap::default(),
1324 ImplTraitContext::disallowed(),
1326 unsafety: this.lower_unsafety(f.unsafety),
1327 abi: this.lower_extern(f.ext, span, t.id),
1328 decl: this.lower_fn_decl(&f.decl, None, false, None),
1329 param_names: this.lower_fn_params_to_names(&f.decl),
1333 TyKind::Never => hir::TyKind::Never,
1334 TyKind::Tup(ref tys) => {
1335 hir::TyKind::Tup(self.arena.alloc_from_iter(
1336 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1339 TyKind::Paren(ref ty) => {
1340 return self.lower_ty_direct(ty, itctx);
1342 TyKind::Path(ref qself, ref path) => {
1343 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1345 TyKind::ImplicitSelf => {
1346 let res = self.expect_full_res(t.id);
1347 let res = self.lower_res(res);
1348 hir::TyKind::Path(hir::QPath::Resolved(
1350 self.arena.alloc(hir::Path {
1352 segments: arena_vec![self; hir::PathSegment::from_ident(
1353 Ident::with_dummy_span(kw::SelfUpper)
1359 TyKind::Array(ref ty, ref length) => {
1360 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1362 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1363 TyKind::TraitObject(ref bounds, kind) => {
1364 let mut lifetime_bound = None;
1365 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1367 this.arena.alloc_from_iter(bounds.iter().filter_map(
1368 |bound| match *bound {
1369 GenericBound::Trait(
1371 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1372 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1373 // `?const ?Bound` will cause an error during AST validation
1374 // anyways, so treat it like `?Bound` as compilation proceeds.
1375 GenericBound::Trait(
1377 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1379 GenericBound::Outlives(ref lifetime) => {
1380 if lifetime_bound.is_none() {
1381 lifetime_bound = Some(this.lower_lifetime(lifetime));
1387 let lifetime_bound =
1388 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1389 (bounds, lifetime_bound)
1391 if kind != TraitObjectSyntax::Dyn {
1392 self.maybe_lint_bare_trait(t.span, t.id, false);
1394 hir::TyKind::TraitObject(bounds, lifetime_bound)
1396 TyKind::ImplTrait(def_node_id, ref bounds) => {
1399 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1400 .lower_opaque_impl_trait(
1406 |this| this.lower_param_bounds(bounds, itctx),
1408 ImplTraitContext::OtherOpaqueTy { ref capturable_lifetimes, origin } => {
1409 // Reset capturable lifetimes, any nested impl trait
1410 // types will inherit lifetimes from this opaque type,
1411 // so don't need to capture them again.
1412 let nested_itctx = ImplTraitContext::OtherOpaqueTy {
1413 capturable_lifetimes: &mut FxHashSet::default(),
1416 self.lower_opaque_impl_trait(
1421 Some(capturable_lifetimes),
1422 |this| this.lower_param_bounds(bounds, nested_itctx),
1425 ImplTraitContext::Universal(in_band_ty_params) => {
1426 // Add a definition for the in-band `Param`.
1427 let def_id = self.resolver.local_def_id(def_node_id);
1429 self.allocate_hir_id_counter(def_node_id);
1431 let hir_bounds = self.with_hir_id_owner(def_node_id, |this| {
1432 this.lower_param_bounds(
1434 ImplTraitContext::Universal(in_band_ty_params),
1437 // Set the name to `impl Bound1 + Bound2`.
1438 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1439 in_band_ty_params.push(hir::GenericParam {
1440 hir_id: self.lower_node_id(def_node_id),
1441 name: ParamName::Plain(ident),
1442 pure_wrt_drop: false,
1446 kind: hir::GenericParamKind::Type {
1448 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1452 hir::TyKind::Path(hir::QPath::Resolved(
1454 self.arena.alloc(hir::Path {
1456 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1457 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1461 ImplTraitContext::Disallowed(pos) => {
1462 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1463 "bindings or function and inherent method return types"
1465 "function and inherent method return types"
1467 let mut err = struct_span_err!(
1471 "`impl Trait` not allowed outside of {}",
1474 if pos == ImplTraitPosition::Binding && self.sess.is_nightly_build() {
1476 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1477 attributes to enable",
1485 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1486 TyKind::CVarArgs => {
1487 self.sess.delay_span_bug(
1489 "`TyKind::CVarArgs` should have been handled elsewhere",
1495 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1498 fn lower_opaque_impl_trait(
1501 fn_def_id: Option<DefId>,
1502 origin: hir::OpaqueTyOrigin,
1503 opaque_ty_node_id: NodeId,
1504 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1505 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1506 ) -> hir::TyKind<'hir> {
1508 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1509 fn_def_id, opaque_ty_node_id, span,
1512 // Make sure we know that some funky desugaring has been going on here.
1513 // This is a first: there is code in other places like for loop
1514 // desugaring that explicitly states that we don't want to track that.
1515 // Not tracking it makes lints in rustc and clippy very fragile, as
1516 // frequently opened issues show.
1517 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1519 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1521 self.allocate_hir_id_counter(opaque_ty_node_id);
1523 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1525 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1529 capturable_lifetimes,
1532 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1534 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1536 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1537 let opaque_ty_item = hir::OpaqueTy {
1538 generics: hir::Generics {
1539 params: lifetime_defs,
1540 where_clause: hir::WhereClause { predicates: &[], span },
1544 impl_trait_fn: fn_def_id,
1548 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1549 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
1551 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1552 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1556 /// Registers a new opaque type with the proper `NodeId`s and
1557 /// returns the lowered node-ID for the opaque type.
1558 fn generate_opaque_type(
1560 opaque_ty_id: LocalDefId,
1561 opaque_ty_item: hir::OpaqueTy<'hir>,
1563 opaque_ty_span: Span,
1565 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1566 // Generate an `type Foo = impl Trait;` declaration.
1567 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1568 let opaque_ty_item = hir::Item {
1569 def_id: opaque_ty_id,
1570 ident: Ident::invalid(),
1571 attrs: Default::default(),
1572 kind: opaque_ty_item_kind,
1573 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1574 span: opaque_ty_span,
1577 // Insert the item into the global item list. This usually happens
1578 // automatically for all AST items. But this opaque type item
1579 // does not actually exist in the AST.
1580 self.insert_item(opaque_ty_item);
1583 fn lifetimes_from_impl_trait_bounds(
1585 opaque_ty_id: NodeId,
1586 parent_def_id: LocalDefId,
1587 bounds: hir::GenericBounds<'hir>,
1588 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
1589 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1591 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1592 parent_def_id={:?}, \
1594 opaque_ty_id, parent_def_id, bounds,
1597 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1598 // appear in the bounds, excluding lifetimes that are created within the bounds.
1599 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1600 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1601 context: &'r mut LoweringContext<'a, 'hir>,
1603 opaque_ty_id: NodeId,
1604 collect_elided_lifetimes: bool,
1605 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1606 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1607 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1608 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1609 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
1612 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1613 type Map = intravisit::ErasedMap<'v>;
1615 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1616 intravisit::NestedVisitorMap::None
1619 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1620 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1621 if parameters.parenthesized {
1622 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1623 self.collect_elided_lifetimes = false;
1624 intravisit::walk_generic_args(self, span, parameters);
1625 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1627 intravisit::walk_generic_args(self, span, parameters);
1631 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1632 // Don't collect elided lifetimes used inside of `fn()` syntax.
1633 if let hir::TyKind::BareFn(_) = t.kind {
1634 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1635 self.collect_elided_lifetimes = false;
1637 // Record the "stack height" of `for<'a>` lifetime bindings
1638 // to be able to later fully undo their introduction.
1639 let old_len = self.currently_bound_lifetimes.len();
1640 intravisit::walk_ty(self, t);
1641 self.currently_bound_lifetimes.truncate(old_len);
1643 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1645 intravisit::walk_ty(self, t)
1649 fn visit_poly_trait_ref(
1651 trait_ref: &'v hir::PolyTraitRef<'v>,
1652 modifier: hir::TraitBoundModifier,
1654 // Record the "stack height" of `for<'a>` lifetime bindings
1655 // to be able to later fully undo their introduction.
1656 let old_len = self.currently_bound_lifetimes.len();
1657 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1658 self.currently_bound_lifetimes.truncate(old_len);
1661 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1662 // Record the introduction of 'a in `for<'a> ...`.
1663 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1664 // Introduce lifetimes one at a time so that we can handle
1665 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1666 let lt_name = hir::LifetimeName::Param(param.name);
1667 self.currently_bound_lifetimes.push(lt_name);
1670 intravisit::walk_generic_param(self, param);
1673 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1674 let name = match lifetime.name {
1675 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1676 if self.collect_elided_lifetimes {
1677 // Use `'_` for both implicit and underscore lifetimes in
1678 // `type Foo<'_> = impl SomeTrait<'_>;`.
1679 hir::LifetimeName::Underscore
1684 hir::LifetimeName::Param(_) => lifetime.name,
1686 // Refers to some other lifetime that is "in
1687 // scope" within the type.
1688 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1690 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1693 if !self.currently_bound_lifetimes.contains(&name)
1694 && !self.already_defined_lifetimes.contains(&name)
1695 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
1697 self.already_defined_lifetimes.insert(name);
1699 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1700 hir_id: self.context.next_id(),
1701 span: lifetime.span,
1705 let def_node_id = self.context.resolver.next_node_id();
1707 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1708 self.context.resolver.create_def(
1711 DefPathData::LifetimeNs(name.ident().name),
1716 let (name, kind) = match name {
1717 hir::LifetimeName::Underscore => (
1718 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1719 hir::LifetimeParamKind::Elided,
1721 hir::LifetimeName::Param(param_name) => {
1722 (param_name, hir::LifetimeParamKind::Explicit)
1724 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1727 self.output_lifetime_params.push(hir::GenericParam {
1730 span: lifetime.span,
1731 pure_wrt_drop: false,
1734 kind: hir::GenericParamKind::Lifetime { kind },
1740 let mut lifetime_collector = ImplTraitLifetimeCollector {
1742 parent: parent_def_id,
1744 collect_elided_lifetimes: true,
1745 currently_bound_lifetimes: Vec::new(),
1746 already_defined_lifetimes: FxHashSet::default(),
1747 output_lifetimes: Vec::new(),
1748 output_lifetime_params: Vec::new(),
1749 lifetimes_to_include,
1752 for bound in bounds {
1753 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1756 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1760 self.arena.alloc_from_iter(output_lifetimes),
1761 self.arena.alloc_from_iter(output_lifetime_params),
1765 fn lower_local(&mut self, l: &Local) -> (hir::Local<'hir>, SmallVec<[NodeId; 1]>) {
1766 let mut ids = SmallVec::<[NodeId; 1]>::new();
1767 if self.sess.features_untracked().impl_trait_in_bindings {
1768 if let Some(ref ty) = l.ty {
1769 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1770 visitor.visit_ty(ty);
1773 let ty = l.ty.as_ref().map(|t| {
1774 let mut capturable_lifetimes;
1777 if self.sess.features_untracked().impl_trait_in_bindings {
1778 capturable_lifetimes = FxHashSet::default();
1779 ImplTraitContext::OtherOpaqueTy {
1780 capturable_lifetimes: &mut capturable_lifetimes,
1781 origin: hir::OpaqueTyOrigin::Binding,
1784 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1788 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1791 hir_id: self.lower_node_id(l.id),
1793 pat: self.lower_pat(&l.pat),
1796 attrs: l.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
1797 source: hir::LocalSource::Normal,
1803 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1804 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1805 // as they are not explicit in HIR/Ty function signatures.
1806 // (instead, the `c_variadic` flag is set to `true`)
1807 let mut inputs = &decl.inputs[..];
1808 if decl.c_variadic() {
1809 inputs = &inputs[..inputs.len() - 1];
1811 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1812 PatKind::Ident(_, ident, _) => ident,
1813 _ => Ident::new(kw::Empty, param.pat.span),
1817 // Lowers a function declaration.
1819 // `decl`: the unlowered (AST) function declaration.
1820 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1821 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1822 // `make_ret_async` is also `Some`.
1823 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1824 // This guards against trait declarations and implementations where `impl Trait` is
1826 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1827 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1828 // return type `impl Trait` item.
1832 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1833 impl_trait_return_allow: bool,
1834 make_ret_async: Option<NodeId>,
1835 ) -> &'hir hir::FnDecl<'hir> {
1839 in_band_ty_params: {:?}, \
1840 impl_trait_return_allow: {}, \
1841 make_ret_async: {:?})",
1842 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1844 let lt_mode = if make_ret_async.is_some() {
1845 // In `async fn`, argument-position elided lifetimes
1846 // must be transformed into fresh generic parameters so that
1847 // they can be applied to the opaque `impl Trait` return type.
1848 AnonymousLifetimeMode::CreateParameter
1850 self.anonymous_lifetime_mode
1853 let c_variadic = decl.c_variadic();
1855 // Remember how many lifetimes were already around so that we can
1856 // only look at the lifetime parameters introduced by the arguments.
1857 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1858 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1859 // as they are not explicit in HIR/Ty function signatures.
1860 // (instead, the `c_variadic` flag is set to `true`)
1861 let mut inputs = &decl.inputs[..];
1863 inputs = &inputs[..inputs.len() - 1];
1865 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1866 if let Some((_, ibty)) = &mut in_band_ty_params {
1867 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
1869 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1874 let output = if let Some(ret_id) = make_ret_async {
1875 self.lower_async_fn_ret_ty(
1877 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1882 FnRetTy::Ty(ref ty) => {
1883 let context = match in_band_ty_params {
1884 Some((def_id, _)) if impl_trait_return_allow => {
1885 ImplTraitContext::ReturnPositionOpaqueTy {
1887 origin: hir::OpaqueTyOrigin::FnReturn,
1890 _ => ImplTraitContext::disallowed(),
1892 hir::FnRetTy::Return(self.lower_ty(ty, context))
1894 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(span),
1898 self.arena.alloc(hir::FnDecl {
1902 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1903 use BindingMode::{ByRef, ByValue};
1904 let is_mutable_pat = matches!(
1906 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1910 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1911 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1912 // Given we are only considering `ImplicitSelf` types, we needn't consider
1913 // the case where we have a mutable pattern to a reference as that would
1914 // no longer be an `ImplicitSelf`.
1915 TyKind::Rptr(_, ref mt)
1916 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1918 hir::ImplicitSelfKind::MutRef
1920 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1921 hir::ImplicitSelfKind::ImmRef
1923 _ => hir::ImplicitSelfKind::None,
1929 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1930 // combined with the following definition of `OpaqueTy`:
1932 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1934 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1935 // `output`: unlowered output type (`T` in `-> T`)
1936 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1937 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1938 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1939 fn lower_async_fn_ret_ty(
1943 opaque_ty_node_id: NodeId,
1944 ) -> hir::FnRetTy<'hir> {
1946 "lower_async_fn_ret_ty(\
1949 opaque_ty_node_id={:?})",
1950 output, fn_def_id, opaque_ty_node_id,
1953 let span = output.span();
1955 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1957 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1959 self.allocate_hir_id_counter(opaque_ty_node_id);
1961 // When we create the opaque type for this async fn, it is going to have
1962 // to capture all the lifetimes involved in the signature (including in the
1963 // return type). This is done by introducing lifetime parameters for:
1965 // - all the explicitly declared lifetimes from the impl and function itself;
1966 // - all the elided lifetimes in the fn arguments;
1967 // - all the elided lifetimes in the return type.
1969 // So for example in this snippet:
1972 // impl<'a> Foo<'a> {
1973 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1974 // // ^ '0 ^ '1 ^ '2
1975 // // elided lifetimes used below
1980 // we would create an opaque type like:
1983 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1986 // and we would then desugar `bar` to the equivalent of:
1989 // impl<'a> Foo<'a> {
1990 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1994 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1995 // this is because the elided lifetimes from the return type
1996 // should be figured out using the ordinary elision rules, and
1997 // this desugaring achieves that.
1999 // The variable `input_lifetimes_count` tracks the number of
2000 // lifetime parameters to the opaque type *not counting* those
2001 // lifetimes elided in the return type. This includes those
2002 // that are explicitly declared (`in_scope_lifetimes`) and
2003 // those elided lifetimes we found in the arguments (current
2004 // content of `lifetimes_to_define`). Next, we will process
2005 // the return type, which will cause `lifetimes_to_define` to
2007 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2009 let lifetime_params = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2010 // We have to be careful to get elision right here. The
2011 // idea is that we create a lifetime parameter for each
2012 // lifetime in the return type. So, given a return type
2013 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2014 // Future<Output = &'1 [ &'2 u32 ]>`.
2016 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2017 // hence the elision takes place at the fn site.
2018 let future_bound = this
2019 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
2020 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
2023 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2025 // Calculate all the lifetimes that should be captured
2026 // by the opaque type. This should include all in-scope
2027 // lifetime parameters, including those defined in-band.
2029 // Note: this must be done after lowering the output type,
2030 // as the output type may introduce new in-band lifetimes.
2031 let lifetime_params: Vec<(Span, ParamName)> = this
2035 .map(|name| (name.ident().span, name))
2036 .chain(this.lifetimes_to_define.iter().cloned())
2039 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2040 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2041 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2043 let generic_params =
2044 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
2045 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
2048 let opaque_ty_item = hir::OpaqueTy {
2049 generics: hir::Generics {
2050 params: generic_params,
2051 where_clause: hir::WhereClause { predicates: &[], span },
2054 bounds: arena_vec![this; future_bound],
2055 impl_trait_fn: Some(fn_def_id),
2056 origin: hir::OpaqueTyOrigin::AsyncFn,
2059 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
2060 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
2065 // As documented above on the variable
2066 // `input_lifetimes_count`, we need to create the lifetime
2067 // arguments to our opaque type. Continuing with our example,
2068 // we're creating the type arguments for the return type:
2071 // Bar<'a, 'b, '0, '1, '_>
2074 // For the "input" lifetime parameters, we wish to create
2075 // references to the parameters themselves, including the
2076 // "implicit" ones created from parameter types (`'a`, `'b`,
2079 // For the "output" lifetime parameters, we just want to
2081 let mut generic_args = Vec::with_capacity(lifetime_params.len());
2082 generic_args.extend(lifetime_params[..input_lifetimes_count].iter().map(
2083 |&(span, hir_name)| {
2084 // Input lifetime like `'a` or `'1`:
2085 GenericArg::Lifetime(hir::Lifetime {
2086 hir_id: self.next_id(),
2088 name: hir::LifetimeName::Param(hir_name),
2092 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
2093 // Output lifetime like `'_`.
2094 GenericArg::Lifetime(hir::Lifetime {
2095 hir_id: self.next_id(),
2097 name: hir::LifetimeName::Implicit,
2099 let generic_args = self.arena.alloc_from_iter(generic_args);
2101 // Create the `Foo<...>` reference itself. Note that the `type
2102 // Foo = impl Trait` is, internally, created as a child of the
2103 // async fn, so the *type parameters* are inherited. It's
2104 // only the lifetime parameters that we must supply.
2106 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
2107 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2108 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2111 /// Transforms `-> T` into `Future<Output = T>`
2112 fn lower_async_fn_output_type_to_future_bound(
2117 ) -> hir::GenericBound<'hir> {
2118 // Compute the `T` in `Future<Output = T>` from the return type.
2119 let output_ty = match output {
2120 FnRetTy::Ty(ty) => {
2121 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2122 // `impl Future` opaque type that `async fn` implicitly
2124 let context = ImplTraitContext::ReturnPositionOpaqueTy {
2126 origin: hir::OpaqueTyOrigin::FnReturn,
2128 self.lower_ty(ty, context)
2130 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2134 let future_args = self.arena.alloc(hir::GenericArgs {
2136 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2137 parenthesized: false,
2140 hir::GenericBound::LangItemTrait(
2141 // ::std::future::Future<future_params>
2142 hir::LangItem::Future,
2149 fn lower_param_bound(
2152 itctx: ImplTraitContext<'_, 'hir>,
2153 ) -> hir::GenericBound<'hir> {
2155 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2156 self.lower_poly_trait_ref(ty, itctx),
2157 self.lower_trait_bound_modifier(modifier),
2159 GenericBound::Outlives(ref lifetime) => {
2160 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2165 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2166 let span = l.ident.span;
2168 ident if ident.name == kw::StaticLifetime => {
2169 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2171 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2172 AnonymousLifetimeMode::CreateParameter => {
2173 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2174 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2177 AnonymousLifetimeMode::PassThrough => {
2178 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2181 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2184 self.maybe_collect_in_band_lifetime(ident);
2185 let param_name = ParamName::Plain(ident);
2186 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2191 fn new_named_lifetime(
2195 name: hir::LifetimeName,
2196 ) -> hir::Lifetime {
2197 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2200 fn lower_generic_params_mut<'s>(
2202 params: &'s [GenericParam],
2203 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2204 mut itctx: ImplTraitContext<'s, 'hir>,
2205 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2208 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2211 fn lower_generic_params(
2213 params: &[GenericParam],
2214 add_bounds: &NodeMap<Vec<GenericBound>>,
2215 itctx: ImplTraitContext<'_, 'hir>,
2216 ) -> &'hir [hir::GenericParam<'hir>] {
2217 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2220 fn lower_generic_param(
2222 param: &GenericParam,
2223 add_bounds: &NodeMap<Vec<GenericBound>>,
2224 mut itctx: ImplTraitContext<'_, 'hir>,
2225 ) -> hir::GenericParam<'hir> {
2226 let mut bounds: Vec<_> = self
2227 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2228 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2231 let (name, kind) = match param.kind {
2232 GenericParamKind::Lifetime => {
2233 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2234 self.is_collecting_in_band_lifetimes = false;
2237 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2238 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2240 let param_name = match lt.name {
2241 hir::LifetimeName::Param(param_name) => param_name,
2242 hir::LifetimeName::Implicit
2243 | hir::LifetimeName::Underscore
2244 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2245 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2246 self.sess.diagnostic().span_bug(
2248 "object-lifetime-default should not occur here",
2251 hir::LifetimeName::Error => ParamName::Error,
2255 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2257 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2261 GenericParamKind::Type { ref default, .. } => {
2262 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2263 if !add_bounds.is_empty() {
2264 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2265 bounds.extend(params);
2268 let kind = hir::GenericParamKind::Type {
2269 default: default.as_ref().map(|x| {
2272 ImplTraitContext::OtherOpaqueTy {
2273 capturable_lifetimes: &mut FxHashSet::default(),
2274 origin: hir::OpaqueTyOrigin::Misc,
2281 .filter(|attr| self.sess.check_name(attr, sym::rustc_synthetic))
2282 .map(|_| hir::SyntheticTyParamKind::FromAttr)
2286 (hir::ParamName::Plain(param.ident), kind)
2288 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2290 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2291 this.lower_ty(&ty, ImplTraitContext::disallowed())
2293 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2295 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty, default })
2300 hir_id: self.lower_node_id(param.id),
2302 span: param.ident.span,
2303 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
2304 attrs: self.lower_attrs(¶m.attrs),
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 mut expr: Option<&'hir _> = None;
2386 let stmts = self.arena.alloc_from_iter(
2390 .filter_map(|(index, stmt)| {
2391 if index == b.stmts.len() - 1 {
2392 if let StmtKind::Expr(ref e) = stmt.kind {
2393 expr = Some(self.lower_expr(e));
2396 Some(self.lower_stmt(stmt))
2399 Some(self.lower_stmt(stmt))
2404 let rules = self.lower_block_check_mode(&b.rules);
2405 let hir_id = self.lower_node_id(b.id);
2407 hir::Block { hir_id, stmts, expr, rules, span: b.span, targeted_by_break }
2410 /// Lowers a block directly to an expression, presuming that it
2411 /// has no attributes and is not targeted by a `break`.
2412 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2413 let block = self.lower_block(b, false);
2414 self.expr_block(block, AttrVec::new())
2417 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2418 self.with_new_scopes(|this| hir::AnonConst {
2419 hir_id: this.lower_node_id(c.id),
2420 body: this.lower_const_body(c.value.span, Some(&c.value)),
2424 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2425 let kind = match s.kind {
2426 StmtKind::Local(ref l) => {
2427 let (l, item_ids) = self.lower_local(l);
2428 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
2431 let item_id = hir::ItemId {
2432 // All the items that `lower_local` finds are `impl Trait` types.
2433 def_id: self.lower_node_id(item_id).expect_owner(),
2435 self.stmt(s.span, hir::StmtKind::Item(item_id))
2440 hir_id: self.lower_node_id(s.id),
2441 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2447 StmtKind::Item(ref it) => {
2448 // Can only use the ID once.
2449 let mut id = Some(s.id);
2456 .map(|id| self.lower_node_id(id))
2457 .unwrap_or_else(|| self.next_id());
2459 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2463 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2464 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
2465 StmtKind::Empty => return smallvec![],
2466 StmtKind::MacCall(..) => panic!("shouldn't exist here"),
2468 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
2471 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2473 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2474 BlockCheckMode::Unsafe(u) => {
2475 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2480 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2482 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2483 UserProvided => hir::UnsafeSource::UserProvided,
2487 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2489 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2490 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2492 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2493 // placeholder for compilation to proceed.
2494 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2495 hir::TraitBoundModifier::Maybe
2500 // Helper methods for building HIR.
2502 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2503 hir::Stmt { span, kind, hir_id: self.next_id() }
2506 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2507 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2514 init: Option<&'hir hir::Expr<'hir>>,
2515 pat: &'hir hir::Pat<'hir>,
2516 source: hir::LocalSource,
2517 ) -> hir::Stmt<'hir> {
2518 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2519 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2522 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2523 self.block_all(expr.span, &[], Some(expr))
2529 stmts: &'hir [hir::Stmt<'hir>],
2530 expr: Option<&'hir hir::Expr<'hir>>,
2531 ) -> &'hir hir::Block<'hir> {
2532 let blk = hir::Block {
2535 hir_id: self.next_id(),
2536 rules: hir::BlockCheckMode::DefaultBlock,
2538 targeted_by_break: false,
2540 self.arena.alloc(blk)
2543 /// Constructs a `true` or `false` literal pattern.
2544 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2545 let expr = self.expr_bool(span, val);
2546 self.pat(span, hir::PatKind::Lit(expr))
2549 fn pat_ok(&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::ResultOk, field)
2554 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2555 let field = self.single_pat_field(span, pat);
2556 self.pat_lang_item_variant(span, hir::LangItem::ResultErr, field)
2559 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2560 let field = self.single_pat_field(span, pat);
2561 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2564 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2565 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2568 fn single_pat_field(
2571 pat: &'hir hir::Pat<'hir>,
2572 ) -> &'hir [hir::FieldPat<'hir>] {
2573 let field = hir::FieldPat {
2574 hir_id: self.next_id(),
2575 ident: Ident::new(sym::integer(0), span),
2576 is_shorthand: false,
2580 arena_vec![self; field]
2583 fn pat_lang_item_variant(
2586 lang_item: hir::LangItem,
2587 fields: &'hir [hir::FieldPat<'hir>],
2588 ) -> &'hir hir::Pat<'hir> {
2589 let qpath = hir::QPath::LangItem(lang_item, span);
2590 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2593 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2594 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2597 fn pat_ident_binding_mode(
2601 bm: hir::BindingAnnotation,
2602 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2603 let hir_id = self.next_id();
2606 self.arena.alloc(hir::Pat {
2608 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2610 default_binding_modes: true,
2616 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2617 self.pat(span, hir::PatKind::Wild)
2620 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2621 self.arena.alloc(hir::Pat {
2622 hir_id: self.next_id(),
2625 default_binding_modes: true,
2629 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2630 self.arena.alloc(hir::Pat {
2631 hir_id: self.next_id(),
2634 default_binding_modes: false,
2640 mut hir_id: hir::HirId,
2642 qpath: hir::QPath<'hir>,
2643 ) -> hir::Ty<'hir> {
2644 let kind = match qpath {
2645 hir::QPath::Resolved(None, path) => {
2646 // Turn trait object paths into `TyKind::TraitObject` instead.
2648 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2649 let principal = hir::PolyTraitRef {
2650 bound_generic_params: &[],
2651 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2655 // The original ID is taken by the `PolyTraitRef`,
2656 // so the `Ty` itself needs a different one.
2657 hir_id = self.next_id();
2658 hir::TyKind::TraitObject(
2659 arena_vec![self; principal],
2660 self.elided_dyn_bound(span),
2663 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2666 _ => hir::TyKind::Path(qpath),
2669 hir::Ty { hir_id, kind, span }
2672 /// Invoked to create the lifetime argument for a type `&T`
2673 /// with no explicit lifetime.
2674 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2675 match self.anonymous_lifetime_mode {
2676 // Intercept when we are in an impl header or async fn and introduce an in-band
2678 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2680 AnonymousLifetimeMode::CreateParameter => {
2681 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2683 hir_id: self.next_id(),
2685 name: hir::LifetimeName::Param(fresh_name),
2689 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2691 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2695 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2696 /// return a "error lifetime".
2697 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2698 let (id, msg, label) = match id {
2699 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2702 self.resolver.next_node_id(),
2703 "`&` without an explicit lifetime name cannot be used here",
2704 "explicit lifetime name needed here",
2708 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2709 err.span_label(span, label);
2712 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2715 /// Invoked to create the lifetime argument(s) for a path like
2716 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2717 /// sorts of cases are deprecated. This may therefore report a warning or an
2718 /// error, depending on the mode.
2719 fn elided_path_lifetimes<'s>(
2723 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2724 (0..count).map(move |_| self.elided_path_lifetime(span))
2727 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2728 match self.anonymous_lifetime_mode {
2729 AnonymousLifetimeMode::CreateParameter => {
2730 // We should have emitted E0726 when processing this path above
2732 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2733 let id = self.resolver.next_node_id();
2734 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2736 // `PassThrough` is the normal case.
2737 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2738 // is unsuitable here, as these can occur from missing lifetime parameters in a
2739 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2740 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2741 // later, at which point a suitable error will be emitted.
2742 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2743 self.new_implicit_lifetime(span)
2748 /// Invoked to create the lifetime argument(s) for an elided trait object
2749 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2750 /// when the bound is written, even if it is written with `'_` like in
2751 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2752 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2753 match self.anonymous_lifetime_mode {
2754 // NB. We intentionally ignore the create-parameter mode here.
2755 // and instead "pass through" to resolve-lifetimes, which will apply
2756 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2757 // do not act like other elided lifetimes. In other words, given this:
2759 // impl Foo for Box<dyn Debug>
2761 // we do not introduce a fresh `'_` to serve as the bound, but instead
2762 // ultimately translate to the equivalent of:
2764 // impl Foo for Box<dyn Debug + 'static>
2766 // `resolve_lifetime` has the code to make that happen.
2767 AnonymousLifetimeMode::CreateParameter => {}
2769 AnonymousLifetimeMode::ReportError => {
2770 // ReportError applies to explicit use of `'_`.
2773 // This is the normal case.
2774 AnonymousLifetimeMode::PassThrough => {}
2777 let r = hir::Lifetime {
2778 hir_id: self.next_id(),
2780 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2782 debug!("elided_dyn_bound: r={:?}", r);
2786 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2787 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
2790 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2791 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2792 // call site which do not have a macro backtrace. See #61963.
2793 let is_macro_callsite = self
2796 .span_to_snippet(span)
2797 .map(|snippet| snippet.starts_with("#["))
2799 if !is_macro_callsite {
2800 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2804 "trait objects without an explicit `dyn` are deprecated",
2805 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2810 fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId, default: Abi) {
2811 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2812 // call site which do not have a macro backtrace. See #61963.
2813 let is_macro_callsite = self
2816 .span_to_snippet(span)
2817 .map(|snippet| snippet.starts_with("#["))
2819 if !is_macro_callsite {
2820 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2824 "extern declarations without an explicit ABI are deprecated",
2825 BuiltinLintDiagnostics::MissingAbi(span, default),
2831 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2832 // Sorting by span ensures that we get things in order within a
2833 // file, and also puts the files in a sensible order.
2834 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2835 body_ids.sort_by_key(|b| bodies[b].value.span);
2839 /// Helper struct for delayed construction of GenericArgs.
2840 struct GenericArgsCtor<'hir> {
2841 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2842 bindings: &'hir [hir::TypeBinding<'hir>],
2843 parenthesized: bool,
2846 impl<'hir> GenericArgsCtor<'hir> {
2847 fn is_empty(&self) -> bool {
2848 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2851 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2853 args: arena.alloc_from_iter(self.args),
2854 bindings: self.bindings,
2855 parenthesized: self.parenthesized,