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