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