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