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