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