]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_lowering/item.rs
Rollup merge of #68143 - skinny121:const-param-type-elided-lifetime, r=petrochenkov
[rust.git] / src / librustc_ast_lowering / item.rs
1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition, ImplTraitTypeIdVisitor};
3
4 use rustc::arena::Arena;
5 use rustc::bug;
6 use rustc_error_codes::*;
7 use rustc_errors::struct_span_err;
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_session::node_id::NodeMap;
12 use rustc_span::source_map::{respan, DesugaringKind};
13 use rustc_span::symbol::{kw, sym};
14 use rustc_span::Span;
15 use rustc_target::spec::abi;
16 use syntax::ast::*;
17 use syntax::attr;
18 use syntax::visit::{self, Visitor};
19
20 use log::debug;
21 use smallvec::{smallvec, SmallVec};
22 use std::collections::BTreeSet;
23
24 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
25     pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
26 }
27
28 impl ItemLowerer<'_, '_, '_> {
29     fn with_trait_impl_ref(&mut self, impl_ref: &Option<TraitRef>, f: impl FnOnce(&mut Self)) {
30         let old = self.lctx.is_in_trait_impl;
31         self.lctx.is_in_trait_impl = if let &None = impl_ref { false } else { true };
32         f(self);
33         self.lctx.is_in_trait_impl = old;
34     }
35 }
36
37 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
38     fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
39         let hir_id = self.lctx.lower_node_id(n);
40
41         self.lctx.modules.insert(
42             hir_id,
43             hir::ModuleItems {
44                 items: BTreeSet::new(),
45                 trait_items: BTreeSet::new(),
46                 impl_items: BTreeSet::new(),
47             },
48         );
49
50         let old = self.lctx.current_module;
51         self.lctx.current_module = hir_id;
52         visit::walk_mod(self, m);
53         self.lctx.current_module = old;
54     }
55
56     fn visit_item(&mut self, item: &'a Item) {
57         let mut item_hir_id = None;
58         self.lctx.with_hir_id_owner(item.id, |lctx| {
59             lctx.without_in_scope_lifetime_defs(|lctx| {
60                 if let Some(hir_item) = lctx.lower_item(item) {
61                     item_hir_id = Some(hir_item.hir_id);
62                     lctx.insert_item(hir_item);
63                 }
64             })
65         });
66
67         if let Some(hir_id) = item_hir_id {
68             self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
69                 let this = &mut ItemLowerer { lctx: this };
70                 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.kind {
71                     if opt_trait_ref.as_ref().map(|tr| tr.constness.is_some()).unwrap_or(false) {
72                         this.lctx
73                             .diagnostic()
74                             .span_err(item.span, "const trait impls are not yet implemented");
75                     }
76
77                     this.with_trait_impl_ref(opt_trait_ref, |this| visit::walk_item(this, item));
78                 } else {
79                     visit::walk_item(this, item);
80                 }
81             });
82         }
83     }
84
85     fn visit_trait_item(&mut self, item: &'a AssocItem) {
86         self.lctx.with_hir_id_owner(item.id, |lctx| {
87             let hir_item = lctx.lower_trait_item(item);
88             let id = hir::TraitItemId { hir_id: hir_item.hir_id };
89             lctx.trait_items.insert(id, hir_item);
90             lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
91         });
92
93         visit::walk_trait_item(self, item);
94     }
95
96     fn visit_impl_item(&mut self, item: &'a AssocItem) {
97         self.lctx.with_hir_id_owner(item.id, |lctx| {
98             let hir_item = lctx.lower_impl_item(item);
99             let id = hir::ImplItemId { hir_id: hir_item.hir_id };
100             lctx.impl_items.insert(id, hir_item);
101             lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
102         });
103         visit::walk_impl_item(self, item);
104     }
105 }
106
107 impl<'hir> LoweringContext<'_, 'hir> {
108     // Same as the method above, but accepts `hir::GenericParam`s
109     // instead of `ast::GenericParam`s.
110     // This should only be used with generics that have already had their
111     // in-band lifetimes added. In practice, this means that this function is
112     // only used when lowering a child item of a trait or impl.
113     fn with_parent_item_lifetime_defs<T>(
114         &mut self,
115         parent_hir_id: hir::HirId,
116         f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
117     ) -> T {
118         let old_len = self.in_scope_lifetimes.len();
119
120         let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
121             hir::ItemKind::Impl(_, _, _, ref generics, ..)
122             | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..],
123             _ => &[],
124         };
125         let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
126             hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
127             _ => None,
128         });
129         self.in_scope_lifetimes.extend(lt_def_names);
130
131         let res = f(self);
132
133         self.in_scope_lifetimes.truncate(old_len);
134         res
135     }
136
137     // Clears (and restores) the `in_scope_lifetimes` field. Used when
138     // visiting nested items, which never inherit in-scope lifetimes
139     // from their surrounding environment.
140     fn without_in_scope_lifetime_defs<T>(
141         &mut self,
142         f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
143     ) -> T {
144         let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
145
146         // this vector is only used when walking over impl headers,
147         // input types, and the like, and should not be non-empty in
148         // between items
149         assert!(self.lifetimes_to_define.is_empty());
150
151         let res = f(self);
152
153         assert!(self.in_scope_lifetimes.is_empty());
154         self.in_scope_lifetimes = old_in_scope_lifetimes;
155
156         res
157     }
158
159     pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
160         hir::Mod {
161             inner: m.inner,
162             item_ids: self
163                 .arena
164                 .alloc_from_iter(m.items.iter().flat_map(|x| self.lower_item_id(x))),
165         }
166     }
167
168     pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
169         let node_ids = match i.kind {
170             ItemKind::Use(ref use_tree) => {
171                 let mut vec = smallvec![i.id];
172                 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
173                 vec
174             }
175             ItemKind::MacroDef(..) => SmallVec::new(),
176             ItemKind::Fn(..) | ItemKind::Impl(.., None, _, _) => smallvec![i.id],
177             ItemKind::Static(ref ty, ..) => {
178                 let mut ids = smallvec![i.id];
179                 if self.sess.features_untracked().impl_trait_in_bindings {
180                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
181                     visitor.visit_ty(ty);
182                 }
183                 ids
184             }
185             ItemKind::Const(ref ty, ..) => {
186                 let mut ids = smallvec![i.id];
187                 if self.sess.features_untracked().impl_trait_in_bindings {
188                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
189                     visitor.visit_ty(ty);
190                 }
191                 ids
192             }
193             _ => smallvec![i.id],
194         };
195
196         node_ids
197             .into_iter()
198             .map(|node_id| hir::ItemId { id: self.allocate_hir_id_counter(node_id) })
199             .collect()
200     }
201
202     fn lower_item_id_use_tree(
203         &mut self,
204         tree: &UseTree,
205         base_id: NodeId,
206         vec: &mut SmallVec<[NodeId; 1]>,
207     ) {
208         match tree.kind {
209             UseTreeKind::Nested(ref nested_vec) => {
210                 for &(ref nested, id) in nested_vec {
211                     vec.push(id);
212                     self.lower_item_id_use_tree(nested, id, vec);
213                 }
214             }
215             UseTreeKind::Glob => {}
216             UseTreeKind::Simple(_, id1, id2) => {
217                 for (_, &id) in
218                     self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter())
219                 {
220                     vec.push(id);
221                 }
222             }
223         }
224     }
225
226     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
227         let mut ident = i.ident;
228         let mut vis = self.lower_visibility(&i.vis, None);
229         let attrs = self.lower_attrs(&i.attrs);
230
231         if let ItemKind::MacroDef(ref def) = i.kind {
232             if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
233                 let body = self.lower_token_stream(def.body.inner_tokens());
234                 let hir_id = self.lower_node_id(i.id);
235                 self.exported_macros.push(hir::MacroDef {
236                     name: ident.name,
237                     vis,
238                     attrs,
239                     hir_id,
240                     span: i.span,
241                     body,
242                     legacy: def.legacy,
243                 });
244             } else {
245                 self.non_exported_macro_attrs.extend(attrs.iter().cloned());
246             }
247             return None;
248         }
249
250         let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind);
251
252         Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span })
253     }
254
255     fn lower_item_kind(
256         &mut self,
257         span: Span,
258         id: NodeId,
259         ident: &mut Ident,
260         attrs: &'hir [Attribute],
261         vis: &mut hir::Visibility<'hir>,
262         i: &ItemKind,
263     ) -> hir::ItemKind<'hir> {
264         match *i {
265             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
266             ItemKind::Use(ref use_tree) => {
267                 // Start with an empty prefix.
268                 let prefix = Path { segments: vec![], span: use_tree.span };
269
270                 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
271             }
272             ItemKind::Static(ref t, m, ref e) => {
273                 let ty = self.lower_ty(
274                     t,
275                     if self.sess.features_untracked().impl_trait_in_bindings {
276                         ImplTraitContext::OpaqueTy(None)
277                     } else {
278                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
279                     },
280                 );
281                 hir::ItemKind::Static(ty, m, self.lower_const_body(span, Some(e)))
282             }
283             ItemKind::Const(ref t, ref e) => {
284                 let ty = self.lower_ty(
285                     t,
286                     if self.sess.features_untracked().impl_trait_in_bindings {
287                         ImplTraitContext::OpaqueTy(None)
288                     } else {
289                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
290                     },
291                 );
292                 hir::ItemKind::Const(ty, self.lower_const_body(span, Some(e)))
293             }
294             ItemKind::Fn(FnSig { ref decl, header }, ref generics, ref body) => {
295                 let fn_def_id = self.resolver.definitions().local_def_id(id);
296                 self.with_new_scopes(|this| {
297                     this.current_item = Some(ident.span);
298
299                     // Note: we don't need to change the return type from `T` to
300                     // `impl Future<Output = T>` here because lower_body
301                     // only cares about the input argument patterns in the function
302                     // declaration (decl), not the return types.
303                     let body_id =
304                         this.lower_maybe_async_body(span, &decl, header.asyncness.node, Some(body));
305
306                     let (generics, decl) = this.add_in_band_defs(
307                         generics,
308                         fn_def_id,
309                         AnonymousLifetimeMode::PassThrough,
310                         |this, idty| {
311                             this.lower_fn_decl(
312                                 &decl,
313                                 Some((fn_def_id, idty)),
314                                 true,
315                                 header.asyncness.node.opt_return_id(),
316                             )
317                         },
318                     );
319                     let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
320                     hir::ItemKind::Fn(sig, generics, body_id)
321                 })
322             }
323             ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
324             ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
325             ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
326             ItemKind::TyAlias(ref ty, ref generics) => match ty.kind.opaque_top_hack() {
327                 None => {
328                     let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
329                     let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
330                     hir::ItemKind::TyAlias(ty, generics)
331                 }
332                 Some(bounds) => {
333                     let ty = hir::OpaqueTy {
334                         generics: self.lower_generics(generics, ImplTraitContext::OpaqueTy(None)),
335                         bounds: self.lower_param_bounds(bounds, ImplTraitContext::OpaqueTy(None)),
336                         impl_trait_fn: None,
337                         origin: hir::OpaqueTyOrigin::TypeAlias,
338                     };
339                     hir::ItemKind::OpaqueTy(ty)
340                 }
341             },
342             ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
343                 hir::EnumDef {
344                     variants: self.arena.alloc_from_iter(
345                         enum_definition.variants.iter().map(|x| self.lower_variant(x)),
346                     ),
347                 },
348                 self.lower_generics(generics, ImplTraitContext::disallowed()),
349             ),
350             ItemKind::Struct(ref struct_def, ref generics) => {
351                 let struct_def = self.lower_variant_data(struct_def);
352                 hir::ItemKind::Struct(
353                     struct_def,
354                     self.lower_generics(generics, ImplTraitContext::disallowed()),
355                 )
356             }
357             ItemKind::Union(ref vdata, ref generics) => {
358                 let vdata = self.lower_variant_data(vdata);
359                 hir::ItemKind::Union(
360                     vdata,
361                     self.lower_generics(generics, ImplTraitContext::disallowed()),
362                 )
363             }
364             ItemKind::Impl(
365                 unsafety,
366                 polarity,
367                 defaultness,
368                 ref ast_generics,
369                 ref trait_ref,
370                 ref ty,
371                 ref impl_items,
372             ) => {
373                 let def_id = self.resolver.definitions().local_def_id(id);
374
375                 // Lower the "impl header" first. This ordering is important
376                 // for in-band lifetimes! Consider `'a` here:
377                 //
378                 //     impl Foo<'a> for u32 {
379                 //         fn method(&'a self) { .. }
380                 //     }
381                 //
382                 // Because we start by lowering the `Foo<'a> for u32`
383                 // part, we will add `'a` to the list of generics on
384                 // the impl. When we then encounter it later in the
385                 // method, it will not be considered an in-band
386                 // lifetime to be added, but rather a reference to a
387                 // parent lifetime.
388                 let lowered_trait_impl_id = self.lower_node_id(id);
389                 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
390                     ast_generics,
391                     def_id,
392                     AnonymousLifetimeMode::CreateParameter,
393                     |this, _| {
394                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
395                             this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
396                         });
397
398                         if let Some(ref trait_ref) = trait_ref {
399                             if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
400                                 this.trait_impls
401                                     .entry(def_id)
402                                     .or_default()
403                                     .push(lowered_trait_impl_id);
404                             }
405                         }
406
407                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
408
409                         (trait_ref, lowered_ty)
410                     },
411                 );
412
413                 let new_impl_items =
414                     self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
415                         this.arena.alloc_from_iter(
416                             impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
417                         )
418                     });
419
420                 hir::ItemKind::Impl(
421                     unsafety,
422                     polarity,
423                     self.lower_defaultness(defaultness, true /* [1] */),
424                     generics,
425                     trait_ref,
426                     lowered_ty,
427                     new_impl_items,
428                 )
429             }
430             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
431                 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
432                 let items = self
433                     .arena
434                     .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
435                 hir::ItemKind::Trait(
436                     is_auto,
437                     unsafety,
438                     self.lower_generics(generics, ImplTraitContext::disallowed()),
439                     bounds,
440                     items,
441                 )
442             }
443             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
444                 self.lower_generics(generics, ImplTraitContext::disallowed()),
445                 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
446             ),
447             ItemKind::MacroDef(..) | ItemKind::Mac(..) => {
448                 bug!("`TyMac` should have been expanded by now")
449             }
450         }
451
452         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
453         //     not cause an assertion failure inside the `lower_defaultness` function.
454     }
455
456     fn lower_use_tree(
457         &mut self,
458         tree: &UseTree,
459         prefix: &Path,
460         id: NodeId,
461         vis: &mut hir::Visibility<'hir>,
462         ident: &mut Ident,
463         attrs: &'hir [Attribute],
464     ) -> hir::ItemKind<'hir> {
465         debug!("lower_use_tree(tree={:?})", tree);
466         debug!("lower_use_tree: vis = {:?}", vis);
467
468         let path = &tree.prefix;
469         let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
470
471         match tree.kind {
472             UseTreeKind::Simple(rename, id1, id2) => {
473                 *ident = tree.ident();
474
475                 // First, apply the prefix to the path.
476                 let mut path = Path { segments, span: path.span };
477
478                 // Correctly resolve `self` imports.
479                 if path.segments.len() > 1
480                     && path.segments.last().unwrap().ident.name == kw::SelfLower
481                 {
482                     let _ = path.segments.pop();
483                     if rename.is_none() {
484                         *ident = path.segments.last().unwrap().ident;
485                     }
486                 }
487
488                 let mut resolutions = self.expect_full_res_from_use(id);
489                 // We want to return *something* from this function, so hold onto the first item
490                 // for later.
491                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
492
493                 // Here, we are looping over namespaces, if they exist for the definition
494                 // being imported. We only handle type and value namespaces because we
495                 // won't be dealing with macros in the rest of the compiler.
496                 // Essentially a single `use` which imports two names is desugared into
497                 // two imports.
498                 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
499                     let ident = *ident;
500                     let mut path = path.clone();
501                     for seg in &mut path.segments {
502                         seg.id = self.resolver.next_node_id();
503                     }
504                     let span = path.span;
505
506                     self.with_hir_id_owner(new_node_id, |this| {
507                         let new_id = this.lower_node_id(new_node_id);
508                         let res = this.lower_res(res);
509                         let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
510                         let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
511                         let vis = this.rebuild_vis(&vis);
512
513                         this.insert_item(hir::Item {
514                             hir_id: new_id,
515                             ident,
516                             attrs,
517                             kind,
518                             vis,
519                             span,
520                         });
521                     });
522                 }
523
524                 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
525                 hir::ItemKind::Use(path, hir::UseKind::Single)
526             }
527             UseTreeKind::Glob => {
528                 let path =
529                     self.lower_path(id, &Path { segments, span: path.span }, ParamMode::Explicit);
530                 hir::ItemKind::Use(path, hir::UseKind::Glob)
531             }
532             UseTreeKind::Nested(ref trees) => {
533                 // Nested imports are desugared into simple imports.
534                 // So, if we start with
535                 //
536                 // ```
537                 // pub(x) use foo::{a, b};
538                 // ```
539                 //
540                 // we will create three items:
541                 //
542                 // ```
543                 // pub(x) use foo::a;
544                 // pub(x) use foo::b;
545                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
546                 // ```
547                 //
548                 // The first two are produced by recursively invoking
549                 // `lower_use_tree` (and indeed there may be things
550                 // like `use foo::{a::{b, c}}` and so forth).  They
551                 // wind up being directly added to
552                 // `self.items`. However, the structure of this
553                 // function also requires us to return one item, and
554                 // for that we return the `{}` import (called the
555                 // `ListStem`).
556
557                 let prefix = Path { segments, span: prefix.span.to(path.span) };
558
559                 // Add all the nested `PathListItem`s to the HIR.
560                 for &(ref use_tree, id) in trees {
561                     let new_hir_id = self.lower_node_id(id);
562
563                     let mut prefix = prefix.clone();
564
565                     // Give the segments new node-ids since they are being cloned.
566                     for seg in &mut prefix.segments {
567                         seg.id = self.resolver.next_node_id();
568                     }
569
570                     // Each `use` import is an item and thus are owners of the
571                     // names in the path. Up to this point the nested import is
572                     // the current owner, since we want each desugared import to
573                     // own its own names, we have to adjust the owner before
574                     // lowering the rest of the import.
575                     self.with_hir_id_owner(id, |this| {
576                         let mut vis = this.rebuild_vis(&vis);
577                         let mut ident = *ident;
578
579                         let kind =
580                             this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
581
582                         this.insert_item(hir::Item {
583                             hir_id: new_hir_id,
584                             ident,
585                             attrs,
586                             kind,
587                             vis,
588                             span: use_tree.span,
589                         });
590                     });
591                 }
592
593                 // Subtle and a bit hacky: we lower the privacy level
594                 // of the list stem to "private" most of the time, but
595                 // not for "restricted" paths. The key thing is that
596                 // we don't want it to stay as `pub` (with no caveats)
597                 // because that affects rustdoc and also the lints
598                 // about `pub` items. But we can't *always* make it
599                 // private -- particularly not for restricted paths --
600                 // because it contains node-ids that would then be
601                 // unused, failing the check that HirIds are "densely
602                 // assigned".
603                 match vis.node {
604                     hir::VisibilityKind::Public
605                     | hir::VisibilityKind::Crate(_)
606                     | hir::VisibilityKind::Inherited => {
607                         *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
608                     }
609                     hir::VisibilityKind::Restricted { .. } => {
610                         // Do nothing here, as described in the comment on the match.
611                     }
612                 }
613
614                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
615                 let res = self.lower_res(res);
616                 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
617                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
618             }
619         }
620     }
621
622     /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
623     /// many times in the HIR tree; for each occurrence, we need to assign distinct
624     /// `NodeId`s. (See, e.g., #56128.)
625     fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
626         debug!("rebuild_use_path(path = {:?})", path);
627         let segments =
628             self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
629                 ident: seg.ident,
630                 hir_id: seg.hir_id.map(|_| self.next_id()),
631                 res: seg.res,
632                 args: None,
633                 infer_args: seg.infer_args,
634             }));
635         self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
636     }
637
638     fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
639         let vis_kind = match vis.node {
640             hir::VisibilityKind::Public => hir::VisibilityKind::Public,
641             hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
642             hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
643             hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
644                 hir::VisibilityKind::Restricted {
645                     path: self.rebuild_use_path(path),
646                     hir_id: self.next_id(),
647                 }
648             }
649         };
650         respan(vis.span, vis_kind)
651     }
652
653     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
654         let def_id = self.resolver.definitions().local_def_id(i.id);
655         hir::ForeignItem {
656             hir_id: self.lower_node_id(i.id),
657             ident: i.ident,
658             attrs: self.lower_attrs(&i.attrs),
659             kind: match i.kind {
660                 ForeignItemKind::Fn(ref fdec, ref generics) => {
661                     let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
662                         generics,
663                         def_id,
664                         AnonymousLifetimeMode::PassThrough,
665                         |this, _| {
666                             (
667                                 // Disallow `impl Trait` in foreign items.
668                                 this.lower_fn_decl(fdec, None, false, None),
669                                 this.lower_fn_params_to_names(fdec),
670                             )
671                         },
672                     );
673
674                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
675                 }
676                 ForeignItemKind::Static(ref t, m) => {
677                     let ty = self.lower_ty(t, ImplTraitContext::disallowed());
678                     hir::ForeignItemKind::Static(ty, m)
679                 }
680                 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
681                 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
682             },
683             vis: self.lower_visibility(&i.vis, None),
684             span: i.span,
685         }
686     }
687
688     fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'hir> {
689         hir::ForeignMod {
690             abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
691             items: self.arena.alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item(x))),
692         }
693     }
694
695     fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
696         self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
697     }
698
699     fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
700         hir::Variant {
701             attrs: self.lower_attrs(&v.attrs),
702             data: self.lower_variant_data(&v.data),
703             disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
704             id: self.lower_node_id(v.id),
705             ident: v.ident,
706             span: v.span,
707         }
708     }
709
710     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> {
711         match *vdata {
712             VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
713                 self.arena
714                     .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
715                 recovered,
716             ),
717             VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
718                 self.arena
719                     .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
720                 self.lower_node_id(id),
721             ),
722             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
723         }
724     }
725
726     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'hir> {
727         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
728             let t = self.lower_path_ty(
729                 &f.ty,
730                 qself,
731                 path,
732                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
733                 ImplTraitContext::disallowed(),
734             );
735             self.arena.alloc(t)
736         } else {
737             self.lower_ty(&f.ty, ImplTraitContext::disallowed())
738         };
739         hir::StructField {
740             span: f.span,
741             hir_id: self.lower_node_id(f.id),
742             ident: match f.ident {
743                 Some(ident) => ident,
744                 // FIXME(jseyfried): positional field hygiene.
745                 None => Ident::new(sym::integer(index), f.span),
746             },
747             vis: self.lower_visibility(&f.vis, None),
748             ty,
749             attrs: self.lower_attrs(&f.attrs),
750         }
751     }
752
753     fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
754         let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
755
756         let (generics, kind) = match i.kind {
757             AssocItemKind::Const(ref ty, ref default) => {
758                 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
759                 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
760                 (
761                     generics,
762                     hir::TraitItemKind::Const(
763                         ty,
764                         default.as_ref().map(|x| self.lower_const_body(i.span, Some(x))),
765                     ),
766                 )
767             }
768             AssocItemKind::Fn(ref sig, None) => {
769                 let names = self.lower_fn_params_to_names(&sig.decl);
770                 let (generics, sig) =
771                     self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
772                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
773             }
774             AssocItemKind::Fn(ref sig, Some(ref body)) => {
775                 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
776                 let (generics, sig) =
777                     self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
778                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
779             }
780             AssocItemKind::TyAlias(ref bounds, ref default) => {
781                 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
782                 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
783                 let kind = hir::TraitItemKind::Type(
784                     self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
785                     ty,
786                 );
787
788                 (generics, kind)
789             }
790             AssocItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
791         };
792
793         hir::TraitItem {
794             hir_id: self.lower_node_id(i.id),
795             ident: i.ident,
796             attrs: self.lower_attrs(&i.attrs),
797             generics,
798             kind,
799             span: i.span,
800         }
801     }
802
803     fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
804         let (kind, has_default) = match i.kind {
805             AssocItemKind::Const(_, ref default) => (hir::AssocItemKind::Const, default.is_some()),
806             AssocItemKind::TyAlias(_, ref default) => (hir::AssocItemKind::Type, default.is_some()),
807             AssocItemKind::Fn(ref sig, ref default) => {
808                 (hir::AssocItemKind::Method { has_self: sig.decl.has_self() }, default.is_some())
809             }
810             AssocItemKind::Macro(..) => unimplemented!(),
811         };
812         hir::TraitItemRef {
813             id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
814             ident: i.ident,
815             span: i.span,
816             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
817             kind,
818         }
819     }
820
821     /// Construct `ExprKind::Err` for the given `span`.
822     fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
823         self.expr(span, hir::ExprKind::Err, AttrVec::new())
824     }
825
826     fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
827         let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
828
829         let (generics, kind) = match i.kind {
830             AssocItemKind::Const(ref ty, ref expr) => {
831                 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
832                 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
833                 (
834                     generics,
835                     hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
836                 )
837             }
838             AssocItemKind::Fn(ref sig, ref body) => {
839                 self.current_item = Some(i.span);
840                 let body_id = self.lower_maybe_async_body(
841                     i.span,
842                     &sig.decl,
843                     sig.header.asyncness.node,
844                     body.as_deref(),
845                 );
846                 let impl_trait_return_allow = !self.is_in_trait_impl;
847                 let (generics, sig) = self.lower_method_sig(
848                     &i.generics,
849                     sig,
850                     impl_item_def_id,
851                     impl_trait_return_allow,
852                     sig.header.asyncness.node.opt_return_id(),
853                 );
854
855                 (generics, hir::ImplItemKind::Method(sig, body_id))
856             }
857             AssocItemKind::TyAlias(_, ref ty) => {
858                 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
859                 let kind = match ty {
860                     None => {
861                         let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
862                         hir::ImplItemKind::TyAlias(ty)
863                     }
864                     Some(ty) => match ty.kind.opaque_top_hack() {
865                         None => {
866                             let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
867                             hir::ImplItemKind::TyAlias(ty)
868                         }
869                         Some(bs) => {
870                             let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
871                             hir::ImplItemKind::OpaqueTy(bs)
872                         }
873                     },
874                 };
875                 (generics, kind)
876             }
877             AssocItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
878         };
879
880         hir::ImplItem {
881             hir_id: self.lower_node_id(i.id),
882             ident: i.ident,
883             attrs: self.lower_attrs(&i.attrs),
884             generics,
885             vis: self.lower_visibility(&i.vis, None),
886             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
887             kind,
888             span: i.span,
889         }
890
891         // [1] since `default impl` is not yet implemented, this is always true in impls
892     }
893
894     fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
895         hir::ImplItemRef {
896             id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
897             ident: i.ident,
898             span: i.span,
899             vis: self.lower_visibility(&i.vis, Some(i.id)),
900             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
901             kind: match &i.kind {
902                 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
903                 AssocItemKind::TyAlias(_, ty) => {
904                     match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
905                         None => hir::AssocItemKind::Type,
906                         Some(_) => hir::AssocItemKind::OpaqueTy,
907                     }
908                 }
909                 AssocItemKind::Fn(sig, _) => {
910                     hir::AssocItemKind::Method { has_self: sig.decl.has_self() }
911                 }
912                 AssocItemKind::Macro(..) => unimplemented!(),
913             },
914         }
915
916         // [1] since `default impl` is not yet implemented, this is always true in impls
917     }
918
919     /// If an `explicit_owner` is given, this method allocates the `HirId` in
920     /// the address space of that item instead of the item currently being
921     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
922     /// lower a `Visibility` value although we haven't lowered the owning
923     /// `ImplItem` in question yet.
924     fn lower_visibility(
925         &mut self,
926         v: &Visibility,
927         explicit_owner: Option<NodeId>,
928     ) -> hir::Visibility<'hir> {
929         let node = match v.node {
930             VisibilityKind::Public => hir::VisibilityKind::Public,
931             VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
932             VisibilityKind::Restricted { ref path, id } => {
933                 debug!("lower_visibility: restricted path id = {:?}", id);
934                 let lowered_id = if let Some(owner) = explicit_owner {
935                     self.lower_node_id_with_owner(id, owner)
936                 } else {
937                     self.lower_node_id(id)
938                 };
939                 let res = self.expect_full_res(id);
940                 let res = self.lower_res(res);
941                 hir::VisibilityKind::Restricted {
942                     path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
943                     hir_id: lowered_id,
944                 }
945             }
946             VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
947         };
948         respan(v.span, node)
949     }
950
951     fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
952         match d {
953             Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
954             Defaultness::Final => {
955                 assert!(has_value);
956                 hir::Defaultness::Final
957             }
958         }
959     }
960
961     fn record_body(
962         &mut self,
963         params: &'hir [hir::Param<'hir>],
964         value: hir::Expr<'hir>,
965     ) -> hir::BodyId {
966         let body = hir::Body { generator_kind: self.generator_kind, params, value };
967         let id = body.id();
968         self.bodies.insert(id, body);
969         id
970     }
971
972     fn lower_body(
973         &mut self,
974         f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
975     ) -> hir::BodyId {
976         let prev_gen_kind = self.generator_kind.take();
977         let (parameters, result) = f(self);
978         let body_id = self.record_body(parameters, result);
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: IsAsync,
1038         body: Option<&Block>,
1039     ) -> hir::BodyId {
1040         let closure_id = match asyncness {
1041             IsAsync::Async { closure_id, .. } => closure_id,
1042             IsAsync::NotAsync => 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: DefId,
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, 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: h.unsafety,
1252             asyncness: self.lower_asyncness(h.asyncness.node),
1253             constness: h.constness.node,
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: IsAsync) -> hir::IsAsync {
1281         match a {
1282             IsAsync::Async { .. } => hir::IsAsync::Async,
1283             IsAsync::NotAsync => hir::IsAsync::NotAsync,
1284         }
1285     }
1286
1287     pub(super) fn lower_generics_mut(
1288         &mut self,
1289         generics: &Generics,
1290         itctx: ImplTraitContext<'_, 'hir>,
1291     ) -> GenericsCtor<'hir> {
1292         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1293         // FIXME: this could probably be done with less rightward drift. It also looks like two
1294         // control paths where `report_error` is called are the only paths that advance to after the
1295         // match statement, so the error reporting could probably just be moved there.
1296         let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1297         for pred in &generics.where_clause.predicates {
1298             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1299                 'next_bound: for bound in &bound_pred.bounds {
1300                     if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1301                         let report_error = |this: &mut Self| {
1302                             this.diagnostic().span_err(
1303                                 bound_pred.bounded_ty.span,
1304                                 "`?Trait` bounds are only permitted at the \
1305                                  point where a type parameter is declared",
1306                             );
1307                         };
1308                         // Check if the where clause type is a plain type parameter.
1309                         match bound_pred.bounded_ty.kind {
1310                             TyKind::Path(None, ref path)
1311                                 if path.segments.len() == 1
1312                                     && bound_pred.bound_generic_params.is_empty() =>
1313                             {
1314                                 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1315                                     .resolver
1316                                     .get_partial_res(bound_pred.bounded_ty.id)
1317                                     .map(|d| d.base_res())
1318                                 {
1319                                     if let Some(node_id) =
1320                                         self.resolver.definitions().as_local_node_id(def_id)
1321                                     {
1322                                         for param in &generics.params {
1323                                             match param.kind {
1324                                                 GenericParamKind::Type { .. } => {
1325                                                     if node_id == param.id {
1326                                                         add_bounds
1327                                                             .entry(param.id)
1328                                                             .or_default()
1329                                                             .push(bound.clone());
1330                                                         continue 'next_bound;
1331                                                     }
1332                                                 }
1333                                                 _ => {}
1334                                             }
1335                                         }
1336                                     }
1337                                 }
1338                                 report_error(self)
1339                             }
1340                             _ => report_error(self),
1341                         }
1342                     }
1343                 }
1344             }
1345         }
1346
1347         GenericsCtor {
1348             params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1349             where_clause: self.lower_where_clause(&generics.where_clause),
1350             span: generics.span,
1351         }
1352     }
1353
1354     pub(super) fn lower_generics(
1355         &mut self,
1356         generics: &Generics,
1357         itctx: ImplTraitContext<'_, 'hir>,
1358     ) -> hir::Generics<'hir> {
1359         let generics_ctor = self.lower_generics_mut(generics, itctx);
1360         generics_ctor.into_generics(self.arena)
1361     }
1362
1363     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1364         self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1365             hir::WhereClause {
1366                 predicates: this.arena.alloc_from_iter(
1367                     wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1368                 ),
1369                 span: wc.span,
1370             }
1371         })
1372     }
1373
1374     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1375         match *pred {
1376             WherePredicate::BoundPredicate(WhereBoundPredicate {
1377                 ref bound_generic_params,
1378                 ref bounded_ty,
1379                 ref bounds,
1380                 span,
1381             }) => {
1382                 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1383                     hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1384                         bound_generic_params: this.lower_generic_params(
1385                             bound_generic_params,
1386                             &NodeMap::default(),
1387                             ImplTraitContext::disallowed(),
1388                         ),
1389                         bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1390                         bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1391                             match *bound {
1392                                 // Ignore `?Trait` bounds.
1393                                 // They were copied into type parameters already.
1394                                 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1395                                 _ => Some(
1396                                     this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1397                                 ),
1398                             }
1399                         })),
1400                         span,
1401                     })
1402                 })
1403             }
1404             WherePredicate::RegionPredicate(WhereRegionPredicate {
1405                 ref lifetime,
1406                 ref bounds,
1407                 span,
1408             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1409                 span,
1410                 lifetime: self.lower_lifetime(lifetime),
1411                 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1412             }),
1413             WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1414                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1415                     hir_id: self.lower_node_id(id),
1416                     lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1417                     rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1418                     span,
1419                 })
1420             }
1421         }
1422     }
1423 }
1424
1425 /// Helper struct for delayed construction of Generics.
1426 pub(super) struct GenericsCtor<'hir> {
1427     pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1428     where_clause: hir::WhereClause<'hir>,
1429     span: Span,
1430 }
1431
1432 impl<'hir> GenericsCtor<'hir> {
1433     pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1434         hir::Generics {
1435             params: arena.alloc_from_iter(self.params),
1436             where_clause: self.where_clause,
1437             span: self.span,
1438         }
1439     }
1440 }