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