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