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