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