]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/item.rs
Auto merge of #2680 - RalfJung:rustup, r=RalfJung
[rust.git] / compiler / rustc_ast_lowering / src / item.rs
1 use super::errors::{InvalidAbi, InvalidAbiSuggestion, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
5
6 use rustc_ast::ptr::P;
7 use rustc_ast::visit::AssocCtxt;
8 use rustc_ast::*;
9 use rustc_data_structures::sorted_map::SortedMap;
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
13 use rustc_hir::PredicateOrigin;
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
16 use rustc_span::lev_distance::find_best_match_for_name;
17 use rustc_span::source_map::DesugaringKind;
18 use rustc_span::symbol::{kw, sym, Ident};
19 use rustc_span::{Span, Symbol};
20 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
22 use std::iter;
23 use thin_vec::ThinVec;
24
25 pub(super) struct ItemLowerer<'a, 'hir> {
26     pub(super) tcx: TyCtxt<'hir>,
27     pub(super) resolver: &'a mut ResolverAstLowering,
28     pub(super) ast_arena: &'a Arena<'static>,
29     pub(super) ast_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
30     pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
31 }
32
33 /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
34 /// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
35 /// clause if it exists.
36 fn add_ty_alias_where_clause(
37     generics: &mut ast::Generics,
38     mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
39     prefer_first: bool,
40 ) {
41     if !prefer_first {
42         where_clauses = (where_clauses.1, where_clauses.0);
43     }
44     if where_clauses.0.0 || !where_clauses.1.0 {
45         generics.where_clause.has_where_token = where_clauses.0.0;
46         generics.where_clause.span = where_clauses.0.1;
47     } else {
48         generics.where_clause.has_where_token = where_clauses.1.0;
49         generics.where_clause.span = where_clauses.1.1;
50     }
51 }
52
53 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
54     fn with_lctx(
55         &mut self,
56         owner: NodeId,
57         f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
58     ) {
59         let mut lctx = LoweringContext {
60             // Pseudo-globals.
61             tcx: self.tcx,
62             resolver: self.resolver,
63             arena: self.tcx.hir_arena,
64             ast_arena: self.ast_arena,
65
66             // HirId handling.
67             bodies: Vec::new(),
68             attrs: SortedMap::default(),
69             children: Vec::default(),
70             current_hir_id_owner: hir::CRATE_OWNER_ID,
71             item_local_id_counter: hir::ItemLocalId::new(0),
72             node_id_to_local_id: Default::default(),
73             local_id_to_def_id: SortedMap::new(),
74             trait_map: Default::default(),
75
76             // Lowering state.
77             catch_scope: None,
78             loop_scope: None,
79             is_in_loop_condition: false,
80             is_in_trait_impl: false,
81             is_in_dyn_type: false,
82             generator_kind: None,
83             task_context: None,
84             current_item: None,
85             impl_trait_defs: Vec::new(),
86             impl_trait_bounds: Vec::new(),
87             allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
88             allow_gen_future: Some([sym::gen_future, sym::closure_track_caller][..].into()),
89             allow_into_future: Some([sym::into_future][..].into()),
90             generics_def_id_map: Default::default(),
91         };
92         lctx.with_hir_id_owner(owner, |lctx| f(lctx));
93
94         for (def_id, info) in lctx.children {
95             self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
96             debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
97             self.owners[def_id] = info;
98         }
99     }
100
101     pub(super) fn lower_node(
102         &mut self,
103         def_id: LocalDefId,
104     ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
105         self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
106         if let hir::MaybeOwner::Phantom = self.owners[def_id] {
107             let node = self.ast_index[def_id];
108             match node {
109                 AstOwner::NonOwner => {}
110                 AstOwner::Crate(c) => self.lower_crate(c),
111                 AstOwner::Item(item) => self.lower_item(item),
112                 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
113                 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
114             }
115         }
116
117         self.owners[def_id]
118     }
119
120     #[instrument(level = "debug", skip(self, c))]
121     fn lower_crate(&mut self, c: &Crate) {
122         debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
123         self.with_lctx(CRATE_NODE_ID, |lctx| {
124             let module = lctx.lower_mod(&c.items, &c.spans);
125             lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
126             hir::OwnerNode::Crate(module)
127         })
128     }
129
130     #[instrument(level = "debug", skip(self))]
131     fn lower_item(&mut self, item: &Item) {
132         self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
133     }
134
135     fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
136         let def_id = self.resolver.node_id_to_def_id[&item.id];
137
138         let parent_id = self.tcx.local_parent(def_id);
139         let parent_hir = self.lower_node(parent_id).unwrap();
140         self.with_lctx(item.id, |lctx| {
141             // Evaluate with the lifetimes in `params` in-scope.
142             // This is used to track which lifetimes have already been defined,
143             // and which need to be replicated when lowering an async fn.
144             match parent_hir.node().expect_item().kind {
145                 hir::ItemKind::Impl(hir::Impl { ref of_trait, .. }) => {
146                     lctx.is_in_trait_impl = of_trait.is_some();
147                 }
148                 _ => {}
149             };
150
151             match ctxt {
152                 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
153                 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
154             }
155         })
156     }
157
158     fn lower_foreign_item(&mut self, item: &ForeignItem) {
159         self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
160     }
161 }
162
163 impl<'hir> LoweringContext<'_, 'hir> {
164     pub(super) fn lower_mod(
165         &mut self,
166         items: &[P<Item>],
167         spans: &ModSpans,
168     ) -> &'hir hir::Mod<'hir> {
169         self.arena.alloc(hir::Mod {
170             spans: hir::ModSpans {
171                 inner_span: self.lower_span(spans.inner_span),
172                 inject_use_span: self.lower_span(spans.inject_use_span),
173             },
174             item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
175         })
176     }
177
178     pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
179         let mut node_ids =
180             smallvec![hir::ItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }];
181         if let ItemKind::Use(ref use_tree) = &i.kind {
182             self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
183         }
184         node_ids
185     }
186
187     fn lower_item_id_use_tree(
188         &mut self,
189         tree: &UseTree,
190         base_id: NodeId,
191         vec: &mut SmallVec<[hir::ItemId; 1]>,
192     ) {
193         match tree.kind {
194             UseTreeKind::Nested(ref nested_vec) => {
195                 for &(ref nested, id) in nested_vec {
196                     vec.push(hir::ItemId {
197                         owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
198                     });
199                     self.lower_item_id_use_tree(nested, id, vec);
200                 }
201             }
202             UseTreeKind::Glob => {}
203             UseTreeKind::Simple(_, id1, id2) => {
204                 for (_, &id) in
205                     iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
206                 {
207                     vec.push(hir::ItemId {
208                         owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
209                     });
210                 }
211             }
212         }
213     }
214
215     fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
216         let mut ident = i.ident;
217         let vis_span = self.lower_span(i.vis.span);
218         let hir_id = self.lower_node_id(i.id);
219         let attrs = self.lower_attrs(hir_id, &i.attrs);
220         let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
221         let item = hir::Item {
222             owner_id: hir_id.expect_owner(),
223             ident: self.lower_ident(ident),
224             kind,
225             vis_span,
226             span: self.lower_span(i.span),
227         };
228         self.arena.alloc(item)
229     }
230
231     fn lower_item_kind(
232         &mut self,
233         span: Span,
234         id: NodeId,
235         hir_id: hir::HirId,
236         ident: &mut Ident,
237         attrs: Option<&'hir [Attribute]>,
238         vis_span: Span,
239         i: &ItemKind,
240     ) -> hir::ItemKind<'hir> {
241         match *i {
242             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
243             ItemKind::Use(ref use_tree) => {
244                 // Start with an empty prefix.
245                 let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
246
247                 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
248             }
249             ItemKind::Static(ref t, m, ref e) => {
250                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
251                 hir::ItemKind::Static(ty, m, body_id)
252             }
253             ItemKind::Const(_, ref t, ref e) => {
254                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
255                 hir::ItemKind::Const(ty, body_id)
256             }
257             ItemKind::Fn(box Fn {
258                 sig: FnSig { ref decl, header, span: fn_sig_span },
259                 ref generics,
260                 ref body,
261                 ..
262             }) => {
263                 self.with_new_scopes(|this| {
264                     this.current_item = Some(ident.span);
265
266                     // Note: we don't need to change the return type from `T` to
267                     // `impl Future<Output = T>` here because lower_body
268                     // only cares about the input argument patterns in the function
269                     // declaration (decl), not the return types.
270                     let asyncness = header.asyncness;
271                     let body_id =
272                         this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
273
274                     let mut itctx = ImplTraitContext::Universal;
275                     let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
276                         let ret_id = asyncness.opt_return_id();
277                         this.lower_fn_decl(&decl, Some(id), fn_sig_span, FnDeclKind::Fn, ret_id)
278                     });
279                     let sig = hir::FnSig {
280                         decl,
281                         header: this.lower_fn_header(header),
282                         span: this.lower_span(fn_sig_span),
283                     };
284                     hir::ItemKind::Fn(sig, generics, body_id)
285                 })
286             }
287             ItemKind::Mod(_, ref mod_kind) => match mod_kind {
288                 ModKind::Loaded(items, _, spans) => {
289                     hir::ItemKind::Mod(self.lower_mod(items, spans))
290                 }
291                 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
292             },
293             ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
294                 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
295                 items: self
296                     .arena
297                     .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
298             },
299             ItemKind::GlobalAsm(ref asm) => {
300                 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
301             }
302             ItemKind::TyAlias(box TyAlias {
303                 ref generics,
304                 where_clauses,
305                 ty: Some(ref ty),
306                 ..
307             }) => {
308                 // We lower
309                 //
310                 // type Foo = impl Trait
311                 //
312                 // to
313                 //
314                 // type Foo = Foo1
315                 // opaque type Foo1: Trait
316                 let mut generics = generics.clone();
317                 add_ty_alias_where_clause(&mut generics, where_clauses, true);
318                 let (generics, ty) = self.lower_generics(
319                     &generics,
320                     id,
321                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
322                     |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
323                 );
324                 hir::ItemKind::TyAlias(ty, generics)
325             }
326             ItemKind::TyAlias(box TyAlias {
327                 ref generics, ref where_clauses, ty: None, ..
328             }) => {
329                 let mut generics = generics.clone();
330                 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
331                 let (generics, ty) = self.lower_generics(
332                     &generics,
333                     id,
334                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
335                     |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
336                 );
337                 hir::ItemKind::TyAlias(ty, generics)
338             }
339             ItemKind::Enum(ref enum_definition, ref generics) => {
340                 let (generics, variants) = self.lower_generics(
341                     generics,
342                     id,
343                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
344                     |this| {
345                         this.arena.alloc_from_iter(
346                             enum_definition.variants.iter().map(|x| this.lower_variant(x)),
347                         )
348                     },
349                 );
350                 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
351             }
352             ItemKind::Struct(ref struct_def, ref generics) => {
353                 let (generics, struct_def) = self.lower_generics(
354                     generics,
355                     id,
356                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
357                     |this| this.lower_variant_data(hir_id, struct_def),
358                 );
359                 hir::ItemKind::Struct(struct_def, generics)
360             }
361             ItemKind::Union(ref vdata, ref generics) => {
362                 let (generics, vdata) = self.lower_generics(
363                     generics,
364                     id,
365                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
366                     |this| this.lower_variant_data(hir_id, vdata),
367                 );
368                 hir::ItemKind::Union(vdata, generics)
369             }
370             ItemKind::Impl(box Impl {
371                 unsafety,
372                 polarity,
373                 defaultness,
374                 constness,
375                 generics: ref ast_generics,
376                 of_trait: ref trait_ref,
377                 self_ty: ref ty,
378                 items: ref impl_items,
379             }) => {
380                 // Lower the "impl header" first. This ordering is important
381                 // for in-band lifetimes! Consider `'a` here:
382                 //
383                 //     impl Foo<'a> for u32 {
384                 //         fn method(&'a self) { .. }
385                 //     }
386                 //
387                 // Because we start by lowering the `Foo<'a> for u32`
388                 // part, we will add `'a` to the list of generics on
389                 // the impl. When we then encounter it later in the
390                 // method, it will not be considered an in-band
391                 // lifetime to be added, but rather a reference to a
392                 // parent lifetime.
393                 let mut itctx = ImplTraitContext::Universal;
394                 let (generics, (trait_ref, lowered_ty)) =
395                     self.lower_generics(ast_generics, id, &mut itctx, |this| {
396                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
397                             this.lower_trait_ref(
398                                 trait_ref,
399                                 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
400                             )
401                         });
402
403                         let lowered_ty = this
404                             .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
405
406                         (trait_ref, lowered_ty)
407                     });
408
409                 let new_impl_items = self
410                     .arena
411                     .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
412
413                 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
414                 // to not cause an assertion failure inside the `lower_defaultness` function.
415                 let has_val = true;
416                 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
417                 let polarity = match polarity {
418                     ImplPolarity::Positive => ImplPolarity::Positive,
419                     ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
420                 };
421                 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
422                     unsafety: self.lower_unsafety(unsafety),
423                     polarity,
424                     defaultness,
425                     defaultness_span,
426                     constness: self.lower_constness(constness),
427                     generics,
428                     of_trait: trait_ref,
429                     self_ty: lowered_ty,
430                     items: new_impl_items,
431                 }))
432             }
433             ItemKind::Trait(box Trait {
434                 is_auto,
435                 unsafety,
436                 ref generics,
437                 ref bounds,
438                 ref items,
439             }) => {
440                 let (generics, (unsafety, items, bounds)) = self.lower_generics(
441                     generics,
442                     id,
443                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
444                     |this| {
445                         let bounds = this.lower_param_bounds(
446                             bounds,
447                             &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
448                         );
449                         let items = this.arena.alloc_from_iter(
450                             items.iter().map(|item| this.lower_trait_item_ref(item)),
451                         );
452                         let unsafety = this.lower_unsafety(unsafety);
453                         (unsafety, items, bounds)
454                     },
455                 );
456                 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
457             }
458             ItemKind::TraitAlias(ref generics, ref bounds) => {
459                 let (generics, bounds) = self.lower_generics(
460                     generics,
461                     id,
462                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
463                     |this| {
464                         this.lower_param_bounds(
465                             bounds,
466                             &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
467                         )
468                     },
469                 );
470                 hir::ItemKind::TraitAlias(generics, bounds)
471             }
472             ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
473                 let body = P(self.lower_mac_args(body));
474                 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
475                 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
476             }
477             ItemKind::MacCall(..) => {
478                 panic!("`TyMac` should have been expanded by now")
479             }
480         }
481     }
482
483     fn lower_const_item(
484         &mut self,
485         ty: &Ty,
486         span: Span,
487         body: Option<&Expr>,
488     ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
489         let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
490         (ty, self.lower_const_body(span, body))
491     }
492
493     #[instrument(level = "debug", skip(self))]
494     fn lower_use_tree(
495         &mut self,
496         tree: &UseTree,
497         prefix: &Path,
498         id: NodeId,
499         vis_span: Span,
500         ident: &mut Ident,
501         attrs: Option<&'hir [Attribute]>,
502     ) -> hir::ItemKind<'hir> {
503         let path = &tree.prefix;
504         let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
505
506         match tree.kind {
507             UseTreeKind::Simple(rename, id1, id2) => {
508                 *ident = tree.ident();
509
510                 // First, apply the prefix to the path.
511                 let mut path = Path { segments, span: path.span, tokens: None };
512
513                 // Correctly resolve `self` imports.
514                 if path.segments.len() > 1
515                     && path.segments.last().unwrap().ident.name == kw::SelfLower
516                 {
517                     let _ = path.segments.pop();
518                     if rename.is_none() {
519                         *ident = path.segments.last().unwrap().ident;
520                     }
521                 }
522
523                 let mut resolutions = self.expect_full_res_from_use(id).fuse();
524                 // We want to return *something* from this function, so hold onto the first item
525                 // for later.
526                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
527
528                 // Here, we are looping over namespaces, if they exist for the definition
529                 // being imported. We only handle type and value namespaces because we
530                 // won't be dealing with macros in the rest of the compiler.
531                 // Essentially a single `use` which imports two names is desugared into
532                 // two imports.
533                 for new_node_id in [id1, id2] {
534                     let new_id = self.local_def_id(new_node_id);
535                     let Some(res) = resolutions.next() else {
536                         debug_assert!(self.children.iter().find(|(id, _)| id == &new_id).is_none());
537                         // Associate an HirId to both ids even if there is no resolution.
538                         self.children.push((
539                             new_id,
540                             hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id))),
541                         );
542                         continue;
543                     };
544                     let ident = *ident;
545                     let mut path = path.clone();
546                     for seg in &mut path.segments {
547                         // Give the cloned segment the same resolution information
548                         // as the old one (this is needed for stability checking).
549                         let new_id = self.next_node_id();
550                         self.resolver.clone_res(seg.id, new_id);
551                         seg.id = new_id;
552                     }
553                     let span = path.span;
554
555                     self.with_hir_id_owner(new_node_id, |this| {
556                         let res = this.lower_res(res);
557                         let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
558                         let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
559                         if let Some(attrs) = attrs {
560                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
561                         }
562
563                         let item = hir::Item {
564                             owner_id: hir::OwnerId { def_id: new_id },
565                             ident: this.lower_ident(ident),
566                             kind,
567                             vis_span,
568                             span: this.lower_span(span),
569                         };
570                         hir::OwnerNode::Item(this.arena.alloc(item))
571                     });
572                 }
573
574                 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
575                 hir::ItemKind::Use(path, hir::UseKind::Single)
576             }
577             UseTreeKind::Glob => {
578                 let path = self.lower_path(
579                     id,
580                     &Path { segments, span: path.span, tokens: None },
581                     ParamMode::Explicit,
582                 );
583                 hir::ItemKind::Use(path, hir::UseKind::Glob)
584             }
585             UseTreeKind::Nested(ref trees) => {
586                 // Nested imports are desugared into simple imports.
587                 // So, if we start with
588                 //
589                 // ```
590                 // pub(x) use foo::{a, b};
591                 // ```
592                 //
593                 // we will create three items:
594                 //
595                 // ```
596                 // pub(x) use foo::a;
597                 // pub(x) use foo::b;
598                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
599                 // ```
600                 //
601                 // The first two are produced by recursively invoking
602                 // `lower_use_tree` (and indeed there may be things
603                 // like `use foo::{a::{b, c}}` and so forth).  They
604                 // wind up being directly added to
605                 // `self.items`. However, the structure of this
606                 // function also requires us to return one item, and
607                 // for that we return the `{}` import (called the
608                 // `ListStem`).
609
610                 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
611
612                 // Add all the nested `PathListItem`s to the HIR.
613                 for &(ref use_tree, id) in trees {
614                     let new_hir_id = self.local_def_id(id);
615
616                     let mut prefix = prefix.clone();
617
618                     // Give the segments new node-ids since they are being cloned.
619                     for seg in &mut prefix.segments {
620                         // Give the cloned segment the same resolution information
621                         // as the old one (this is needed for stability checking).
622                         let new_id = self.next_node_id();
623                         self.resolver.clone_res(seg.id, new_id);
624                         seg.id = new_id;
625                     }
626
627                     // Each `use` import is an item and thus are owners of the
628                     // names in the path. Up to this point the nested import is
629                     // the current owner, since we want each desugared import to
630                     // own its own names, we have to adjust the owner before
631                     // lowering the rest of the import.
632                     self.with_hir_id_owner(id, |this| {
633                         let mut ident = *ident;
634
635                         let kind =
636                             this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
637                         if let Some(attrs) = attrs {
638                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
639                         }
640
641                         let item = hir::Item {
642                             owner_id: hir::OwnerId { def_id: new_hir_id },
643                             ident: this.lower_ident(ident),
644                             kind,
645                             vis_span,
646                             span: this.lower_span(use_tree.span),
647                         };
648                         hir::OwnerNode::Item(this.arena.alloc(item))
649                     });
650                 }
651
652                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
653                 let res = self.lower_res(res);
654                 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
655                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
656             }
657         }
658     }
659
660     fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
661         let hir_id = self.lower_node_id(i.id);
662         let owner_id = hir_id.expect_owner();
663         self.lower_attrs(hir_id, &i.attrs);
664         let item = hir::ForeignItem {
665             owner_id,
666             ident: self.lower_ident(i.ident),
667             kind: match i.kind {
668                 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
669                     let fdec = &sig.decl;
670                     let mut itctx = ImplTraitContext::Universal;
671                     let (generics, (fn_dec, fn_args)) =
672                         self.lower_generics(generics, i.id, &mut itctx, |this| {
673                             (
674                                 // Disallow `impl Trait` in foreign items.
675                                 this.lower_fn_decl(
676                                     fdec,
677                                     None,
678                                     sig.span,
679                                     FnDeclKind::ExternFn,
680                                     None,
681                                 ),
682                                 this.lower_fn_params_to_names(fdec),
683                             )
684                         });
685
686                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
687                 }
688                 ForeignItemKind::Static(ref t, m, _) => {
689                     let ty =
690                         self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
691                     hir::ForeignItemKind::Static(ty, m)
692                 }
693                 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
694                 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
695             },
696             vis_span: self.lower_span(i.vis.span),
697             span: self.lower_span(i.span),
698         };
699         self.arena.alloc(item)
700     }
701
702     fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
703         hir::ForeignItemRef {
704             id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
705             ident: self.lower_ident(i.ident),
706             span: self.lower_span(i.span),
707         }
708     }
709
710     fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
711         let hir_id = self.lower_node_id(v.id);
712         self.lower_attrs(hir_id, &v.attrs);
713         hir::Variant {
714             hir_id,
715             def_id: self.local_def_id(v.id),
716             data: self.lower_variant_data(hir_id, &v.data),
717             disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
718             ident: self.lower_ident(v.ident),
719             span: self.lower_span(v.span),
720         }
721     }
722
723     fn lower_variant_data(
724         &mut self,
725         parent_id: hir::HirId,
726         vdata: &VariantData,
727     ) -> hir::VariantData<'hir> {
728         match *vdata {
729             VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
730                 self.arena
731                     .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
732                 recovered,
733             ),
734             VariantData::Tuple(ref fields, id) => {
735                 let ctor_id = self.lower_node_id(id);
736                 self.alias_attrs(ctor_id, parent_id);
737                 hir::VariantData::Tuple(
738                     self.arena.alloc_from_iter(
739                         fields.iter().enumerate().map(|f| self.lower_field_def(f)),
740                     ),
741                     ctor_id,
742                     self.local_def_id(id),
743                 )
744             }
745             VariantData::Unit(id) => {
746                 let ctor_id = self.lower_node_id(id);
747                 self.alias_attrs(ctor_id, parent_id);
748                 hir::VariantData::Unit(ctor_id, self.local_def_id(id))
749             }
750         }
751     }
752
753     fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
754         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
755             let t = self.lower_path_ty(
756                 &f.ty,
757                 qself,
758                 path,
759                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
760                 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
761             );
762             self.arena.alloc(t)
763         } else {
764             self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
765         };
766         let hir_id = self.lower_node_id(f.id);
767         self.lower_attrs(hir_id, &f.attrs);
768         hir::FieldDef {
769             span: self.lower_span(f.span),
770             hir_id,
771             def_id: self.local_def_id(f.id),
772             ident: match f.ident {
773                 Some(ident) => self.lower_ident(ident),
774                 // FIXME(jseyfried): positional field hygiene.
775                 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
776             },
777             vis_span: self.lower_span(f.vis.span),
778             ty,
779         }
780     }
781
782     fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
783         let hir_id = self.lower_node_id(i.id);
784         let trait_item_def_id = hir_id.expect_owner();
785
786         let (generics, kind, has_default) = match i.kind {
787             AssocItemKind::Const(_, ref ty, ref default) => {
788                 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
789                 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
790                 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
791             }
792             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
793                 let asyncness = sig.header.asyncness;
794                 let names = self.lower_fn_params_to_names(&sig.decl);
795                 let (generics, sig) = self.lower_method_sig(
796                     generics,
797                     sig,
798                     i.id,
799                     FnDeclKind::Trait,
800                     asyncness.opt_return_id(),
801                 );
802                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
803             }
804             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
805                 let asyncness = sig.header.asyncness;
806                 let body_id =
807                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
808                 let (generics, sig) = self.lower_method_sig(
809                     generics,
810                     sig,
811                     i.id,
812                     FnDeclKind::Trait,
813                     asyncness.opt_return_id(),
814                 );
815                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
816             }
817             AssocItemKind::Type(box TyAlias {
818                 ref generics,
819                 where_clauses,
820                 ref bounds,
821                 ref ty,
822                 ..
823             }) => {
824                 let mut generics = generics.clone();
825                 add_ty_alias_where_clause(&mut generics, where_clauses, false);
826                 let (generics, kind) = self.lower_generics(
827                     &generics,
828                     i.id,
829                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
830                     |this| {
831                         let ty = ty.as_ref().map(|x| {
832                             this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
833                         });
834                         hir::TraitItemKind::Type(
835                             this.lower_param_bounds(
836                                 bounds,
837                                 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
838                             ),
839                             ty,
840                         )
841                     },
842                 );
843                 (generics, kind, ty.is_some())
844             }
845             AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
846         };
847
848         self.lower_attrs(hir_id, &i.attrs);
849         let item = hir::TraitItem {
850             owner_id: trait_item_def_id,
851             ident: self.lower_ident(i.ident),
852             generics,
853             kind,
854             span: self.lower_span(i.span),
855             defaultness: hir::Defaultness::Default { has_value: has_default },
856         };
857         self.arena.alloc(item)
858     }
859
860     fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
861         let kind = match &i.kind {
862             AssocItemKind::Const(..) => hir::AssocItemKind::Const,
863             AssocItemKind::Type(..) => hir::AssocItemKind::Type,
864             AssocItemKind::Fn(box Fn { sig, .. }) => {
865                 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
866             }
867             AssocItemKind::MacCall(..) => unimplemented!(),
868         };
869         let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
870         hir::TraitItemRef {
871             id,
872             ident: self.lower_ident(i.ident),
873             span: self.lower_span(i.span),
874             kind,
875         }
876     }
877
878     /// Construct `ExprKind::Err` for the given `span`.
879     pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
880         self.expr(span, hir::ExprKind::Err, AttrVec::new())
881     }
882
883     fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
884         // Since `default impl` is not yet implemented, this is always true in impls.
885         let has_value = true;
886         let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
887
888         let (generics, kind) = match &i.kind {
889             AssocItemKind::Const(_, ty, expr) => {
890                 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
891                 (
892                     hir::Generics::empty(),
893                     hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
894                 )
895             }
896             AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
897                 self.current_item = Some(i.span);
898                 let asyncness = sig.header.asyncness;
899                 let body_id =
900                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
901                 let (generics, sig) = self.lower_method_sig(
902                     generics,
903                     sig,
904                     i.id,
905                     if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
906                     asyncness.opt_return_id(),
907                 );
908
909                 (generics, hir::ImplItemKind::Fn(sig, body_id))
910             }
911             AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
912                 let mut generics = generics.clone();
913                 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
914                 self.lower_generics(
915                     &generics,
916                     i.id,
917                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
918                     |this| match ty {
919                         None => {
920                             let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
921                             hir::ImplItemKind::Type(ty)
922                         }
923                         Some(ty) => {
924                             let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
925                             hir::ImplItemKind::Type(ty)
926                         }
927                     },
928                 )
929             }
930             AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
931         };
932
933         let hir_id = self.lower_node_id(i.id);
934         self.lower_attrs(hir_id, &i.attrs);
935         let item = hir::ImplItem {
936             owner_id: hir_id.expect_owner(),
937             ident: self.lower_ident(i.ident),
938             generics,
939             kind,
940             vis_span: self.lower_span(i.vis.span),
941             span: self.lower_span(i.span),
942             defaultness,
943         };
944         self.arena.alloc(item)
945     }
946
947     fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
948         hir::ImplItemRef {
949             id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
950             ident: self.lower_ident(i.ident),
951             span: self.lower_span(i.span),
952             kind: match &i.kind {
953                 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
954                 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
955                 AssocItemKind::Fn(box Fn { sig, .. }) => {
956                     hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
957                 }
958                 AssocItemKind::MacCall(..) => unimplemented!(),
959             },
960             trait_item_def_id: self
961                 .resolver
962                 .get_partial_res(i.id)
963                 .map(|r| r.expect_full_res().def_id()),
964         }
965     }
966
967     fn lower_defaultness(
968         &self,
969         d: Defaultness,
970         has_value: bool,
971     ) -> (hir::Defaultness, Option<Span>) {
972         match d {
973             Defaultness::Default(sp) => {
974                 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
975             }
976             Defaultness::Final => {
977                 assert!(has_value);
978                 (hir::Defaultness::Final, None)
979             }
980         }
981     }
982
983     fn record_body(
984         &mut self,
985         params: &'hir [hir::Param<'hir>],
986         value: hir::Expr<'hir>,
987     ) -> hir::BodyId {
988         let body = hir::Body {
989             generator_kind: self.generator_kind,
990             params,
991             value: self.arena.alloc(value),
992         };
993         let id = body.id();
994         debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
995         self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
996         id
997     }
998
999     pub(super) fn lower_body(
1000         &mut self,
1001         f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1002     ) -> hir::BodyId {
1003         let prev_gen_kind = self.generator_kind.take();
1004         let task_context = self.task_context.take();
1005         let (parameters, result) = f(self);
1006         let body_id = self.record_body(parameters, result);
1007         self.task_context = task_context;
1008         self.generator_kind = prev_gen_kind;
1009         body_id
1010     }
1011
1012     fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1013         let hir_id = self.lower_node_id(param.id);
1014         self.lower_attrs(hir_id, &param.attrs);
1015         hir::Param {
1016             hir_id,
1017             pat: self.lower_pat(&param.pat),
1018             ty_span: self.lower_span(param.ty.span),
1019             span: self.lower_span(param.span),
1020         }
1021     }
1022
1023     pub(super) fn lower_fn_body(
1024         &mut self,
1025         decl: &FnDecl,
1026         body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1027     ) -> hir::BodyId {
1028         self.lower_body(|this| {
1029             (
1030                 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1031                 body(this),
1032             )
1033         })
1034     }
1035
1036     fn lower_fn_body_block(
1037         &mut self,
1038         span: Span,
1039         decl: &FnDecl,
1040         body: Option<&Block>,
1041     ) -> hir::BodyId {
1042         self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1043     }
1044
1045     fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1046         match block {
1047             Some(block) => self.lower_block_expr(block),
1048             None => self.expr_err(span),
1049         }
1050     }
1051
1052     pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1053         self.lower_body(|this| {
1054             (
1055                 &[],
1056                 match expr {
1057                     Some(expr) => this.lower_expr_mut(expr),
1058                     None => this.expr_err(span),
1059                 },
1060             )
1061         })
1062     }
1063
1064     fn lower_maybe_async_body(
1065         &mut self,
1066         span: Span,
1067         decl: &FnDecl,
1068         asyncness: Async,
1069         body: Option<&Block>,
1070     ) -> hir::BodyId {
1071         let (closure_id, body) = match (asyncness, body) {
1072             (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
1073             _ => return self.lower_fn_body_block(span, decl, body),
1074         };
1075
1076         self.lower_body(|this| {
1077             let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1078             let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1079
1080             // Async function parameters are lowered into the closure body so that they are
1081             // captured and so that the drop order matches the equivalent non-async functions.
1082             //
1083             // from:
1084             //
1085             //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1086             //         <body>
1087             //     }
1088             //
1089             // into:
1090             //
1091             //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1092             //       async move {
1093             //         let __arg2 = __arg2;
1094             //         let <pattern> = __arg2;
1095             //         let __arg1 = __arg1;
1096             //         let <pattern> = __arg1;
1097             //         let __arg0 = __arg0;
1098             //         let <pattern> = __arg0;
1099             //         drop-temps { <body> } // see comments later in fn for details
1100             //       }
1101             //     }
1102             //
1103             // If `<pattern>` is a simple ident, then it is lowered to a single
1104             // `let <pattern> = <pattern>;` statement as an optimization.
1105             //
1106             // Note that the body is embedded in `drop-temps`; an
1107             // equivalent desugaring would be `return { <body>
1108             // };`. The key point is that we wish to drop all the
1109             // let-bound variables and temporaries created in the body
1110             // (and its tail expression!) before we drop the
1111             // parameters (c.f. rust-lang/rust#64512).
1112             for (index, parameter) in decl.inputs.iter().enumerate() {
1113                 let parameter = this.lower_param(parameter);
1114                 let span = parameter.pat.span;
1115
1116                 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1117                 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1118                 let (ident, is_simple_parameter) = match parameter.pat.kind {
1119                     hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1120                         (ident, true)
1121                     }
1122                     // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1123                     // we can keep the same name for the parameter.
1124                     // This lets rustdoc render it correctly in documentation.
1125                     hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1126                     hir::PatKind::Wild => {
1127                         (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1128                     }
1129                     _ => {
1130                         // Replace the ident for bindings that aren't simple.
1131                         let name = format!("__arg{}", index);
1132                         let ident = Ident::from_str(&name);
1133
1134                         (ident, false)
1135                     }
1136                 };
1137
1138                 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1139
1140                 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1141                 // async function.
1142                 //
1143                 // If this is the simple case, this parameter will end up being the same as the
1144                 // original parameter, but with a different pattern id.
1145                 let stmt_attrs = this.attrs.get(&parameter.hir_id.local_id).copied();
1146                 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1147                 let new_parameter = hir::Param {
1148                     hir_id: parameter.hir_id,
1149                     pat: new_parameter_pat,
1150                     ty_span: this.lower_span(parameter.ty_span),
1151                     span: this.lower_span(parameter.span),
1152                 };
1153
1154                 if is_simple_parameter {
1155                     // If this is the simple case, then we only insert one statement that is
1156                     // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1157                     // `HirId`s are densely assigned.
1158                     let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1159                     let stmt = this.stmt_let_pat(
1160                         stmt_attrs,
1161                         desugared_span,
1162                         Some(expr),
1163                         parameter.pat,
1164                         hir::LocalSource::AsyncFn,
1165                     );
1166                     statements.push(stmt);
1167                 } else {
1168                     // If this is not the simple case, then we construct two statements:
1169                     //
1170                     // ```
1171                     // let __argN = __argN;
1172                     // let <pat> = __argN;
1173                     // ```
1174                     //
1175                     // The first statement moves the parameter into the closure and thus ensures
1176                     // that the drop order is correct.
1177                     //
1178                     // The second statement creates the bindings that the user wrote.
1179
1180                     // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1181                     // because the user may have specified a `ref mut` binding in the next
1182                     // statement.
1183                     let (move_pat, move_id) = this.pat_ident_binding_mode(
1184                         desugared_span,
1185                         ident,
1186                         hir::BindingAnnotation::MUT,
1187                     );
1188                     let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1189                     let move_stmt = this.stmt_let_pat(
1190                         None,
1191                         desugared_span,
1192                         Some(move_expr),
1193                         move_pat,
1194                         hir::LocalSource::AsyncFn,
1195                     );
1196
1197                     // Construct the `let <pat> = __argN;` statement. We re-use the original
1198                     // parameter's pattern so that `HirId`s are densely assigned.
1199                     let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1200                     let pattern_stmt = this.stmt_let_pat(
1201                         stmt_attrs,
1202                         desugared_span,
1203                         Some(pattern_expr),
1204                         parameter.pat,
1205                         hir::LocalSource::AsyncFn,
1206                     );
1207
1208                     statements.push(move_stmt);
1209                     statements.push(pattern_stmt);
1210                 };
1211
1212                 parameters.push(new_parameter);
1213             }
1214
1215             let async_expr = this.make_async_expr(
1216                 CaptureBy::Value,
1217                 closure_id,
1218                 None,
1219                 body.span,
1220                 hir::AsyncGeneratorKind::Fn,
1221                 |this| {
1222                     // Create a block from the user's function body:
1223                     let user_body = this.lower_block_expr(body);
1224
1225                     // Transform into `drop-temps { <user-body> }`, an expression:
1226                     let desugared_span =
1227                         this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1228                     let user_body = this.expr_drop_temps(
1229                         desugared_span,
1230                         this.arena.alloc(user_body),
1231                         AttrVec::new(),
1232                     );
1233
1234                     // As noted above, create the final block like
1235                     //
1236                     // ```
1237                     // {
1238                     //   let $param_pattern = $raw_param;
1239                     //   ...
1240                     //   drop-temps { <user-body> }
1241                     // }
1242                     // ```
1243                     let body = this.block_all(
1244                         desugared_span,
1245                         this.arena.alloc_from_iter(statements),
1246                         Some(user_body),
1247                     );
1248
1249                     this.expr_block(body, AttrVec::new())
1250                 },
1251             );
1252
1253             (
1254                 this.arena.alloc_from_iter(parameters),
1255                 this.expr(body.span, async_expr, AttrVec::new()),
1256             )
1257         })
1258     }
1259
1260     fn lower_method_sig(
1261         &mut self,
1262         generics: &Generics,
1263         sig: &FnSig,
1264         id: NodeId,
1265         kind: FnDeclKind,
1266         is_async: Option<(NodeId, Span)>,
1267     ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1268         let header = self.lower_fn_header(sig.header);
1269         let mut itctx = ImplTraitContext::Universal;
1270         let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1271             this.lower_fn_decl(&sig.decl, Some(id), sig.span, kind, is_async)
1272         });
1273         (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1274     }
1275
1276     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1277         hir::FnHeader {
1278             unsafety: self.lower_unsafety(h.unsafety),
1279             asyncness: self.lower_asyncness(h.asyncness),
1280             constness: self.lower_constness(h.constness),
1281             abi: self.lower_extern(h.ext),
1282         }
1283     }
1284
1285     pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1286         abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1287             self.error_on_invalid_abi(abi);
1288             abi::Abi::Rust
1289         })
1290     }
1291
1292     pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1293         match ext {
1294             Extern::None => abi::Abi::Rust,
1295             Extern::Implicit(_) => abi::Abi::FALLBACK,
1296             Extern::Explicit(abi, _) => self.lower_abi(abi),
1297         }
1298     }
1299
1300     fn error_on_invalid_abi(&self, abi: StrLit) {
1301         let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1302             .iter()
1303             .map(|s| Symbol::intern(s))
1304             .collect::<Vec<_>>();
1305         let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1306         self.tcx.sess.emit_err(InvalidAbi {
1307             abi: abi.symbol_unescaped,
1308             span: abi.span,
1309             suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1310                 span: abi.span,
1311                 suggestion: format!("\"{suggested_name}\""),
1312             }),
1313             command: "rustc --print=calling-conventions".to_string(),
1314         });
1315     }
1316
1317     fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1318         match a {
1319             Async::Yes { .. } => hir::IsAsync::Async,
1320             Async::No => hir::IsAsync::NotAsync,
1321         }
1322     }
1323
1324     fn lower_constness(&mut self, c: Const) -> hir::Constness {
1325         match c {
1326             Const::Yes(_) => hir::Constness::Const,
1327             Const::No => hir::Constness::NotConst,
1328         }
1329     }
1330
1331     pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1332         match u {
1333             Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1334             Unsafe::No => hir::Unsafety::Normal,
1335         }
1336     }
1337
1338     /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1339     /// the carried impl trait definitions and bounds.
1340     #[instrument(level = "debug", skip(self, f))]
1341     fn lower_generics<T>(
1342         &mut self,
1343         generics: &Generics,
1344         parent_node_id: NodeId,
1345         itctx: &ImplTraitContext,
1346         f: impl FnOnce(&mut Self) -> T,
1347     ) -> (&'hir hir::Generics<'hir>, T) {
1348         debug_assert!(self.impl_trait_defs.is_empty());
1349         debug_assert!(self.impl_trait_bounds.is_empty());
1350
1351         // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1352         // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1353         // these into hir when we lower thee where clauses), but this makes it quite difficult to
1354         // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1355         // where clauses for `?Sized`.
1356         for pred in &generics.where_clause.predicates {
1357             let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1358                 continue;
1359             };
1360             let compute_is_param = || {
1361                 // Check if the where clause type is a plain type parameter.
1362                 match self
1363                     .resolver
1364                     .get_partial_res(bound_pred.bounded_ty.id)
1365                     .and_then(|r| r.full_res())
1366                 {
1367                     Some(Res::Def(DefKind::TyParam, def_id))
1368                         if bound_pred.bound_generic_params.is_empty() =>
1369                     {
1370                         generics
1371                             .params
1372                             .iter()
1373                             .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1374                     }
1375                     // Either the `bounded_ty` is not a plain type parameter, or
1376                     // it's not found in the generic type parameters list.
1377                     _ => false,
1378                 }
1379             };
1380             // We only need to compute this once per `WherePredicate`, but don't
1381             // need to compute this at all unless there is a Maybe bound.
1382             let mut is_param: Option<bool> = None;
1383             for bound in &bound_pred.bounds {
1384                 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1385                     continue;
1386                 }
1387                 let is_param = *is_param.get_or_insert_with(compute_is_param);
1388                 if !is_param {
1389                     self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1390                 }
1391             }
1392         }
1393
1394         let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1395         predicates.extend(generics.params.iter().filter_map(|param| {
1396             self.lower_generic_bound_predicate(
1397                 param.ident,
1398                 param.id,
1399                 &param.kind,
1400                 &param.bounds,
1401                 itctx,
1402                 PredicateOrigin::GenericParam,
1403             )
1404         }));
1405         predicates.extend(
1406             generics
1407                 .where_clause
1408                 .predicates
1409                 .iter()
1410                 .map(|predicate| self.lower_where_predicate(predicate)),
1411         );
1412
1413         let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1414             self.lower_generic_params_mut(&generics.params).collect();
1415
1416         // Introduce extra lifetimes if late resolution tells us to.
1417         let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1418         params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1419             self.lifetime_res_to_generic_param(ident, node_id, res)
1420         }));
1421
1422         let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1423         let where_clause_span = self.lower_span(generics.where_clause.span);
1424         let span = self.lower_span(generics.span);
1425         let res = f(self);
1426
1427         let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1428         params.extend(impl_trait_defs.into_iter());
1429
1430         let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1431         predicates.extend(impl_trait_bounds.into_iter());
1432
1433         let lowered_generics = self.arena.alloc(hir::Generics {
1434             params: self.arena.alloc_from_iter(params),
1435             predicates: self.arena.alloc_from_iter(predicates),
1436             has_where_clause_predicates,
1437             where_clause_span,
1438             span,
1439         });
1440
1441         (lowered_generics, res)
1442     }
1443
1444     pub(super) fn lower_generic_bound_predicate(
1445         &mut self,
1446         ident: Ident,
1447         id: NodeId,
1448         kind: &GenericParamKind,
1449         bounds: &[GenericBound],
1450         itctx: &ImplTraitContext,
1451         origin: PredicateOrigin,
1452     ) -> Option<hir::WherePredicate<'hir>> {
1453         // Do not create a clause if we do not have anything inside it.
1454         if bounds.is_empty() {
1455             return None;
1456         }
1457
1458         let bounds = self.lower_param_bounds(bounds, itctx);
1459
1460         let ident = self.lower_ident(ident);
1461         let param_span = ident.span;
1462         let span = bounds
1463             .iter()
1464             .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1465                 let bound_span = bound.span();
1466                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1467                 // as we use this method to get a span appropriate for suggestions.
1468                 if !bound_span.can_be_used_for_suggestions() {
1469                     None
1470                 } else if let Some(span) = span {
1471                     Some(span.to(bound_span))
1472                 } else {
1473                     Some(bound_span)
1474                 }
1475             })
1476             .unwrap_or(param_span.shrink_to_hi());
1477         match kind {
1478             GenericParamKind::Const { .. } => None,
1479             GenericParamKind::Type { .. } => {
1480                 let def_id = self.local_def_id(id).to_def_id();
1481                 let hir_id = self.next_id();
1482                 let res = Res::Def(DefKind::TyParam, def_id);
1483                 let ty_path = self.arena.alloc(hir::Path {
1484                     span: param_span,
1485                     res,
1486                     segments: self
1487                         .arena
1488                         .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1489                 });
1490                 let ty_id = self.next_id();
1491                 let bounded_ty =
1492                     self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1493                 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1494                     hir_id: self.next_id(),
1495                     bounded_ty: self.arena.alloc(bounded_ty),
1496                     bounds,
1497                     span,
1498                     bound_generic_params: &[],
1499                     origin,
1500                 }))
1501             }
1502             GenericParamKind::Lifetime => {
1503                 let ident_span = self.lower_span(ident.span);
1504                 let ident = self.lower_ident(ident);
1505                 let lt_id = self.next_node_id();
1506                 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1507                 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1508                     lifetime,
1509                     span,
1510                     bounds,
1511                     in_where_clause: false,
1512                 }))
1513             }
1514         }
1515     }
1516
1517     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1518         match *pred {
1519             WherePredicate::BoundPredicate(WhereBoundPredicate {
1520                 ref bound_generic_params,
1521                 ref bounded_ty,
1522                 ref bounds,
1523                 span,
1524             }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1525                 hir_id: self.next_id(),
1526                 bound_generic_params: self.lower_generic_params(bound_generic_params),
1527                 bounded_ty: self
1528                     .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1529                 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1530                     self.lower_param_bound(
1531                         bound,
1532                         &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1533                     )
1534                 })),
1535                 span: self.lower_span(span),
1536                 origin: PredicateOrigin::WhereClause,
1537             }),
1538             WherePredicate::RegionPredicate(WhereRegionPredicate {
1539                 ref lifetime,
1540                 ref bounds,
1541                 span,
1542             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1543                 span: self.lower_span(span),
1544                 lifetime: self.lower_lifetime(lifetime),
1545                 bounds: self.lower_param_bounds(
1546                     bounds,
1547                     &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1548                 ),
1549                 in_where_clause: true,
1550             }),
1551             WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1552                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1553                     lhs_ty: self
1554                         .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1555                     rhs_ty: self
1556                         .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1557                     span: self.lower_span(span),
1558                 })
1559             }
1560         }
1561     }
1562 }