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