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