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()),
89 lctx.with_hir_id_owner(owner, |lctx| f(lctx));
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;
98 pub(super) fn lower_node(
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];
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),
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(lctx.arena.alloc(module))
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)))
132 fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
133 let def_id = self.resolver.node_id_to_def_id[&item.id];
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 { ref of_trait, .. }) => {
143 lctx.is_in_trait_impl = of_trait.is_some();
149 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
150 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
155 fn lower_foreign_item(&mut self, item: &ForeignItem) {
156 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
160 impl<'hir> LoweringContext<'_, 'hir> {
161 pub(super) fn lower_mod(&mut self, items: &[P<Item>], spans: &ModSpans) -> hir::Mod<'hir> {
163 spans: hir::ModSpans {
164 inner_span: self.lower_span(spans.inner_span),
165 inject_use_span: self.lower_span(spans.inject_use_span),
167 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
171 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
172 let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }];
173 if let ItemKind::Use(ref use_tree) = &i.kind {
174 self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
179 fn lower_item_id_use_tree(
183 vec: &mut SmallVec<[hir::ItemId; 1]>,
186 UseTreeKind::Nested(ref nested_vec) => {
187 for &(ref nested, id) in nested_vec {
188 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
189 self.lower_item_id_use_tree(nested, id, vec);
192 UseTreeKind::Glob => {}
193 UseTreeKind::Simple(_, id1, id2) => {
195 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
197 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
203 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
204 let mut ident = i.ident;
205 let vis_span = self.lower_span(i.vis.span);
206 let hir_id = self.lower_node_id(i.id);
207 let attrs = self.lower_attrs(hir_id, &i.attrs);
208 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
209 let item = hir::Item {
210 def_id: hir_id.expect_owner(),
211 ident: self.lower_ident(ident),
214 span: self.lower_span(i.span),
216 self.arena.alloc(item)
225 attrs: Option<&'hir [Attribute]>,
228 ) -> hir::ItemKind<'hir> {
230 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
231 ItemKind::Use(ref use_tree) => {
232 // Start with an empty prefix.
233 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
235 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
237 ItemKind::Static(ref t, m, ref e) => {
238 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
239 hir::ItemKind::Static(ty, m, body_id)
241 ItemKind::Const(_, ref t, ref e) => {
242 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
243 hir::ItemKind::Const(ty, body_id)
245 ItemKind::Fn(box Fn {
246 sig: FnSig { ref decl, header, span: fn_sig_span },
251 self.with_new_scopes(|this| {
252 this.current_item = Some(ident.span);
254 // Note: we don't need to change the return type from `T` to
255 // `impl Future<Output = T>` here because lower_body
256 // only cares about the input argument patterns in the function
257 // declaration (decl), not the return types.
258 let asyncness = header.asyncness;
260 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
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, Some(id), FnDeclKind::Fn, ret_id)
267 let sig = hir::FnSig {
269 header: this.lower_fn_header(header),
270 span: this.lower_span(fn_sig_span),
272 hir::ItemKind::Fn(sig, generics, body_id)
275 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
276 ModKind::Loaded(items, _, spans) => {
277 hir::ItemKind::Mod(self.lower_mod(items, spans))
279 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
281 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
282 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
285 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
287 ItemKind::GlobalAsm(ref asm) => {
288 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
290 ItemKind::TyAlias(box TyAlias {
298 // type Foo = impl Trait
303 // opaque type Foo1: Trait
304 let mut generics = generics.clone();
305 add_ty_alias_where_clause(&mut generics, where_clauses, true);
306 let (generics, ty) = self.lower_generics(
309 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
310 |this| this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy),
312 hir::ItemKind::TyAlias(ty, generics)
314 ItemKind::TyAlias(box TyAlias {
315 ref generics, ref where_clauses, ty: None, ..
317 let mut generics = generics.clone();
318 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
319 let (generics, ty) = self.lower_generics(
322 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
323 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
325 hir::ItemKind::TyAlias(ty, generics)
327 ItemKind::Enum(ref enum_definition, ref generics) => {
328 let (generics, variants) = self.lower_generics(
331 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
333 this.arena.alloc_from_iter(
334 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
338 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
340 ItemKind::Struct(ref struct_def, ref generics) => {
341 let (generics, struct_def) = self.lower_generics(
344 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
345 |this| this.lower_variant_data(hir_id, struct_def),
347 hir::ItemKind::Struct(struct_def, generics)
349 ItemKind::Union(ref vdata, ref generics) => {
350 let (generics, vdata) = self.lower_generics(
353 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
354 |this| this.lower_variant_data(hir_id, vdata),
356 hir::ItemKind::Union(vdata, generics)
358 ItemKind::Impl(box Impl {
363 generics: ref ast_generics,
364 of_trait: ref trait_ref,
366 items: ref impl_items,
368 // Lower the "impl header" first. This ordering is important
369 // for in-band lifetimes! Consider `'a` here:
371 // impl Foo<'a> for u32 {
372 // fn method(&'a self) { .. }
375 // Because we start by lowering the `Foo<'a> for u32`
376 // part, we will add `'a` to the list of generics on
377 // the impl. When we then encounter it later in the
378 // method, it will not be considered an in-band
379 // lifetime to be added, but rather a reference to a
381 let itctx = ImplTraitContext::Universal;
382 let (generics, (trait_ref, lowered_ty)) =
383 self.lower_generics(ast_generics, id, itctx, |this| {
384 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
385 this.lower_trait_ref(
387 ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
391 let lowered_ty = this
392 .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
394 (trait_ref, lowered_ty)
397 let new_impl_items = self
399 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
401 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
402 // to not cause an assertion failure inside the `lower_defaultness` function.
404 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
405 let polarity = match polarity {
406 ImplPolarity::Positive => ImplPolarity::Positive,
407 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
409 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
410 unsafety: self.lower_unsafety(unsafety),
414 constness: self.lower_constness(constness),
418 items: new_impl_items,
421 ItemKind::Trait(box Trait {
428 let (generics, (unsafety, items, bounds)) = self.lower_generics(
431 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
433 let bounds = this.lower_param_bounds(
435 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
437 let items = this.arena.alloc_from_iter(
438 items.iter().map(|item| this.lower_trait_item_ref(item)),
440 let unsafety = this.lower_unsafety(unsafety);
441 (unsafety, items, bounds)
444 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
446 ItemKind::TraitAlias(ref generics, ref bounds) => {
447 let (generics, bounds) = self.lower_generics(
450 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
452 this.lower_param_bounds(
454 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
458 hir::ItemKind::TraitAlias(generics, bounds)
460 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
461 let body = P(self.lower_mac_args(body));
462 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
463 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
465 ItemKind::MacCall(..) => {
466 panic!("`TyMac` should have been expanded by now")
476 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
477 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
478 (ty, self.lower_const_body(span, body))
481 #[instrument(level = "debug", skip(self))]
489 attrs: Option<&'hir [Attribute]>,
490 ) -> hir::ItemKind<'hir> {
491 let path = &tree.prefix;
492 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
495 UseTreeKind::Simple(rename, id1, id2) => {
496 *ident = tree.ident();
498 // First, apply the prefix to the path.
499 let mut path = Path { segments, span: path.span, tokens: None };
501 // Correctly resolve `self` imports.
502 if path.segments.len() > 1
503 && path.segments.last().unwrap().ident.name == kw::SelfLower
505 let _ = path.segments.pop();
506 if rename.is_none() {
507 *ident = path.segments.last().unwrap().ident;
511 let mut resolutions = self.expect_full_res_from_use(id).fuse();
512 // We want to return *something* from this function, so hold onto the first item
514 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
516 // Here, we are looping over namespaces, if they exist for the definition
517 // being imported. We only handle type and value namespaces because we
518 // won't be dealing with macros in the rest of the compiler.
519 // Essentially a single `use` which imports two names is desugared into
521 for new_node_id in [id1, id2] {
522 let new_id = self.local_def_id(new_node_id);
523 let Some(res) = resolutions.next() else {
524 // Associate an HirId to both ids even if there is no resolution.
525 let _old = self.children.insert(
527 hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
529 debug_assert!(_old.is_none());
533 let mut path = path.clone();
534 for seg in &mut path.segments {
535 seg.id = self.next_node_id();
537 let span = path.span;
539 self.with_hir_id_owner(new_node_id, |this| {
540 let res = this.lower_res(res);
541 let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
542 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
543 if let Some(attrs) = attrs {
544 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
547 let item = hir::Item {
549 ident: this.lower_ident(ident),
552 span: this.lower_span(span),
554 hir::OwnerNode::Item(this.arena.alloc(item))
558 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
559 hir::ItemKind::Use(path, hir::UseKind::Single)
561 UseTreeKind::Glob => {
562 let path = self.lower_path(
564 &Path { segments, span: path.span, tokens: None },
567 hir::ItemKind::Use(path, hir::UseKind::Glob)
569 UseTreeKind::Nested(ref trees) => {
570 // Nested imports are desugared into simple imports.
571 // So, if we start with
574 // pub(x) use foo::{a, b};
577 // we will create three items:
580 // pub(x) use foo::a;
581 // pub(x) use foo::b;
582 // pub(x) use foo::{}; // <-- this is called the `ListStem`
585 // The first two are produced by recursively invoking
586 // `lower_use_tree` (and indeed there may be things
587 // like `use foo::{a::{b, c}}` and so forth). They
588 // wind up being directly added to
589 // `self.items`. However, the structure of this
590 // function also requires us to return one item, and
591 // for that we return the `{}` import (called the
594 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
596 // Add all the nested `PathListItem`s to the HIR.
597 for &(ref use_tree, id) in trees {
598 let new_hir_id = self.local_def_id(id);
600 let mut prefix = prefix.clone();
602 // Give the segments new node-ids since they are being cloned.
603 for seg in &mut prefix.segments {
604 seg.id = self.next_node_id();
607 // Each `use` import is an item and thus are owners of the
608 // names in the path. Up to this point the nested import is
609 // the current owner, since we want each desugared import to
610 // own its own names, we have to adjust the owner before
611 // lowering the rest of the import.
612 self.with_hir_id_owner(id, |this| {
613 let mut ident = *ident;
616 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
617 if let Some(attrs) = attrs {
618 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
621 let item = hir::Item {
623 ident: this.lower_ident(ident),
626 span: this.lower_span(use_tree.span),
628 hir::OwnerNode::Item(this.arena.alloc(item))
632 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
633 let res = self.lower_res(res);
634 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
635 hir::ItemKind::Use(path, hir::UseKind::ListStem)
640 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
641 let hir_id = self.lower_node_id(i.id);
642 let def_id = hir_id.expect_owner();
643 self.lower_attrs(hir_id, &i.attrs);
644 let item = hir::ForeignItem {
646 ident: self.lower_ident(i.ident),
648 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
649 let fdec = &sig.decl;
650 let itctx = ImplTraitContext::Universal;
651 let (generics, (fn_dec, fn_args)) =
652 self.lower_generics(generics, i.id, itctx, |this| {
654 // Disallow `impl Trait` in foreign items.
655 this.lower_fn_decl(fdec, None, FnDeclKind::ExternFn, None),
656 this.lower_fn_params_to_names(fdec),
660 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
662 ForeignItemKind::Static(ref t, m, _) => {
664 self.lower_ty(t, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
665 hir::ForeignItemKind::Static(ty, m)
667 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
668 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
670 vis_span: self.lower_span(i.vis.span),
671 span: self.lower_span(i.span),
673 self.arena.alloc(item)
676 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
677 hir::ForeignItemRef {
678 id: hir::ForeignItemId { def_id: self.local_def_id(i.id) },
679 ident: self.lower_ident(i.ident),
680 span: self.lower_span(i.span),
684 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
685 let id = self.lower_node_id(v.id);
686 self.lower_attrs(id, &v.attrs);
689 data: self.lower_variant_data(id, &v.data),
690 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
691 ident: self.lower_ident(v.ident),
692 span: self.lower_span(v.span),
696 fn lower_variant_data(
698 parent_id: hir::HirId,
700 ) -> hir::VariantData<'hir> {
702 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
704 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
707 VariantData::Tuple(ref fields, id) => {
708 let ctor_id = self.lower_node_id(id);
709 self.alias_attrs(ctor_id, parent_id);
710 hir::VariantData::Tuple(
711 self.arena.alloc_from_iter(
712 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
717 VariantData::Unit(id) => {
718 let ctor_id = self.lower_node_id(id);
719 self.alias_attrs(ctor_id, parent_id);
720 hir::VariantData::Unit(ctor_id)
725 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
726 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
727 let t = self.lower_path_ty(
731 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
732 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
736 self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
738 let hir_id = self.lower_node_id(f.id);
739 self.lower_attrs(hir_id, &f.attrs);
741 span: self.lower_span(f.span),
743 ident: match f.ident {
744 Some(ident) => self.lower_ident(ident),
745 // FIXME(jseyfried): positional field hygiene.
746 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
748 vis_span: self.lower_span(f.vis.span),
753 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
754 let hir_id = self.lower_node_id(i.id);
755 let trait_item_def_id = hir_id.expect_owner();
757 let (generics, kind, has_default) = match i.kind {
758 AssocItemKind::Const(_, ref ty, ref default) => {
759 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
760 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
761 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
763 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
764 let names = self.lower_fn_params_to_names(&sig.decl);
765 let (generics, sig) =
766 self.lower_method_sig(generics, sig, i.id, FnDeclKind::Trait, None);
767 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
769 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
770 let asyncness = sig.header.asyncness;
772 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
773 let (generics, sig) = self.lower_method_sig(
778 asyncness.opt_return_id(),
780 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
782 AssocItemKind::TyAlias(box TyAlias {
789 let mut generics = generics.clone();
790 add_ty_alias_where_clause(&mut generics, where_clauses, false);
791 let (generics, kind) = self.lower_generics(
794 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
796 let ty = ty.as_ref().map(|x| {
797 this.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
799 hir::TraitItemKind::Type(
800 this.lower_param_bounds(
802 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
808 (generics, kind, ty.is_some())
810 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
813 self.lower_attrs(hir_id, &i.attrs);
814 let item = hir::TraitItem {
815 def_id: trait_item_def_id,
816 ident: self.lower_ident(i.ident),
819 span: self.lower_span(i.span),
820 defaultness: hir::Defaultness::Default { has_value: has_default },
822 self.arena.alloc(item)
825 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
826 let kind = match &i.kind {
827 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
828 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
829 AssocItemKind::Fn(box Fn { sig, .. }) => {
830 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
832 AssocItemKind::MacCall(..) => unimplemented!(),
834 let id = hir::TraitItemId { def_id: self.local_def_id(i.id) };
837 ident: self.lower_ident(i.ident),
838 span: self.lower_span(i.span),
843 /// Construct `ExprKind::Err` for the given `span`.
844 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
845 self.expr(span, hir::ExprKind::Err, AttrVec::new())
848 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
849 // Since `default impl` is not yet implemented, this is always true in impls.
850 let has_value = true;
851 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
853 let (generics, kind) = match &i.kind {
854 AssocItemKind::Const(_, ty, expr) => {
855 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
857 hir::Generics::empty(),
858 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
861 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
862 self.current_item = Some(i.span);
863 let asyncness = sig.header.asyncness;
865 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
866 let (generics, sig) = self.lower_method_sig(
870 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
871 asyncness.opt_return_id(),
874 (generics, hir::ImplItemKind::Fn(sig, body_id))
876 AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
877 let mut generics = generics.clone();
878 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
882 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
885 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
886 hir::ImplItemKind::TyAlias(ty)
889 let ty = this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy);
890 hir::ImplItemKind::TyAlias(ty)
895 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
898 let hir_id = self.lower_node_id(i.id);
899 self.lower_attrs(hir_id, &i.attrs);
900 let item = hir::ImplItem {
901 def_id: hir_id.expect_owner(),
902 ident: self.lower_ident(i.ident),
905 vis_span: self.lower_span(i.vis.span),
906 span: self.lower_span(i.span),
909 self.arena.alloc(item)
912 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
914 id: hir::ImplItemId { def_id: self.local_def_id(i.id) },
915 ident: self.lower_ident(i.ident),
916 span: self.lower_span(i.span),
917 kind: match &i.kind {
918 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
919 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
920 AssocItemKind::Fn(box Fn { sig, .. }) => {
921 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
923 AssocItemKind::MacCall(..) => unimplemented!(),
925 trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
929 fn lower_defaultness(
933 ) -> (hir::Defaultness, Option<Span>) {
935 Defaultness::Default(sp) => {
936 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
938 Defaultness::Final => {
940 (hir::Defaultness::Final, None)
947 params: &'hir [hir::Param<'hir>],
948 value: hir::Expr<'hir>,
950 let body = hir::Body { generator_kind: self.generator_kind, params, value };
952 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
953 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
957 pub(super) fn lower_body(
959 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
961 let prev_gen_kind = self.generator_kind.take();
962 let task_context = self.task_context.take();
963 let (parameters, result) = f(self);
964 let body_id = self.record_body(parameters, result);
965 self.task_context = task_context;
966 self.generator_kind = prev_gen_kind;
970 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
971 let hir_id = self.lower_node_id(param.id);
972 self.lower_attrs(hir_id, ¶m.attrs);
975 pat: self.lower_pat(¶m.pat),
976 ty_span: self.lower_span(param.ty.span),
977 span: self.lower_span(param.span),
981 pub(super) fn lower_fn_body(
984 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
986 self.lower_body(|this| {
988 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
994 fn lower_fn_body_block(
998 body: Option<&Block>,
1000 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1003 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1005 Some(block) => self.lower_block_expr(block),
1006 None => self.expr_err(span),
1010 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1011 self.lower_body(|this| {
1015 Some(expr) => this.lower_expr_mut(expr),
1016 None => this.expr_err(span),
1022 fn lower_maybe_async_body(
1027 body: Option<&Block>,
1029 let closure_id = match asyncness {
1030 Async::Yes { closure_id, .. } => closure_id,
1031 Async::No => return self.lower_fn_body_block(span, decl, body),
1034 self.lower_body(|this| {
1035 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1036 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1038 // Async function parameters are lowered into the closure body so that they are
1039 // captured and so that the drop order matches the equivalent non-async functions.
1043 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1049 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1051 // let __arg2 = __arg2;
1052 // let <pattern> = __arg2;
1053 // let __arg1 = __arg1;
1054 // let <pattern> = __arg1;
1055 // let __arg0 = __arg0;
1056 // let <pattern> = __arg0;
1057 // drop-temps { <body> } // see comments later in fn for details
1061 // If `<pattern>` is a simple ident, then it is lowered to a single
1062 // `let <pattern> = <pattern>;` statement as an optimization.
1064 // Note that the body is embedded in `drop-temps`; an
1065 // equivalent desugaring would be `return { <body>
1066 // };`. The key point is that we wish to drop all the
1067 // let-bound variables and temporaries created in the body
1068 // (and its tail expression!) before we drop the
1069 // parameters (c.f. rust-lang/rust#64512).
1070 for (index, parameter) in decl.inputs.iter().enumerate() {
1071 let parameter = this.lower_param(parameter);
1072 let span = parameter.pat.span;
1074 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1075 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1076 let (ident, is_simple_parameter) = match parameter.pat.kind {
1077 hir::PatKind::Binding(
1078 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
1083 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1084 // we can keep the same name for the parameter.
1085 // This lets rustdoc render it correctly in documentation.
1086 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1087 hir::PatKind::Wild => {
1088 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1091 // Replace the ident for bindings that aren't simple.
1092 let name = format!("__arg{}", index);
1093 let ident = Ident::from_str(&name);
1099 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1101 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1104 // If this is the simple case, this parameter will end up being the same as the
1105 // original parameter, but with a different pattern id.
1106 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1107 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1108 let new_parameter = hir::Param {
1109 hir_id: parameter.hir_id,
1110 pat: new_parameter_pat,
1111 ty_span: this.lower_span(parameter.ty_span),
1112 span: this.lower_span(parameter.span),
1115 if is_simple_parameter {
1116 // If this is the simple case, then we only insert one statement that is
1117 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1118 // `HirId`s are densely assigned.
1119 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1120 let stmt = this.stmt_let_pat(
1125 hir::LocalSource::AsyncFn,
1127 statements.push(stmt);
1129 // If this is not the simple case, then we construct two statements:
1132 // let __argN = __argN;
1133 // let <pat> = __argN;
1136 // The first statement moves the parameter into the closure and thus ensures
1137 // that the drop order is correct.
1139 // The second statement creates the bindings that the user wrote.
1141 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1142 // because the user may have specified a `ref mut` binding in the next
1144 let (move_pat, move_id) = this.pat_ident_binding_mode(
1147 hir::BindingAnnotation::Mutable,
1149 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1150 let move_stmt = this.stmt_let_pat(
1155 hir::LocalSource::AsyncFn,
1158 // Construct the `let <pat> = __argN;` statement. We re-use the original
1159 // parameter's pattern so that `HirId`s are densely assigned.
1160 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1161 let pattern_stmt = this.stmt_let_pat(
1166 hir::LocalSource::AsyncFn,
1169 statements.push(move_stmt);
1170 statements.push(pattern_stmt);
1173 parameters.push(new_parameter);
1176 let body_span = body.map_or(span, |b| b.span);
1177 let async_expr = this.make_async_expr(
1182 hir::AsyncGeneratorKind::Fn,
1184 // Create a block from the user's function body:
1185 let user_body = this.lower_block_expr_opt(body_span, body);
1187 // Transform into `drop-temps { <user-body> }`, an expression:
1188 let desugared_span =
1189 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1190 let user_body = this.expr_drop_temps(
1192 this.arena.alloc(user_body),
1196 // As noted above, create the final block like
1200 // let $param_pattern = $raw_param;
1202 // drop-temps { <user-body> }
1205 let body = this.block_all(
1207 this.arena.alloc_from_iter(statements),
1211 this.expr_block(body, AttrVec::new())
1216 this.arena.alloc_from_iter(parameters),
1217 this.expr(body_span, async_expr, AttrVec::new()),
1222 fn lower_method_sig(
1224 generics: &Generics,
1228 is_async: Option<NodeId>,
1229 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1230 let header = self.lower_fn_header(sig.header);
1231 let itctx = ImplTraitContext::Universal;
1232 let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
1233 this.lower_fn_decl(&sig.decl, Some(id), kind, is_async)
1235 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1238 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1240 unsafety: self.lower_unsafety(h.unsafety),
1241 asyncness: self.lower_asyncness(h.asyncness),
1242 constness: self.lower_constness(h.constness),
1243 abi: self.lower_extern(h.ext),
1247 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1248 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1249 self.error_on_invalid_abi(abi);
1254 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1256 Extern::None => abi::Abi::Rust,
1257 Extern::Implicit(_) => abi::Abi::FALLBACK,
1258 Extern::Explicit(abi, _) => self.lower_abi(abi),
1262 fn error_on_invalid_abi(&self, abi: StrLit) {
1263 self.tcx.sess.emit_err(InvalidAbi {
1266 valid_abis: abi::all_names().join(", "),
1270 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1272 Async::Yes { .. } => hir::IsAsync::Async,
1273 Async::No => hir::IsAsync::NotAsync,
1277 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1279 Const::Yes(_) => hir::Constness::Const,
1280 Const::No => hir::Constness::NotConst,
1284 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1286 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1287 Unsafe::No => hir::Unsafety::Normal,
1291 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1292 /// the carried impl trait definitions and bounds.
1293 #[instrument(level = "debug", skip(self, f))]
1294 fn lower_generics<T>(
1296 generics: &Generics,
1297 parent_node_id: NodeId,
1298 itctx: ImplTraitContext,
1299 f: impl FnOnce(&mut Self) -> T,
1300 ) -> (&'hir hir::Generics<'hir>, T) {
1301 debug_assert!(self.impl_trait_defs.is_empty());
1302 debug_assert!(self.impl_trait_bounds.is_empty());
1304 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1305 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1306 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1307 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1308 // where clauses for `?Sized`.
1309 for pred in &generics.where_clause.predicates {
1310 let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1313 let compute_is_param = || {
1314 // Check if the where clause type is a plain type parameter.
1317 .get_partial_res(bound_pred.bounded_ty.id)
1318 .map(|d| (d.base_res(), d.unresolved_segments()))
1320 Some((Res::Def(DefKind::TyParam, def_id), 0))
1321 if bound_pred.bound_generic_params.is_empty() =>
1326 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1328 // Either the `bounded_ty` is not a plain type parameter, or
1329 // it's not found in the generic type parameters list.
1333 // We only need to compute this once per `WherePredicate`, but don't
1334 // need to compute this at all unless there is a Maybe bound.
1335 let mut is_param: Option<bool> = None;
1336 for bound in &bound_pred.bounds {
1337 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1340 let is_param = *is_param.get_or_insert_with(compute_is_param);
1342 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1347 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1348 predicates.extend(generics.params.iter().filter_map(|param| {
1349 self.lower_generic_bound_predicate(
1355 PredicateOrigin::GenericParam,
1363 .map(|predicate| self.lower_where_predicate(predicate)),
1366 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1367 self.lower_generic_params_mut(&generics.params).collect();
1369 // Introduce extra lifetimes if late resolution tells us to.
1370 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1371 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1372 self.lifetime_res_to_generic_param(ident, node_id, res)
1375 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1376 let where_clause_span = self.lower_span(generics.where_clause.span);
1377 let span = self.lower_span(generics.span);
1380 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1381 params.extend(impl_trait_defs.into_iter());
1383 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1384 predicates.extend(impl_trait_bounds.into_iter());
1386 let lowered_generics = self.arena.alloc(hir::Generics {
1387 params: self.arena.alloc_from_iter(params),
1388 predicates: self.arena.alloc_from_iter(predicates),
1389 has_where_clause_predicates,
1394 (lowered_generics, res)
1397 pub(super) fn lower_generic_bound_predicate(
1401 kind: &GenericParamKind,
1402 bounds: &[GenericBound],
1403 itctx: ImplTraitContext,
1404 origin: PredicateOrigin,
1405 ) -> Option<hir::WherePredicate<'hir>> {
1406 // Do not create a clause if we do not have anything inside it.
1407 if bounds.is_empty() {
1411 let bounds = self.lower_param_bounds(bounds, itctx);
1413 let ident = self.lower_ident(ident);
1414 let param_span = ident.span;
1417 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1418 let bound_span = bound.span();
1419 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1420 // as we use this method to get a span appropriate for suggestions.
1421 if !bound_span.can_be_used_for_suggestions() {
1423 } else if let Some(span) = span {
1424 Some(span.to(bound_span))
1429 .unwrap_or(param_span.shrink_to_hi());
1431 GenericParamKind::Const { .. } => None,
1432 GenericParamKind::Type { .. } => {
1433 let def_id = self.local_def_id(id).to_def_id();
1434 let ty_path = self.arena.alloc(hir::Path {
1436 res: Res::Def(DefKind::TyParam, def_id),
1437 segments: self.arena.alloc_from_iter([hir::PathSegment::from_ident(ident)]),
1439 let ty_id = self.next_id();
1441 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1442 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1443 bounded_ty: self.arena.alloc(bounded_ty),
1446 bound_generic_params: &[],
1450 GenericParamKind::Lifetime => {
1451 let ident_span = self.lower_span(ident.span);
1452 let ident = self.lower_ident(ident);
1453 let lt_id = self.next_node_id();
1454 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1455 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1459 in_where_clause: false,
1465 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1467 WherePredicate::BoundPredicate(WhereBoundPredicate {
1468 ref bound_generic_params,
1472 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1473 bound_generic_params: self.lower_generic_params(bound_generic_params),
1475 .lower_ty(bounded_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1476 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1477 self.lower_param_bound(
1479 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1482 span: self.lower_span(span),
1483 origin: PredicateOrigin::WhereClause,
1485 WherePredicate::RegionPredicate(WhereRegionPredicate {
1489 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1490 span: self.lower_span(span),
1491 lifetime: self.lower_lifetime(lifetime),
1492 bounds: self.lower_param_bounds(
1494 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1496 in_where_clause: true,
1498 WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1499 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1501 .lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1503 .lower_ty(rhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1504 span: self.lower_span(span),