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