]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/item.rs
76316a574acb7033c2311b45e32d06a84e9f3a2d
[rust.git] / compiler / rustc_ast_lowering / src / item.rs
1 use super::errors::{InvalidAbi, InvalidAbiSuggestion, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
5
6 use rustc_ast::ptr::P;
7 use rustc_ast::visit::AssocCtxt;
8 use rustc_ast::*;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::sorted_map::SortedMap;
11 use rustc_hir as hir;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
14 use rustc_hir::PredicateOrigin;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
17 use rustc_span::lev_distance::find_best_match_for_name;
18 use rustc_span::source_map::DesugaringKind;
19 use rustc_span::symbol::{kw, sym, Ident};
20 use rustc_span::{Span, Symbol};
21 use rustc_target::spec::abi;
22 use smallvec::{smallvec, SmallVec};
23
24 use std::iter;
25
26 pub(super) struct ItemLowerer<'a, 'hir> {
27     pub(super) tcx: TyCtxt<'hir>,
28     pub(super) resolver: &'a mut ResolverAstLowering,
29     pub(super) ast_arena: &'a Arena<'static>,
30     pub(super) ast_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
31     pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
32 }
33
34 /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
35 /// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
36 /// clause if it exists.
37 fn add_ty_alias_where_clause(
38     generics: &mut ast::Generics,
39     mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
40     prefer_first: bool,
41 ) {
42     if !prefer_first {
43         where_clauses = (where_clauses.1, where_clauses.0);
44     }
45     if where_clauses.0.0 || !where_clauses.1.0 {
46         generics.where_clause.has_where_token = where_clauses.0.0;
47         generics.where_clause.span = where_clauses.0.1;
48     } else {
49         generics.where_clause.has_where_token = where_clauses.1.0;
50         generics.where_clause.span = where_clauses.1.1;
51     }
52 }
53
54 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
55     fn with_lctx(
56         &mut self,
57         owner: NodeId,
58         f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
59     ) {
60         let mut lctx = LoweringContext {
61             // Pseudo-globals.
62             tcx: self.tcx,
63             resolver: self.resolver,
64             arena: self.tcx.hir_arena,
65             ast_arena: self.ast_arena,
66
67             // HirId handling.
68             bodies: Vec::new(),
69             attrs: SortedMap::default(),
70             children: FxHashMap::default(),
71             current_hir_id_owner: hir::CRATE_OWNER_ID,
72             item_local_id_counter: hir::ItemLocalId::new(0),
73             node_id_to_local_id: Default::default(),
74             local_id_to_def_id: SortedMap::new(),
75             trait_map: Default::default(),
76
77             // Lowering state.
78             catch_scope: None,
79             loop_scope: None,
80             is_in_loop_condition: false,
81             is_in_trait_impl: false,
82             is_in_dyn_type: false,
83             generator_kind: None,
84             task_context: None,
85             current_item: None,
86             impl_trait_defs: Vec::new(),
87             impl_trait_bounds: Vec::new(),
88             allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
89             allow_gen_future: Some([sym::gen_future][..].into()),
90             allow_into_future: Some([sym::into_future][..].into()),
91             generics_def_id_map: Default::default(),
92         };
93         lctx.with_hir_id_owner(owner, |lctx| f(lctx));
94
95         for (def_id, info) in lctx.children {
96             self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
97             debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
98             self.owners[def_id] = info;
99         }
100     }
101
102     pub(super) fn lower_node(
103         &mut self,
104         def_id: LocalDefId,
105     ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
106         self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
107         if let hir::MaybeOwner::Phantom = self.owners[def_id] {
108             let node = self.ast_index[def_id];
109             match node {
110                 AstOwner::NonOwner => {}
111                 AstOwner::Crate(c) => self.lower_crate(c),
112                 AstOwner::Item(item) => self.lower_item(item),
113                 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
114                 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
115             }
116         }
117
118         self.owners[def_id]
119     }
120
121     #[instrument(level = "debug", skip(self, c))]
122     fn lower_crate(&mut self, c: &Crate) {
123         debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
124         self.with_lctx(CRATE_NODE_ID, |lctx| {
125             let module = lctx.lower_mod(&c.items, &c.spans);
126             lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
127             hir::OwnerNode::Crate(module)
128         })
129     }
130
131     #[instrument(level = "debug", skip(self))]
132     fn lower_item(&mut self, item: &Item) {
133         self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
134     }
135
136     fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
137         let def_id = self.resolver.node_id_to_def_id[&item.id];
138
139         let parent_id = self.tcx.local_parent(def_id);
140         let parent_hir = self.lower_node(parent_id).unwrap();
141         self.with_lctx(item.id, |lctx| {
142             // Evaluate with the lifetimes in `params` in-scope.
143             // This is used to track which lifetimes have already been defined,
144             // and which need to be replicated when lowering an async fn.
145             match parent_hir.node().expect_item().kind {
146                 hir::ItemKind::Impl(hir::Impl { ref of_trait, .. }) => {
147                     lctx.is_in_trait_impl = of_trait.is_some();
148                 }
149                 _ => {}
150             };
151
152             match ctxt {
153                 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
154                 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
155             }
156         })
157     }
158
159     fn lower_foreign_item(&mut self, item: &ForeignItem) {
160         self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
161     }
162 }
163
164 impl<'hir> LoweringContext<'_, 'hir> {
165     pub(super) fn lower_mod(
166         &mut self,
167         items: &[P<Item>],
168         spans: &ModSpans,
169     ) -> &'hir hir::Mod<'hir> {
170         self.arena.alloc(hir::Mod {
171             spans: hir::ModSpans {
172                 inner_span: self.lower_span(spans.inner_span),
173                 inject_use_span: self.lower_span(spans.inject_use_span),
174             },
175             item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
176         })
177     }
178
179     pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
180         let mut node_ids =
181             smallvec![hir::ItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }];
182         if let ItemKind::Use(ref use_tree) = &i.kind {
183             self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
184         }
185         node_ids
186     }
187
188     fn lower_item_id_use_tree(
189         &mut self,
190         tree: &UseTree,
191         base_id: NodeId,
192         vec: &mut SmallVec<[hir::ItemId; 1]>,
193     ) {
194         match tree.kind {
195             UseTreeKind::Nested(ref nested_vec) => {
196                 for &(ref nested, id) in nested_vec {
197                     vec.push(hir::ItemId {
198                         owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
199                     });
200                     self.lower_item_id_use_tree(nested, id, vec);
201                 }
202             }
203             UseTreeKind::Glob => {}
204             UseTreeKind::Simple(_, id1, id2) => {
205                 for (_, &id) in
206                     iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
207                 {
208                     vec.push(hir::ItemId {
209                         owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
210                     });
211                 }
212             }
213         }
214     }
215
216     fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
217         let mut ident = i.ident;
218         let vis_span = self.lower_span(i.vis.span);
219         let hir_id = self.lower_node_id(i.id);
220         let attrs = self.lower_attrs(hir_id, &i.attrs);
221         let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
222         let item = hir::Item {
223             owner_id: hir_id.expect_owner(),
224             ident: self.lower_ident(ident),
225             kind,
226             vis_span,
227             span: self.lower_span(i.span),
228         };
229         self.arena.alloc(item)
230     }
231
232     fn lower_item_kind(
233         &mut self,
234         span: Span,
235         id: NodeId,
236         hir_id: hir::HirId,
237         ident: &mut Ident,
238         attrs: Option<&'hir [Attribute]>,
239         vis_span: Span,
240         i: &ItemKind,
241     ) -> hir::ItemKind<'hir> {
242         match *i {
243             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
244             ItemKind::Use(ref use_tree) => {
245                 // Start with an empty prefix.
246                 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
247
248                 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
249             }
250             ItemKind::Static(ref t, m, ref e) => {
251                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
252                 hir::ItemKind::Static(ty, m, body_id)
253             }
254             ItemKind::Const(_, ref t, ref e) => {
255                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
256                 hir::ItemKind::Const(ty, body_id)
257             }
258             ItemKind::Fn(box Fn {
259                 sig: FnSig { ref decl, header, span: fn_sig_span },
260                 ref generics,
261                 ref body,
262                 ..
263             }) => {
264                 self.with_new_scopes(|this| {
265                     this.current_item = Some(ident.span);
266
267                     // Note: we don't need to change the return type from `T` to
268                     // `impl Future<Output = T>` here because lower_body
269                     // only cares about the input argument patterns in the function
270                     // declaration (decl), not the return types.
271                     let asyncness = header.asyncness;
272                     let body_id =
273                         this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
274
275                     let mut itctx = ImplTraitContext::Universal;
276                     let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
277                         let ret_id = asyncness.opt_return_id();
278                         this.lower_fn_decl(&decl, Some(id), fn_sig_span, FnDeclKind::Fn, ret_id)
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, _, spans) => {
290                     hir::ItemKind::Mod(self.lower_mod(items, spans))
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 TyAlias {
304                 ref generics,
305                 where_clauses,
306                 ty: Some(ref ty),
307                 ..
308             }) => {
309                 // We lower
310                 //
311                 // type Foo = impl Trait
312                 //
313                 // to
314                 //
315                 // type Foo = Foo1
316                 // opaque type Foo1: Trait
317                 let mut generics = generics.clone();
318                 add_ty_alias_where_clause(&mut generics, where_clauses, true);
319                 let (generics, ty) = self.lower_generics(
320                     &generics,
321                     id,
322                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
323                     |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
324                 );
325                 hir::ItemKind::TyAlias(ty, generics)
326             }
327             ItemKind::TyAlias(box TyAlias {
328                 ref generics, ref where_clauses, ty: None, ..
329             }) => {
330                 let mut generics = generics.clone();
331                 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
332                 let (generics, ty) = self.lower_generics(
333                     &generics,
334                     id,
335                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
336                     |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
337                 );
338                 hir::ItemKind::TyAlias(ty, generics)
339             }
340             ItemKind::Enum(ref enum_definition, ref generics) => {
341                 let (generics, variants) = self.lower_generics(
342                     generics,
343                     id,
344                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
345                     |this| {
346                         this.arena.alloc_from_iter(
347                             enum_definition.variants.iter().map(|x| this.lower_variant(x)),
348                         )
349                     },
350                 );
351                 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
352             }
353             ItemKind::Struct(ref struct_def, ref generics) => {
354                 let (generics, struct_def) = self.lower_generics(
355                     generics,
356                     id,
357                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
358                     |this| this.lower_variant_data(hir_id, struct_def),
359                 );
360                 hir::ItemKind::Struct(struct_def, generics)
361             }
362             ItemKind::Union(ref vdata, ref generics) => {
363                 let (generics, vdata) = self.lower_generics(
364                     generics,
365                     id,
366                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
367                     |this| this.lower_variant_data(hir_id, vdata),
368                 );
369                 hir::ItemKind::Union(vdata, generics)
370             }
371             ItemKind::Impl(box Impl {
372                 unsafety,
373                 polarity,
374                 defaultness,
375                 constness,
376                 generics: ref ast_generics,
377                 of_trait: ref trait_ref,
378                 self_ty: ref ty,
379                 items: ref impl_items,
380             }) => {
381                 // Lower the "impl header" first. This ordering is important
382                 // for in-band lifetimes! Consider `'a` here:
383                 //
384                 //     impl Foo<'a> for u32 {
385                 //         fn method(&'a self) { .. }
386                 //     }
387                 //
388                 // Because we start by lowering the `Foo<'a> for u32`
389                 // part, we will add `'a` to the list of generics on
390                 // the impl. When we then encounter it later in the
391                 // method, it will not be considered an in-band
392                 // lifetime to be added, but rather a reference to a
393                 // parent lifetime.
394                 let mut itctx = ImplTraitContext::Universal;
395                 let (generics, (trait_ref, lowered_ty)) =
396                     self.lower_generics(ast_generics, id, &mut itctx, |this| {
397                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
398                             this.lower_trait_ref(
399                                 trait_ref,
400                                 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
401                             )
402                         });
403
404                         let lowered_ty = this
405                             .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
406
407                         (trait_ref, lowered_ty)
408                     });
409
410                 let new_impl_items = self
411                     .arena
412                     .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
413
414                 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
415                 // to not cause an assertion failure inside the `lower_defaultness` function.
416                 let has_val = true;
417                 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
418                 let polarity = match polarity {
419                     ImplPolarity::Positive => ImplPolarity::Positive,
420                     ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
421                 };
422                 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
423                     unsafety: self.lower_unsafety(unsafety),
424                     polarity,
425                     defaultness,
426                     defaultness_span,
427                     constness: self.lower_constness(constness),
428                     generics,
429                     of_trait: trait_ref,
430                     self_ty: lowered_ty,
431                     items: new_impl_items,
432                 }))
433             }
434             ItemKind::Trait(box Trait {
435                 is_auto,
436                 unsafety,
437                 ref generics,
438                 ref bounds,
439                 ref items,
440             }) => {
441                 let (generics, (unsafety, items, bounds)) = self.lower_generics(
442                     generics,
443                     id,
444                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
445                     |this| {
446                         let bounds = this.lower_param_bounds(
447                             bounds,
448                             &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
449                         );
450                         let items = this.arena.alloc_from_iter(
451                             items.iter().map(|item| this.lower_trait_item_ref(item)),
452                         );
453                         let unsafety = this.lower_unsafety(unsafety);
454                         (unsafety, items, bounds)
455                     },
456                 );
457                 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
458             }
459             ItemKind::TraitAlias(ref generics, ref bounds) => {
460                 let (generics, bounds) = self.lower_generics(
461                     generics,
462                     id,
463                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
464                     |this| {
465                         this.lower_param_bounds(
466                             bounds,
467                             &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
468                         )
469                     },
470                 );
471                 hir::ItemKind::TraitAlias(generics, bounds)
472             }
473             ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
474                 let body = P(self.lower_mac_args(body));
475                 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
476                 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
477             }
478             ItemKind::MacCall(..) => {
479                 panic!("`TyMac` should have been expanded by now")
480             }
481         }
482     }
483
484     fn lower_const_item(
485         &mut self,
486         ty: &Ty,
487         span: Span,
488         body: Option<&Expr>,
489     ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
490         let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
491         (ty, self.lower_const_body(span, body))
492     }
493
494     #[instrument(level = "debug", skip(self))]
495     fn lower_use_tree(
496         &mut self,
497         tree: &UseTree,
498         prefix: &Path,
499         id: NodeId,
500         vis_span: Span,
501         ident: &mut Ident,
502         attrs: Option<&'hir [Attribute]>,
503     ) -> hir::ItemKind<'hir> {
504         let path = &tree.prefix;
505         let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
506
507         match tree.kind {
508             UseTreeKind::Simple(rename, id1, id2) => {
509                 *ident = tree.ident();
510
511                 // First, apply the prefix to the path.
512                 let mut path = Path { segments, span: path.span, tokens: None };
513
514                 // Correctly resolve `self` imports.
515                 if path.segments.len() > 1
516                     && path.segments.last().unwrap().ident.name == kw::SelfLower
517                 {
518                     let _ = path.segments.pop();
519                     if rename.is_none() {
520                         *ident = path.segments.last().unwrap().ident;
521                     }
522                 }
523
524                 let mut resolutions = self.expect_full_res_from_use(id).fuse();
525                 // We want to return *something* from this function, so hold onto the first item
526                 // for later.
527                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
528
529                 // Here, we are looping over namespaces, if they exist for the definition
530                 // being imported. We only handle type and value namespaces because we
531                 // won't be dealing with macros in the rest of the compiler.
532                 // Essentially a single `use` which imports two names is desugared into
533                 // two imports.
534                 for new_node_id in [id1, id2] {
535                     let new_id = self.local_def_id(new_node_id);
536                     let Some(res) = resolutions.next() else {
537                         // Associate an HirId to both ids even if there is no resolution.
538                         let _old = self.children.insert(
539                             new_id,
540                             hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
541                         );
542                         debug_assert!(_old.is_none());
543                         continue;
544                     };
545                     let ident = *ident;
546                     let mut path = path.clone();
547                     for seg in &mut path.segments {
548                         // Give the cloned segment the same resolution information
549                         // as the old one (this is needed for stability checking).
550                         let new_id = self.next_node_id();
551                         self.resolver.clone_res(seg.id, new_id);
552                         seg.id = new_id;
553                     }
554                     let span = path.span;
555
556                     self.with_hir_id_owner(new_node_id, |this| {
557                         let res = this.lower_res(res);
558                         let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
559                         let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
560                         if let Some(attrs) = attrs {
561                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
562                         }
563
564                         let item = hir::Item {
565                             owner_id: hir::OwnerId { def_id: new_id },
566                             ident: this.lower_ident(ident),
567                             kind,
568                             vis_span,
569                             span: this.lower_span(span),
570                         };
571                         hir::OwnerNode::Item(this.arena.alloc(item))
572                     });
573                 }
574
575                 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
576                 hir::ItemKind::Use(path, hir::UseKind::Single)
577             }
578             UseTreeKind::Glob => {
579                 let path = self.lower_path(
580                     id,
581                     &Path { segments, span: path.span, tokens: None },
582                     ParamMode::Explicit,
583                 );
584                 hir::ItemKind::Use(path, hir::UseKind::Glob)
585             }
586             UseTreeKind::Nested(ref trees) => {
587                 // Nested imports are desugared into simple imports.
588                 // So, if we start with
589                 //
590                 // ```
591                 // pub(x) use foo::{a, b};
592                 // ```
593                 //
594                 // we will create three items:
595                 //
596                 // ```
597                 // pub(x) use foo::a;
598                 // pub(x) use foo::b;
599                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
600                 // ```
601                 //
602                 // The first two are produced by recursively invoking
603                 // `lower_use_tree` (and indeed there may be things
604                 // like `use foo::{a::{b, c}}` and so forth).  They
605                 // wind up being directly added to
606                 // `self.items`. However, the structure of this
607                 // function also requires us to return one item, and
608                 // for that we return the `{}` import (called the
609                 // `ListStem`).
610
611                 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
612
613                 // Add all the nested `PathListItem`s to the HIR.
614                 for &(ref use_tree, id) in trees {
615                     let new_hir_id = self.local_def_id(id);
616
617                     let mut prefix = prefix.clone();
618
619                     // Give the segments new node-ids since they are being cloned.
620                     for seg in &mut prefix.segments {
621                         // Give the cloned segment the same resolution information
622                         // as the old one (this is needed for stability checking).
623                         let new_id = self.next_node_id();
624                         self.resolver.clone_res(seg.id, new_id);
625                         seg.id = new_id;
626                     }
627
628                     // Each `use` import is an item and thus are owners of the
629                     // names in the path. Up to this point the nested import is
630                     // the current owner, since we want each desugared import to
631                     // own its own names, we have to adjust the owner before
632                     // lowering the rest of the import.
633                     self.with_hir_id_owner(id, |this| {
634                         let mut ident = *ident;
635
636                         let kind =
637                             this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
638                         if let Some(attrs) = attrs {
639                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
640                         }
641
642                         let item = hir::Item {
643                             owner_id: hir::OwnerId { def_id: new_hir_id },
644                             ident: this.lower_ident(ident),
645                             kind,
646                             vis_span,
647                             span: this.lower_span(use_tree.span),
648                         };
649                         hir::OwnerNode::Item(this.arena.alloc(item))
650                     });
651                 }
652
653                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
654                 let res = self.lower_res(res);
655                 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
656                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
657             }
658         }
659     }
660
661     fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
662         let hir_id = self.lower_node_id(i.id);
663         let owner_id = hir_id.expect_owner();
664         self.lower_attrs(hir_id, &i.attrs);
665         let item = hir::ForeignItem {
666             owner_id,
667             ident: self.lower_ident(i.ident),
668             kind: match i.kind {
669                 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
670                     let fdec = &sig.decl;
671                     let mut itctx = ImplTraitContext::Universal;
672                     let (generics, (fn_dec, fn_args)) =
673                         self.lower_generics(generics, i.id, &mut itctx, |this| {
674                             (
675                                 // Disallow `impl Trait` in foreign items.
676                                 this.lower_fn_decl(
677                                     fdec,
678                                     None,
679                                     sig.span,
680                                     FnDeclKind::ExternFn,
681                                     None,
682                                 ),
683                                 this.lower_fn_params_to_names(fdec),
684                             )
685                         });
686
687                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
688                 }
689                 ForeignItemKind::Static(ref t, m, _) => {
690                     let ty =
691                         self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
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_span: self.lower_span(i.vis.span),
698             span: self.lower_span(i.span),
699         };
700         self.arena.alloc(item)
701     }
702
703     fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
704         hir::ForeignItemRef {
705             id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
706             ident: self.lower_ident(i.ident),
707             span: self.lower_span(i.span),
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     fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
753         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
754             let t = self.lower_path_ty(
755                 &f.ty,
756                 qself,
757                 path,
758                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
759                 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
760             );
761             self.arena.alloc(t)
762         } else {
763             self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
764         };
765         let hir_id = self.lower_node_id(f.id);
766         self.lower_attrs(hir_id, &f.attrs);
767         hir::FieldDef {
768             span: self.lower_span(f.span),
769             hir_id,
770             ident: match f.ident {
771                 Some(ident) => self.lower_ident(ident),
772                 // FIXME(jseyfried): positional field hygiene.
773                 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
774             },
775             vis_span: self.lower_span(f.vis.span),
776             ty,
777         }
778     }
779
780     fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
781         let hir_id = self.lower_node_id(i.id);
782         let trait_item_def_id = hir_id.expect_owner();
783
784         let (generics, kind, has_default) = match i.kind {
785             AssocItemKind::Const(_, ref ty, ref default) => {
786                 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
787                 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
788                 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
789             }
790             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
791                 let asyncness = sig.header.asyncness;
792                 let names = self.lower_fn_params_to_names(&sig.decl);
793                 let (generics, sig) = self.lower_method_sig(
794                     generics,
795                     sig,
796                     i.id,
797                     FnDeclKind::Trait,
798                     asyncness.opt_return_id(),
799                 );
800                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
801             }
802             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
803                 let asyncness = sig.header.asyncness;
804                 let body_id =
805                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
806                 let (generics, sig) = self.lower_method_sig(
807                     generics,
808                     sig,
809                     i.id,
810                     FnDeclKind::Trait,
811                     asyncness.opt_return_id(),
812                 );
813                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
814             }
815             AssocItemKind::Type(box TyAlias {
816                 ref generics,
817                 where_clauses,
818                 ref bounds,
819                 ref ty,
820                 ..
821             }) => {
822                 let mut generics = generics.clone();
823                 add_ty_alias_where_clause(&mut generics, where_clauses, false);
824                 let (generics, kind) = self.lower_generics(
825                     &generics,
826                     i.id,
827                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
828                     |this| {
829                         let ty = ty.as_ref().map(|x| {
830                             this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
831                         });
832                         hir::TraitItemKind::Type(
833                             this.lower_param_bounds(
834                                 bounds,
835                                 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
836                             ),
837                             ty,
838                         )
839                     },
840                 );
841                 (generics, kind, ty.is_some())
842             }
843             AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
844         };
845
846         self.lower_attrs(hir_id, &i.attrs);
847         let item = hir::TraitItem {
848             owner_id: trait_item_def_id,
849             ident: self.lower_ident(i.ident),
850             generics,
851             kind,
852             span: self.lower_span(i.span),
853             defaultness: hir::Defaultness::Default { has_value: has_default },
854         };
855         self.arena.alloc(item)
856     }
857
858     fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
859         let kind = match &i.kind {
860             AssocItemKind::Const(..) => hir::AssocItemKind::Const,
861             AssocItemKind::Type(..) => hir::AssocItemKind::Type,
862             AssocItemKind::Fn(box Fn { sig, .. }) => {
863                 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
864             }
865             AssocItemKind::MacCall(..) => unimplemented!(),
866         };
867         let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
868         hir::TraitItemRef {
869             id,
870             ident: self.lower_ident(i.ident),
871             span: self.lower_span(i.span),
872             kind,
873         }
874     }
875
876     /// Construct `ExprKind::Err` for the given `span`.
877     pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
878         self.expr(span, hir::ExprKind::Err, AttrVec::new())
879     }
880
881     fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
882         // Since `default impl` is not yet implemented, this is always true in impls.
883         let has_value = true;
884         let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
885
886         let (generics, kind) = match &i.kind {
887             AssocItemKind::Const(_, ty, expr) => {
888                 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
889                 (
890                     hir::Generics::empty(),
891                     hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
892                 )
893             }
894             AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
895                 self.current_item = Some(i.span);
896                 let asyncness = sig.header.asyncness;
897                 let body_id =
898                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
899                 let (generics, sig) = self.lower_method_sig(
900                     generics,
901                     sig,
902                     i.id,
903                     if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
904                     asyncness.opt_return_id(),
905                 );
906
907                 (generics, hir::ImplItemKind::Fn(sig, body_id))
908             }
909             AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
910                 let mut generics = generics.clone();
911                 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
912                 self.lower_generics(
913                     &generics,
914                     i.id,
915                     &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
916                     |this| match ty {
917                         None => {
918                             let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
919                             hir::ImplItemKind::Type(ty)
920                         }
921                         Some(ty) => {
922                             let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
923                             hir::ImplItemKind::Type(ty)
924                         }
925                     },
926                 )
927             }
928             AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
929         };
930
931         let hir_id = self.lower_node_id(i.id);
932         self.lower_attrs(hir_id, &i.attrs);
933         let item = hir::ImplItem {
934             owner_id: hir_id.expect_owner(),
935             ident: self.lower_ident(i.ident),
936             generics,
937             kind,
938             vis_span: self.lower_span(i.vis.span),
939             span: self.lower_span(i.span),
940             defaultness,
941         };
942         self.arena.alloc(item)
943     }
944
945     fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
946         hir::ImplItemRef {
947             id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
948             ident: self.lower_ident(i.ident),
949             span: self.lower_span(i.span),
950             kind: match &i.kind {
951                 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
952                 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
953                 AssocItemKind::Fn(box Fn { sig, .. }) => {
954                     hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
955                 }
956                 AssocItemKind::MacCall(..) => unimplemented!(),
957             },
958             trait_item_def_id: self
959                 .resolver
960                 .get_partial_res(i.id)
961                 .map(|r| r.expect_full_res().def_id()),
962         }
963     }
964
965     fn lower_defaultness(
966         &self,
967         d: Defaultness,
968         has_value: bool,
969     ) -> (hir::Defaultness, Option<Span>) {
970         match d {
971             Defaultness::Default(sp) => {
972                 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
973             }
974             Defaultness::Final => {
975                 assert!(has_value);
976                 (hir::Defaultness::Final, None)
977             }
978         }
979     }
980
981     fn record_body(
982         &mut self,
983         params: &'hir [hir::Param<'hir>],
984         value: hir::Expr<'hir>,
985     ) -> hir::BodyId {
986         let body = hir::Body {
987             generator_kind: self.generator_kind,
988             params,
989             value: self.arena.alloc(value),
990         };
991         let id = body.id();
992         debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
993         self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
994         id
995     }
996
997     pub(super) fn lower_body(
998         &mut self,
999         f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1000     ) -> hir::BodyId {
1001         let prev_gen_kind = self.generator_kind.take();
1002         let task_context = self.task_context.take();
1003         let (parameters, result) = f(self);
1004         let body_id = self.record_body(parameters, result);
1005         self.task_context = task_context;
1006         self.generator_kind = prev_gen_kind;
1007         body_id
1008     }
1009
1010     fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1011         let hir_id = self.lower_node_id(param.id);
1012         self.lower_attrs(hir_id, &param.attrs);
1013         hir::Param {
1014             hir_id,
1015             pat: self.lower_pat(&param.pat),
1016             ty_span: self.lower_span(param.ty.span),
1017             span: self.lower_span(param.span),
1018         }
1019     }
1020
1021     pub(super) fn lower_fn_body(
1022         &mut self,
1023         decl: &FnDecl,
1024         body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1025     ) -> hir::BodyId {
1026         self.lower_body(|this| {
1027             (
1028                 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1029                 body(this),
1030             )
1031         })
1032     }
1033
1034     fn lower_fn_body_block(
1035         &mut self,
1036         span: Span,
1037         decl: &FnDecl,
1038         body: Option<&Block>,
1039     ) -> hir::BodyId {
1040         self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1041     }
1042
1043     fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1044         match block {
1045             Some(block) => self.lower_block_expr(block),
1046             None => self.expr_err(span),
1047         }
1048     }
1049
1050     pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1051         self.lower_body(|this| {
1052             (
1053                 &[],
1054                 match expr {
1055                     Some(expr) => this.lower_expr_mut(expr),
1056                     None => this.expr_err(span),
1057                 },
1058             )
1059         })
1060     }
1061
1062     fn lower_maybe_async_body(
1063         &mut self,
1064         span: Span,
1065         decl: &FnDecl,
1066         asyncness: Async,
1067         body: Option<&Block>,
1068     ) -> hir::BodyId {
1069         let (closure_id, body) = match (asyncness, body) {
1070             (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
1071             _ => return self.lower_fn_body_block(span, decl, body),
1072         };
1073
1074         self.lower_body(|this| {
1075             let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1076             let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1077
1078             // Async function parameters are lowered into the closure body so that they are
1079             // captured and so that the drop order matches the equivalent non-async functions.
1080             //
1081             // from:
1082             //
1083             //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1084             //         <body>
1085             //     }
1086             //
1087             // into:
1088             //
1089             //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1090             //       async move {
1091             //         let __arg2 = __arg2;
1092             //         let <pattern> = __arg2;
1093             //         let __arg1 = __arg1;
1094             //         let <pattern> = __arg1;
1095             //         let __arg0 = __arg0;
1096             //         let <pattern> = __arg0;
1097             //         drop-temps { <body> } // see comments later in fn for details
1098             //       }
1099             //     }
1100             //
1101             // If `<pattern>` is a simple ident, then it is lowered to a single
1102             // `let <pattern> = <pattern>;` statement as an optimization.
1103             //
1104             // Note that the body is embedded in `drop-temps`; an
1105             // equivalent desugaring would be `return { <body>
1106             // };`. The key point is that we wish to drop all the
1107             // let-bound variables and temporaries created in the body
1108             // (and its tail expression!) before we drop the
1109             // parameters (c.f. rust-lang/rust#64512).
1110             for (index, parameter) in decl.inputs.iter().enumerate() {
1111                 let parameter = this.lower_param(parameter);
1112                 let span = parameter.pat.span;
1113
1114                 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1115                 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1116                 let (ident, is_simple_parameter) = match parameter.pat.kind {
1117                     hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1118                         (ident, true)
1119                     }
1120                     // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1121                     // we can keep the same name for the parameter.
1122                     // This lets rustdoc render it correctly in documentation.
1123                     hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1124                     hir::PatKind::Wild => {
1125                         (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1126                     }
1127                     _ => {
1128                         // Replace the ident for bindings that aren't simple.
1129                         let name = format!("__arg{}", index);
1130                         let ident = Ident::from_str(&name);
1131
1132                         (ident, false)
1133                     }
1134                 };
1135
1136                 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1137
1138                 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1139                 // async function.
1140                 //
1141                 // If this is the simple case, this parameter will end up being the same as the
1142                 // original parameter, but with a different pattern id.
1143                 let stmt_attrs = this.attrs.get(&parameter.hir_id.local_id).copied();
1144                 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1145                 let new_parameter = hir::Param {
1146                     hir_id: parameter.hir_id,
1147                     pat: new_parameter_pat,
1148                     ty_span: this.lower_span(parameter.ty_span),
1149                     span: this.lower_span(parameter.span),
1150                 };
1151
1152                 if is_simple_parameter {
1153                     // If this is the simple case, then we only insert one statement that is
1154                     // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1155                     // `HirId`s are densely assigned.
1156                     let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1157                     let stmt = this.stmt_let_pat(
1158                         stmt_attrs,
1159                         desugared_span,
1160                         Some(expr),
1161                         parameter.pat,
1162                         hir::LocalSource::AsyncFn,
1163                     );
1164                     statements.push(stmt);
1165                 } else {
1166                     // If this is not the simple case, then we construct two statements:
1167                     //
1168                     // ```
1169                     // let __argN = __argN;
1170                     // let <pat> = __argN;
1171                     // ```
1172                     //
1173                     // The first statement moves the parameter into the closure and thus ensures
1174                     // that the drop order is correct.
1175                     //
1176                     // The second statement creates the bindings that the user wrote.
1177
1178                     // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1179                     // because the user may have specified a `ref mut` binding in the next
1180                     // statement.
1181                     let (move_pat, move_id) = this.pat_ident_binding_mode(
1182                         desugared_span,
1183                         ident,
1184                         hir::BindingAnnotation::MUT,
1185                     );
1186                     let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1187                     let move_stmt = this.stmt_let_pat(
1188                         None,
1189                         desugared_span,
1190                         Some(move_expr),
1191                         move_pat,
1192                         hir::LocalSource::AsyncFn,
1193                     );
1194
1195                     // Construct the `let <pat> = __argN;` statement. We re-use the original
1196                     // parameter's pattern so that `HirId`s are densely assigned.
1197                     let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1198                     let pattern_stmt = this.stmt_let_pat(
1199                         stmt_attrs,
1200                         desugared_span,
1201                         Some(pattern_expr),
1202                         parameter.pat,
1203                         hir::LocalSource::AsyncFn,
1204                     );
1205
1206                     statements.push(move_stmt);
1207                     statements.push(pattern_stmt);
1208                 };
1209
1210                 parameters.push(new_parameter);
1211             }
1212
1213             let async_expr = this.make_async_expr(
1214                 CaptureBy::Value,
1215                 closure_id,
1216                 None,
1217                 body.span,
1218                 hir::AsyncGeneratorKind::Fn,
1219                 |this| {
1220                     // Create a block from the user's function body:
1221                     let user_body = this.lower_block_expr(body);
1222
1223                     // Transform into `drop-temps { <user-body> }`, an expression:
1224                     let desugared_span =
1225                         this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1226                     let user_body = this.expr_drop_temps(
1227                         desugared_span,
1228                         this.arena.alloc(user_body),
1229                         AttrVec::new(),
1230                     );
1231
1232                     // As noted above, create the final block like
1233                     //
1234                     // ```
1235                     // {
1236                     //   let $param_pattern = $raw_param;
1237                     //   ...
1238                     //   drop-temps { <user-body> }
1239                     // }
1240                     // ```
1241                     let body = this.block_all(
1242                         desugared_span,
1243                         this.arena.alloc_from_iter(statements),
1244                         Some(user_body),
1245                     );
1246
1247                     this.expr_block(body, AttrVec::new())
1248                 },
1249             );
1250
1251             (
1252                 this.arena.alloc_from_iter(parameters),
1253                 this.expr(body.span, async_expr, AttrVec::new()),
1254             )
1255         })
1256     }
1257
1258     fn lower_method_sig(
1259         &mut self,
1260         generics: &Generics,
1261         sig: &FnSig,
1262         id: NodeId,
1263         kind: FnDeclKind,
1264         is_async: Option<(NodeId, Span)>,
1265     ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1266         let header = self.lower_fn_header(sig.header);
1267         let mut itctx = ImplTraitContext::Universal;
1268         let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1269             this.lower_fn_decl(&sig.decl, Some(id), sig.span, kind, is_async)
1270         });
1271         (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1272     }
1273
1274     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1275         hir::FnHeader {
1276             unsafety: self.lower_unsafety(h.unsafety),
1277             asyncness: self.lower_asyncness(h.asyncness),
1278             constness: self.lower_constness(h.constness),
1279             abi: self.lower_extern(h.ext),
1280         }
1281     }
1282
1283     pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1284         abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1285             self.error_on_invalid_abi(abi);
1286             abi::Abi::Rust
1287         })
1288     }
1289
1290     pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1291         match ext {
1292             Extern::None => abi::Abi::Rust,
1293             Extern::Implicit(_) => abi::Abi::FALLBACK,
1294             Extern::Explicit(abi, _) => self.lower_abi(abi),
1295         }
1296     }
1297
1298     fn error_on_invalid_abi(&self, abi: StrLit) {
1299         let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1300             .iter()
1301             .map(|s| Symbol::intern(s))
1302             .collect::<Vec<_>>();
1303         let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1304         self.tcx.sess.emit_err(InvalidAbi {
1305             abi: abi.symbol_unescaped,
1306             span: abi.span,
1307             suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1308                 span: abi.span,
1309                 suggestion: format!("\"{suggested_name}\""),
1310             }),
1311             command: "rustc --print=calling-conventions".to_string(),
1312         });
1313     }
1314
1315     fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1316         match a {
1317             Async::Yes { .. } => hir::IsAsync::Async,
1318             Async::No => hir::IsAsync::NotAsync,
1319         }
1320     }
1321
1322     fn lower_constness(&mut self, c: Const) -> hir::Constness {
1323         match c {
1324             Const::Yes(_) => hir::Constness::Const,
1325             Const::No => hir::Constness::NotConst,
1326         }
1327     }
1328
1329     pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1330         match u {
1331             Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1332             Unsafe::No => hir::Unsafety::Normal,
1333         }
1334     }
1335
1336     /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1337     /// the carried impl trait definitions and bounds.
1338     #[instrument(level = "debug", skip(self, f))]
1339     fn lower_generics<T>(
1340         &mut self,
1341         generics: &Generics,
1342         parent_node_id: NodeId,
1343         itctx: &ImplTraitContext,
1344         f: impl FnOnce(&mut Self) -> T,
1345     ) -> (&'hir hir::Generics<'hir>, T) {
1346         debug_assert!(self.impl_trait_defs.is_empty());
1347         debug_assert!(self.impl_trait_bounds.is_empty());
1348
1349         // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1350         // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1351         // these into hir when we lower thee where clauses), but this makes it quite difficult to
1352         // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1353         // where clauses for `?Sized`.
1354         for pred in &generics.where_clause.predicates {
1355             let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1356                 continue;
1357             };
1358             let compute_is_param = || {
1359                 // Check if the where clause type is a plain type parameter.
1360                 match self
1361                     .resolver
1362                     .get_partial_res(bound_pred.bounded_ty.id)
1363                     .and_then(|r| r.full_res())
1364                 {
1365                     Some(Res::Def(DefKind::TyParam, def_id))
1366                         if bound_pred.bound_generic_params.is_empty() =>
1367                     {
1368                         generics
1369                             .params
1370                             .iter()
1371                             .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1372                     }
1373                     // Either the `bounded_ty` is not a plain type parameter, or
1374                     // it's not found in the generic type parameters list.
1375                     _ => false,
1376                 }
1377             };
1378             // We only need to compute this once per `WherePredicate`, but don't
1379             // need to compute this at all unless there is a Maybe bound.
1380             let mut is_param: Option<bool> = None;
1381             for bound in &bound_pred.bounds {
1382                 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1383                     continue;
1384                 }
1385                 let is_param = *is_param.get_or_insert_with(compute_is_param);
1386                 if !is_param {
1387                     self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1388                 }
1389             }
1390         }
1391
1392         let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1393         predicates.extend(generics.params.iter().filter_map(|param| {
1394             self.lower_generic_bound_predicate(
1395                 param.ident,
1396                 param.id,
1397                 &param.kind,
1398                 &param.bounds,
1399                 itctx,
1400                 PredicateOrigin::GenericParam,
1401             )
1402         }));
1403         predicates.extend(
1404             generics
1405                 .where_clause
1406                 .predicates
1407                 .iter()
1408                 .map(|predicate| self.lower_where_predicate(predicate)),
1409         );
1410
1411         let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1412             self.lower_generic_params_mut(&generics.params).collect();
1413
1414         // Introduce extra lifetimes if late resolution tells us to.
1415         let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1416         params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1417             self.lifetime_res_to_generic_param(ident, node_id, res)
1418         }));
1419
1420         let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1421         let where_clause_span = self.lower_span(generics.where_clause.span);
1422         let span = self.lower_span(generics.span);
1423         let res = f(self);
1424
1425         let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1426         params.extend(impl_trait_defs.into_iter());
1427
1428         let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1429         predicates.extend(impl_trait_bounds.into_iter());
1430
1431         let lowered_generics = self.arena.alloc(hir::Generics {
1432             params: self.arena.alloc_from_iter(params),
1433             predicates: self.arena.alloc_from_iter(predicates),
1434             has_where_clause_predicates,
1435             where_clause_span,
1436             span,
1437         });
1438
1439         (lowered_generics, res)
1440     }
1441
1442     pub(super) fn lower_generic_bound_predicate(
1443         &mut self,
1444         ident: Ident,
1445         id: NodeId,
1446         kind: &GenericParamKind,
1447         bounds: &[GenericBound],
1448         itctx: &ImplTraitContext,
1449         origin: PredicateOrigin,
1450     ) -> Option<hir::WherePredicate<'hir>> {
1451         // Do not create a clause if we do not have anything inside it.
1452         if bounds.is_empty() {
1453             return None;
1454         }
1455
1456         let bounds = self.lower_param_bounds(bounds, itctx);
1457
1458         let ident = self.lower_ident(ident);
1459         let param_span = ident.span;
1460         let span = bounds
1461             .iter()
1462             .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1463                 let bound_span = bound.span();
1464                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1465                 // as we use this method to get a span appropriate for suggestions.
1466                 if !bound_span.can_be_used_for_suggestions() {
1467                     None
1468                 } else if let Some(span) = span {
1469                     Some(span.to(bound_span))
1470                 } else {
1471                     Some(bound_span)
1472                 }
1473             })
1474             .unwrap_or(param_span.shrink_to_hi());
1475         match kind {
1476             GenericParamKind::Const { .. } => None,
1477             GenericParamKind::Type { .. } => {
1478                 let def_id = self.local_def_id(id).to_def_id();
1479                 let hir_id = self.next_id();
1480                 let res = Res::Def(DefKind::TyParam, def_id);
1481                 let ty_path = self.arena.alloc(hir::Path {
1482                     span: param_span,
1483                     res,
1484                     segments: self
1485                         .arena
1486                         .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1487                 });
1488                 let ty_id = self.next_id();
1489                 let bounded_ty =
1490                     self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1491                 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1492                     hir_id: self.next_id(),
1493                     bounded_ty: self.arena.alloc(bounded_ty),
1494                     bounds,
1495                     span,
1496                     bound_generic_params: &[],
1497                     origin,
1498                 }))
1499             }
1500             GenericParamKind::Lifetime => {
1501                 let ident_span = self.lower_span(ident.span);
1502                 let ident = self.lower_ident(ident);
1503                 let lt_id = self.next_node_id();
1504                 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1505                 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1506                     lifetime,
1507                     span,
1508                     bounds,
1509                     in_where_clause: false,
1510                 }))
1511             }
1512         }
1513     }
1514
1515     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1516         match *pred {
1517             WherePredicate::BoundPredicate(WhereBoundPredicate {
1518                 ref bound_generic_params,
1519                 ref bounded_ty,
1520                 ref bounds,
1521                 span,
1522             }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1523                 hir_id: self.next_id(),
1524                 bound_generic_params: self.lower_generic_params(bound_generic_params),
1525                 bounded_ty: self
1526                     .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1527                 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1528                     self.lower_param_bound(
1529                         bound,
1530                         &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1531                     )
1532                 })),
1533                 span: self.lower_span(span),
1534                 origin: PredicateOrigin::WhereClause,
1535             }),
1536             WherePredicate::RegionPredicate(WhereRegionPredicate {
1537                 ref lifetime,
1538                 ref bounds,
1539                 span,
1540             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1541                 span: self.lower_span(span),
1542                 lifetime: self.lower_lifetime(lifetime),
1543                 bounds: self.lower_param_bounds(
1544                     bounds,
1545                     &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1546                 ),
1547                 in_where_clause: true,
1548             }),
1549             WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1550                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1551                     lhs_ty: self
1552                         .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1553                     rhs_ty: self
1554                         .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1555                     span: self.lower_span(span),
1556                 })
1557             }
1558         }
1559     }
1560 }