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