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