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