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