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