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