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