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