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