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