1 use super::errors::{InvalidAbi, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
7 use rustc_ast::visit::AssocCtxt;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::sorted_map::SortedMap;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
14 use rustc_hir::PredicateOrigin;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
17 use rustc_span::source_map::DesugaringKind;
18 use rustc_span::symbol::{kw, sym, Ident};
20 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
25 pub(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>>>,
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.
35 fn add_ty_alias_where_clause(
36 generics: &mut ast::Generics,
37 mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
41 where_clauses = (where_clauses.1, where_clauses.0);
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;
47 generics.where_clause.has_where_token = where_clauses.1.0;
48 generics.where_clause.span = where_clauses.1.1;
52 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
56 f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
58 let mut lctx = LoweringContext {
61 resolver: self.resolver,
62 arena: self.tcx.hir_arena,
66 attrs: SortedMap::default(),
67 children: FxHashMap::default(),
68 current_hir_id_owner: CRATE_DEF_ID,
69 item_local_id_counter: hir::ItemLocalId::new(0),
70 node_id_to_local_id: Default::default(),
71 local_id_to_def_id: SortedMap::new(),
72 trait_map: Default::default(),
77 is_in_loop_condition: false,
78 is_in_trait_impl: false,
79 is_in_dyn_type: false,
83 impl_trait_defs: Vec::new(),
84 impl_trait_bounds: Vec::new(),
85 allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
86 allow_gen_future: Some([sym::gen_future][..].into()),
87 allow_into_future: Some([sym::into_future][..].into()),
88 generics_def_id_map: Default::default(),
90 lctx.with_hir_id_owner(owner, |lctx| f(lctx));
92 for (def_id, info) in lctx.children {
93 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
94 debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
95 self.owners[def_id] = info;
99 pub(super) fn lower_node(
102 ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
103 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
104 if let hir::MaybeOwner::Phantom = self.owners[def_id] {
105 let node = self.ast_index[def_id];
107 AstOwner::NonOwner => {}
108 AstOwner::Crate(c) => self.lower_crate(c),
109 AstOwner::Item(item) => self.lower_item(item),
110 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
111 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
118 #[instrument(level = "debug", skip(self, c))]
119 fn lower_crate(&mut self, c: &Crate) {
120 debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
121 self.with_lctx(CRATE_NODE_ID, |lctx| {
122 let module = lctx.lower_mod(&c.items, &c.spans);
123 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
124 hir::OwnerNode::Crate(module)
128 #[instrument(level = "debug", skip(self))]
129 fn lower_item(&mut self, item: &Item) {
130 self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
133 fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
134 let def_id = self.resolver.node_id_to_def_id[&item.id];
136 let parent_id = self.tcx.local_parent(def_id);
137 let parent_hir = self.lower_node(parent_id).unwrap();
138 self.with_lctx(item.id, |lctx| {
139 // Evaluate with the lifetimes in `params` in-scope.
140 // This is used to track which lifetimes have already been defined,
141 // and which need to be replicated when lowering an async fn.
142 match parent_hir.node().expect_item().kind {
143 hir::ItemKind::Impl(hir::Impl { ref of_trait, .. }) => {
144 lctx.is_in_trait_impl = of_trait.is_some();
150 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
151 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
156 fn lower_foreign_item(&mut self, item: &ForeignItem) {
157 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
161 impl<'hir> LoweringContext<'_, 'hir> {
162 pub(super) fn lower_mod(
166 ) -> &'hir hir::Mod<'hir> {
167 self.arena.alloc(hir::Mod {
168 spans: hir::ModSpans {
169 inner_span: self.lower_span(spans.inner_span),
170 inject_use_span: self.lower_span(spans.inject_use_span),
172 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
176 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
177 let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }];
178 if let ItemKind::Use(ref use_tree) = &i.kind {
179 self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
184 fn lower_item_id_use_tree(
188 vec: &mut SmallVec<[hir::ItemId; 1]>,
191 UseTreeKind::Nested(ref nested_vec) => {
192 for &(ref nested, id) in nested_vec {
193 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
194 self.lower_item_id_use_tree(nested, id, vec);
197 UseTreeKind::Glob => {}
198 UseTreeKind::Simple(_, id1, id2) => {
200 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
202 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
208 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
209 let mut ident = i.ident;
210 let vis_span = self.lower_span(i.vis.span);
211 let hir_id = self.lower_node_id(i.id);
212 let attrs = self.lower_attrs(hir_id, &i.attrs);
213 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
214 let item = hir::Item {
215 def_id: hir_id.expect_owner(),
216 ident: self.lower_ident(ident),
219 span: self.lower_span(i.span),
221 self.arena.alloc(item)
230 attrs: Option<&'hir [Attribute]>,
233 ) -> hir::ItemKind<'hir> {
235 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
236 ItemKind::Use(ref use_tree) => {
237 // Start with an empty prefix.
238 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
240 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
242 ItemKind::Static(ref t, m, ref e) => {
243 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
244 hir::ItemKind::Static(ty, m, body_id)
246 ItemKind::Const(_, ref t, ref e) => {
247 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
248 hir::ItemKind::Const(ty, body_id)
250 ItemKind::Fn(box Fn {
251 sig: FnSig { ref decl, header, span: fn_sig_span },
256 self.with_new_scopes(|this| {
257 this.current_item = Some(ident.span);
259 // Note: we don't need to change the return type from `T` to
260 // `impl Future<Output = T>` here because lower_body
261 // only cares about the input argument patterns in the function
262 // declaration (decl), not the return types.
263 let asyncness = header.asyncness;
265 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
267 let itctx = ImplTraitContext::Universal;
268 let (generics, decl) = this.lower_generics(generics, id, itctx, |this| {
269 let ret_id = asyncness.opt_return_id();
270 this.lower_fn_decl(&decl, Some(id), FnDeclKind::Fn, ret_id)
272 let sig = hir::FnSig {
274 header: this.lower_fn_header(header),
275 span: this.lower_span(fn_sig_span),
277 hir::ItemKind::Fn(sig, generics, body_id)
280 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
281 ModKind::Loaded(items, _, spans) => {
282 hir::ItemKind::Mod(self.lower_mod(items, spans))
284 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
286 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
287 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
290 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
292 ItemKind::GlobalAsm(ref asm) => {
293 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
295 ItemKind::TyAlias(box TyAlias {
303 // type Foo = impl Trait
308 // opaque type Foo1: Trait
309 let mut generics = generics.clone();
310 add_ty_alias_where_clause(&mut generics, where_clauses, true);
311 let (generics, ty) = self.lower_generics(
314 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
315 |this| this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy),
317 hir::ItemKind::TyAlias(ty, generics)
319 ItemKind::TyAlias(box TyAlias {
320 ref generics, ref where_clauses, ty: None, ..
322 let mut generics = generics.clone();
323 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
324 let (generics, ty) = self.lower_generics(
327 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
328 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
330 hir::ItemKind::TyAlias(ty, generics)
332 ItemKind::Enum(ref enum_definition, ref generics) => {
333 let (generics, variants) = self.lower_generics(
336 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
338 this.arena.alloc_from_iter(
339 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
343 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
345 ItemKind::Struct(ref struct_def, ref generics) => {
346 let (generics, struct_def) = self.lower_generics(
349 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
350 |this| this.lower_variant_data(hir_id, struct_def),
352 hir::ItemKind::Struct(struct_def, generics)
354 ItemKind::Union(ref vdata, ref generics) => {
355 let (generics, vdata) = self.lower_generics(
358 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
359 |this| this.lower_variant_data(hir_id, vdata),
361 hir::ItemKind::Union(vdata, generics)
363 ItemKind::Impl(box Impl {
368 generics: ref ast_generics,
369 of_trait: ref trait_ref,
371 items: ref impl_items,
373 // Lower the "impl header" first. This ordering is important
374 // for in-band lifetimes! Consider `'a` here:
376 // impl Foo<'a> for u32 {
377 // fn method(&'a self) { .. }
380 // Because we start by lowering the `Foo<'a> for u32`
381 // part, we will add `'a` to the list of generics on
382 // the impl. When we then encounter it later in the
383 // method, it will not be considered an in-band
384 // lifetime to be added, but rather a reference to a
386 let itctx = ImplTraitContext::Universal;
387 let (generics, (trait_ref, lowered_ty)) =
388 self.lower_generics(ast_generics, id, itctx, |this| {
389 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
390 this.lower_trait_ref(
392 ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
396 let lowered_ty = this
397 .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
399 (trait_ref, lowered_ty)
402 let new_impl_items = self
404 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
406 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
407 // to not cause an assertion failure inside the `lower_defaultness` function.
409 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
410 let polarity = match polarity {
411 ImplPolarity::Positive => ImplPolarity::Positive,
412 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
414 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
415 unsafety: self.lower_unsafety(unsafety),
419 constness: self.lower_constness(constness),
423 items: new_impl_items,
426 ItemKind::Trait(box Trait {
433 let (generics, (unsafety, items, bounds)) = self.lower_generics(
436 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
438 let bounds = this.lower_param_bounds(
440 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
442 let items = this.arena.alloc_from_iter(
443 items.iter().map(|item| this.lower_trait_item_ref(item)),
445 let unsafety = this.lower_unsafety(unsafety);
446 (unsafety, items, bounds)
449 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
451 ItemKind::TraitAlias(ref generics, ref bounds) => {
452 let (generics, bounds) = self.lower_generics(
455 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
457 this.lower_param_bounds(
459 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
463 hir::ItemKind::TraitAlias(generics, bounds)
465 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
466 let body = P(self.lower_mac_args(body));
467 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
468 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
470 ItemKind::MacCall(..) => {
471 panic!("`TyMac` should have been expanded by now")
481 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
482 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
483 (ty, self.lower_const_body(span, body))
486 #[instrument(level = "debug", skip(self))]
494 attrs: Option<&'hir [Attribute]>,
495 ) -> hir::ItemKind<'hir> {
496 let path = &tree.prefix;
497 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
500 UseTreeKind::Simple(rename, id1, id2) => {
501 *ident = tree.ident();
503 // First, apply the prefix to the path.
504 let mut path = Path { segments, span: path.span, tokens: None };
506 // Correctly resolve `self` imports.
507 if path.segments.len() > 1
508 && path.segments.last().unwrap().ident.name == kw::SelfLower
510 let _ = path.segments.pop();
511 if rename.is_none() {
512 *ident = path.segments.last().unwrap().ident;
516 let mut resolutions = self.expect_full_res_from_use(id).fuse();
517 // We want to return *something* from this function, so hold onto the first item
519 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
521 // Here, we are looping over namespaces, if they exist for the definition
522 // being imported. We only handle type and value namespaces because we
523 // won't be dealing with macros in the rest of the compiler.
524 // Essentially a single `use` which imports two names is desugared into
526 for new_node_id in [id1, id2] {
527 let new_id = self.local_def_id(new_node_id);
528 let Some(res) = resolutions.next() else {
529 // Associate an HirId to both ids even if there is no resolution.
530 let _old = self.children.insert(
532 hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
534 debug_assert!(_old.is_none());
538 let mut path = path.clone();
539 for seg in &mut path.segments {
540 seg.id = self.next_node_id();
542 let span = path.span;
544 self.with_hir_id_owner(new_node_id, |this| {
545 let res = this.lower_res(res);
546 let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
547 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
548 if let Some(attrs) = attrs {
549 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
552 let item = hir::Item {
554 ident: this.lower_ident(ident),
557 span: this.lower_span(span),
559 hir::OwnerNode::Item(this.arena.alloc(item))
563 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
564 hir::ItemKind::Use(path, hir::UseKind::Single)
566 UseTreeKind::Glob => {
567 let path = self.lower_path(
569 &Path { segments, span: path.span, tokens: None },
572 hir::ItemKind::Use(path, hir::UseKind::Glob)
574 UseTreeKind::Nested(ref trees) => {
575 // Nested imports are desugared into simple imports.
576 // So, if we start with
579 // pub(x) use foo::{a, b};
582 // we will create three items:
585 // pub(x) use foo::a;
586 // pub(x) use foo::b;
587 // pub(x) use foo::{}; // <-- this is called the `ListStem`
590 // The first two are produced by recursively invoking
591 // `lower_use_tree` (and indeed there may be things
592 // like `use foo::{a::{b, c}}` and so forth). They
593 // wind up being directly added to
594 // `self.items`. However, the structure of this
595 // function also requires us to return one item, and
596 // for that we return the `{}` import (called the
599 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
601 // Add all the nested `PathListItem`s to the HIR.
602 for &(ref use_tree, id) in trees {
603 let new_hir_id = self.local_def_id(id);
605 let mut prefix = prefix.clone();
607 // Give the segments new node-ids since they are being cloned.
608 for seg in &mut prefix.segments {
609 seg.id = self.next_node_id();
612 // Each `use` import is an item and thus are owners of the
613 // names in the path. Up to this point the nested import is
614 // the current owner, since we want each desugared import to
615 // own its own names, we have to adjust the owner before
616 // lowering the rest of the import.
617 self.with_hir_id_owner(id, |this| {
618 let mut ident = *ident;
621 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
622 if let Some(attrs) = attrs {
623 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
626 let item = hir::Item {
628 ident: this.lower_ident(ident),
631 span: this.lower_span(use_tree.span),
633 hir::OwnerNode::Item(this.arena.alloc(item))
637 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
638 let res = self.lower_res(res);
639 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
640 hir::ItemKind::Use(path, hir::UseKind::ListStem)
645 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
646 let hir_id = self.lower_node_id(i.id);
647 let def_id = hir_id.expect_owner();
648 self.lower_attrs(hir_id, &i.attrs);
649 let item = hir::ForeignItem {
651 ident: self.lower_ident(i.ident),
653 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
654 let fdec = &sig.decl;
655 let itctx = ImplTraitContext::Universal;
656 let (generics, (fn_dec, fn_args)) =
657 self.lower_generics(generics, i.id, itctx, |this| {
659 // Disallow `impl Trait` in foreign items.
660 this.lower_fn_decl(fdec, None, FnDeclKind::ExternFn, None),
661 this.lower_fn_params_to_names(fdec),
665 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
667 ForeignItemKind::Static(ref t, m, _) => {
669 self.lower_ty(t, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
670 hir::ForeignItemKind::Static(ty, m)
672 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
673 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
675 vis_span: self.lower_span(i.vis.span),
676 span: self.lower_span(i.span),
678 self.arena.alloc(item)
681 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
682 hir::ForeignItemRef {
683 id: hir::ForeignItemId { def_id: self.local_def_id(i.id) },
684 ident: self.lower_ident(i.ident),
685 span: self.lower_span(i.span),
689 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
690 let id = self.lower_node_id(v.id);
691 self.lower_attrs(id, &v.attrs);
694 data: self.lower_variant_data(id, &v.data),
695 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
696 ident: self.lower_ident(v.ident),
697 span: self.lower_span(v.span),
701 fn lower_variant_data(
703 parent_id: hir::HirId,
705 ) -> hir::VariantData<'hir> {
707 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
709 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
712 VariantData::Tuple(ref fields, id) => {
713 let ctor_id = self.lower_node_id(id);
714 self.alias_attrs(ctor_id, parent_id);
715 hir::VariantData::Tuple(
716 self.arena.alloc_from_iter(
717 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
722 VariantData::Unit(id) => {
723 let ctor_id = self.lower_node_id(id);
724 self.alias_attrs(ctor_id, parent_id);
725 hir::VariantData::Unit(ctor_id)
730 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
731 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
732 let t = self.lower_path_ty(
736 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
737 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
741 self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
743 let hir_id = self.lower_node_id(f.id);
744 self.lower_attrs(hir_id, &f.attrs);
746 span: self.lower_span(f.span),
748 ident: match f.ident {
749 Some(ident) => self.lower_ident(ident),
750 // FIXME(jseyfried): positional field hygiene.
751 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
753 vis_span: self.lower_span(f.vis.span),
758 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
759 let hir_id = self.lower_node_id(i.id);
760 let trait_item_def_id = hir_id.expect_owner();
762 let (generics, kind, has_default) = match i.kind {
763 AssocItemKind::Const(_, ref ty, ref default) => {
764 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
765 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
766 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
768 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
769 let names = self.lower_fn_params_to_names(&sig.decl);
770 let (generics, sig) =
771 self.lower_method_sig(generics, sig, i.id, FnDeclKind::Trait, None);
772 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
774 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
775 let asyncness = sig.header.asyncness;
777 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
778 let (generics, sig) = self.lower_method_sig(
783 asyncness.opt_return_id(),
785 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
787 AssocItemKind::TyAlias(box TyAlias {
794 let mut generics = generics.clone();
795 add_ty_alias_where_clause(&mut generics, where_clauses, false);
796 let (generics, kind) = self.lower_generics(
799 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
801 let ty = ty.as_ref().map(|x| {
802 this.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
804 hir::TraitItemKind::Type(
805 this.lower_param_bounds(
807 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
813 (generics, kind, ty.is_some())
815 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
818 self.lower_attrs(hir_id, &i.attrs);
819 let item = hir::TraitItem {
820 def_id: trait_item_def_id,
821 ident: self.lower_ident(i.ident),
824 span: self.lower_span(i.span),
825 defaultness: hir::Defaultness::Default { has_value: has_default },
827 self.arena.alloc(item)
830 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
831 let kind = match &i.kind {
832 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
833 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
834 AssocItemKind::Fn(box Fn { sig, .. }) => {
835 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
837 AssocItemKind::MacCall(..) => unimplemented!(),
839 let id = hir::TraitItemId { def_id: self.local_def_id(i.id) };
842 ident: self.lower_ident(i.ident),
843 span: self.lower_span(i.span),
848 /// Construct `ExprKind::Err` for the given `span`.
849 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
850 self.expr(span, hir::ExprKind::Err, AttrVec::new())
853 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
854 // Since `default impl` is not yet implemented, this is always true in impls.
855 let has_value = true;
856 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
858 let (generics, kind) = match &i.kind {
859 AssocItemKind::Const(_, ty, expr) => {
860 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
862 hir::Generics::empty(),
863 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
866 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
867 self.current_item = Some(i.span);
868 let asyncness = sig.header.asyncness;
870 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
871 let (generics, sig) = self.lower_method_sig(
875 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
876 asyncness.opt_return_id(),
879 (generics, hir::ImplItemKind::Fn(sig, body_id))
881 AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
882 let mut generics = generics.clone();
883 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
887 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
890 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
891 hir::ImplItemKind::TyAlias(ty)
894 let ty = this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy);
895 hir::ImplItemKind::TyAlias(ty)
900 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
903 let hir_id = self.lower_node_id(i.id);
904 self.lower_attrs(hir_id, &i.attrs);
905 let item = hir::ImplItem {
906 def_id: hir_id.expect_owner(),
907 ident: self.lower_ident(i.ident),
910 vis_span: self.lower_span(i.vis.span),
911 span: self.lower_span(i.span),
914 self.arena.alloc(item)
917 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
919 id: hir::ImplItemId { def_id: self.local_def_id(i.id) },
920 ident: self.lower_ident(i.ident),
921 span: self.lower_span(i.span),
922 kind: match &i.kind {
923 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
924 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
925 AssocItemKind::Fn(box Fn { sig, .. }) => {
926 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
928 AssocItemKind::MacCall(..) => unimplemented!(),
930 trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
934 fn lower_defaultness(
938 ) -> (hir::Defaultness, Option<Span>) {
940 Defaultness::Default(sp) => {
941 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
943 Defaultness::Final => {
945 (hir::Defaultness::Final, None)
952 params: &'hir [hir::Param<'hir>],
953 value: hir::Expr<'hir>,
955 let body = hir::Body {
956 generator_kind: self.generator_kind,
958 value: self.arena.alloc(value),
961 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
962 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
966 pub(super) fn lower_body(
968 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
970 let prev_gen_kind = self.generator_kind.take();
971 let task_context = self.task_context.take();
972 let (parameters, result) = f(self);
973 let body_id = self.record_body(parameters, result);
974 self.task_context = task_context;
975 self.generator_kind = prev_gen_kind;
979 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
980 let hir_id = self.lower_node_id(param.id);
981 self.lower_attrs(hir_id, ¶m.attrs);
984 pat: self.lower_pat(¶m.pat),
985 ty_span: self.lower_span(param.ty.span),
986 span: self.lower_span(param.span),
990 pub(super) fn lower_fn_body(
993 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
995 self.lower_body(|this| {
997 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1003 fn lower_fn_body_block(
1007 body: Option<&Block>,
1009 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1012 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1014 Some(block) => self.lower_block_expr(block),
1015 None => self.expr_err(span),
1019 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1020 self.lower_body(|this| {
1024 Some(expr) => this.lower_expr_mut(expr),
1025 None => this.expr_err(span),
1031 fn lower_maybe_async_body(
1036 body: Option<&Block>,
1038 let closure_id = match asyncness {
1039 Async::Yes { closure_id, .. } => closure_id,
1040 Async::No => return self.lower_fn_body_block(span, decl, body),
1043 self.lower_body(|this| {
1044 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1045 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1047 // Async function parameters are lowered into the closure body so that they are
1048 // captured and so that the drop order matches the equivalent non-async functions.
1052 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1058 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1060 // let __arg2 = __arg2;
1061 // let <pattern> = __arg2;
1062 // let __arg1 = __arg1;
1063 // let <pattern> = __arg1;
1064 // let __arg0 = __arg0;
1065 // let <pattern> = __arg0;
1066 // drop-temps { <body> } // see comments later in fn for details
1070 // If `<pattern>` is a simple ident, then it is lowered to a single
1071 // `let <pattern> = <pattern>;` statement as an optimization.
1073 // Note that the body is embedded in `drop-temps`; an
1074 // equivalent desugaring would be `return { <body>
1075 // };`. The key point is that we wish to drop all the
1076 // let-bound variables and temporaries created in the body
1077 // (and its tail expression!) before we drop the
1078 // parameters (c.f. rust-lang/rust#64512).
1079 for (index, parameter) in decl.inputs.iter().enumerate() {
1080 let parameter = this.lower_param(parameter);
1081 let span = parameter.pat.span;
1083 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1084 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1085 let (ident, is_simple_parameter) = match parameter.pat.kind {
1086 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1089 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1090 // we can keep the same name for the parameter.
1091 // This lets rustdoc render it correctly in documentation.
1092 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1093 hir::PatKind::Wild => {
1094 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1097 // Replace the ident for bindings that aren't simple.
1098 let name = format!("__arg{}", index);
1099 let ident = Ident::from_str(&name);
1105 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1107 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1110 // If this is the simple case, this parameter will end up being the same as the
1111 // original parameter, but with a different pattern id.
1112 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1113 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1114 let new_parameter = hir::Param {
1115 hir_id: parameter.hir_id,
1116 pat: new_parameter_pat,
1117 ty_span: this.lower_span(parameter.ty_span),
1118 span: this.lower_span(parameter.span),
1121 if is_simple_parameter {
1122 // If this is the simple case, then we only insert one statement that is
1123 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1124 // `HirId`s are densely assigned.
1125 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1126 let stmt = this.stmt_let_pat(
1131 hir::LocalSource::AsyncFn,
1133 statements.push(stmt);
1135 // If this is not the simple case, then we construct two statements:
1138 // let __argN = __argN;
1139 // let <pat> = __argN;
1142 // The first statement moves the parameter into the closure and thus ensures
1143 // that the drop order is correct.
1145 // The second statement creates the bindings that the user wrote.
1147 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1148 // because the user may have specified a `ref mut` binding in the next
1150 let (move_pat, move_id) = this.pat_ident_binding_mode(
1153 hir::BindingAnnotation::MUT,
1155 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1156 let move_stmt = this.stmt_let_pat(
1161 hir::LocalSource::AsyncFn,
1164 // Construct the `let <pat> = __argN;` statement. We re-use the original
1165 // parameter's pattern so that `HirId`s are densely assigned.
1166 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1167 let pattern_stmt = this.stmt_let_pat(
1172 hir::LocalSource::AsyncFn,
1175 statements.push(move_stmt);
1176 statements.push(pattern_stmt);
1179 parameters.push(new_parameter);
1182 let body_span = body.map_or(span, |b| b.span);
1183 let async_expr = this.make_async_expr(
1188 hir::AsyncGeneratorKind::Fn,
1190 // Create a block from the user's function body:
1191 let user_body = this.lower_block_expr_opt(body_span, body);
1193 // Transform into `drop-temps { <user-body> }`, an expression:
1194 let desugared_span =
1195 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1196 let user_body = this.expr_drop_temps(
1198 this.arena.alloc(user_body),
1202 // As noted above, create the final block like
1206 // let $param_pattern = $raw_param;
1208 // drop-temps { <user-body> }
1211 let body = this.block_all(
1213 this.arena.alloc_from_iter(statements),
1217 this.expr_block(body, AttrVec::new())
1222 this.arena.alloc_from_iter(parameters),
1223 this.expr(body_span, async_expr, AttrVec::new()),
1228 fn lower_method_sig(
1230 generics: &Generics,
1234 is_async: Option<NodeId>,
1235 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1236 let header = self.lower_fn_header(sig.header);
1237 let itctx = ImplTraitContext::Universal;
1238 let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
1239 this.lower_fn_decl(&sig.decl, Some(id), kind, is_async)
1241 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1244 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1246 unsafety: self.lower_unsafety(h.unsafety),
1247 asyncness: self.lower_asyncness(h.asyncness),
1248 constness: self.lower_constness(h.constness),
1249 abi: self.lower_extern(h.ext),
1253 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1254 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1255 self.error_on_invalid_abi(abi);
1260 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1262 Extern::None => abi::Abi::Rust,
1263 Extern::Implicit(_) => abi::Abi::FALLBACK,
1264 Extern::Explicit(abi, _) => self.lower_abi(abi),
1268 fn error_on_invalid_abi(&self, abi: StrLit) {
1269 self.tcx.sess.emit_err(InvalidAbi {
1272 valid_abis: abi::all_names().join(", "),
1276 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1278 Async::Yes { .. } => hir::IsAsync::Async,
1279 Async::No => hir::IsAsync::NotAsync,
1283 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1285 Const::Yes(_) => hir::Constness::Const,
1286 Const::No => hir::Constness::NotConst,
1290 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1292 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1293 Unsafe::No => hir::Unsafety::Normal,
1297 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1298 /// the carried impl trait definitions and bounds.
1299 #[instrument(level = "debug", skip(self, f))]
1300 fn lower_generics<T>(
1302 generics: &Generics,
1303 parent_node_id: NodeId,
1304 itctx: ImplTraitContext,
1305 f: impl FnOnce(&mut Self) -> T,
1306 ) -> (&'hir hir::Generics<'hir>, T) {
1307 debug_assert!(self.impl_trait_defs.is_empty());
1308 debug_assert!(self.impl_trait_bounds.is_empty());
1310 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1311 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1312 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1313 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1314 // where clauses for `?Sized`.
1315 for pred in &generics.where_clause.predicates {
1316 let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1319 let compute_is_param = || {
1320 // Check if the where clause type is a plain type parameter.
1323 .get_partial_res(bound_pred.bounded_ty.id)
1324 .map(|d| (d.base_res(), d.unresolved_segments()))
1326 Some((Res::Def(DefKind::TyParam, def_id), 0))
1327 if bound_pred.bound_generic_params.is_empty() =>
1332 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1334 // Either the `bounded_ty` is not a plain type parameter, or
1335 // it's not found in the generic type parameters list.
1339 // We only need to compute this once per `WherePredicate`, but don't
1340 // need to compute this at all unless there is a Maybe bound.
1341 let mut is_param: Option<bool> = None;
1342 for bound in &bound_pred.bounds {
1343 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1346 let is_param = *is_param.get_or_insert_with(compute_is_param);
1348 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1353 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1354 predicates.extend(generics.params.iter().filter_map(|param| {
1355 self.lower_generic_bound_predicate(
1361 PredicateOrigin::GenericParam,
1369 .map(|predicate| self.lower_where_predicate(predicate)),
1372 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1373 self.lower_generic_params_mut(&generics.params).collect();
1375 // Introduce extra lifetimes if late resolution tells us to.
1376 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1377 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1378 self.lifetime_res_to_generic_param(ident, node_id, res)
1381 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1382 let where_clause_span = self.lower_span(generics.where_clause.span);
1383 let span = self.lower_span(generics.span);
1386 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1387 params.extend(impl_trait_defs.into_iter());
1389 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1390 predicates.extend(impl_trait_bounds.into_iter());
1392 let lowered_generics = self.arena.alloc(hir::Generics {
1393 params: self.arena.alloc_from_iter(params),
1394 predicates: self.arena.alloc_from_iter(predicates),
1395 has_where_clause_predicates,
1400 (lowered_generics, res)
1403 pub(super) fn lower_generic_bound_predicate(
1407 kind: &GenericParamKind,
1408 bounds: &[GenericBound],
1409 itctx: ImplTraitContext,
1410 origin: PredicateOrigin,
1411 ) -> Option<hir::WherePredicate<'hir>> {
1412 // Do not create a clause if we do not have anything inside it.
1413 if bounds.is_empty() {
1417 let bounds = self.lower_param_bounds(bounds, itctx);
1419 let ident = self.lower_ident(ident);
1420 let param_span = ident.span;
1423 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1424 let bound_span = bound.span();
1425 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1426 // as we use this method to get a span appropriate for suggestions.
1427 if !bound_span.can_be_used_for_suggestions() {
1429 } else if let Some(span) = span {
1430 Some(span.to(bound_span))
1435 .unwrap_or(param_span.shrink_to_hi());
1437 GenericParamKind::Const { .. } => None,
1438 GenericParamKind::Type { .. } => {
1439 let def_id = self.local_def_id(id).to_def_id();
1440 let hir_id = self.next_id();
1441 let res = Res::Def(DefKind::TyParam, def_id);
1442 let ty_path = self.arena.alloc(hir::Path {
1447 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1449 let ty_id = self.next_id();
1451 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1452 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1453 bounded_ty: self.arena.alloc(bounded_ty),
1456 bound_generic_params: &[],
1460 GenericParamKind::Lifetime => {
1461 let ident_span = self.lower_span(ident.span);
1462 let ident = self.lower_ident(ident);
1463 let lt_id = self.next_node_id();
1464 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1465 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1469 in_where_clause: false,
1475 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1477 WherePredicate::BoundPredicate(WhereBoundPredicate {
1478 ref bound_generic_params,
1482 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1483 bound_generic_params: self.lower_generic_params(bound_generic_params),
1485 .lower_ty(bounded_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1486 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1487 self.lower_param_bound(
1489 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1492 span: self.lower_span(span),
1493 origin: PredicateOrigin::WhereClause,
1495 WherePredicate::RegionPredicate(WhereRegionPredicate {
1499 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1500 span: self.lower_span(span),
1501 lifetime: self.lower_lifetime(lifetime),
1502 bounds: self.lower_param_bounds(
1504 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1506 in_where_clause: true,
1508 WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1509 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1511 .lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1513 .lower_ty(rhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1514 span: self.lower_span(span),