1 use super::errors::{InvalidAbi, InvalidAbiSuggestion, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
7 use rustc_ast::visit::AssocCtxt;
9 use rustc_data_structures::sorted_map::SortedMap;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
13 use rustc_hir::PredicateOrigin;
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
16 use rustc_span::lev_distance::find_best_match_for_name;
17 use rustc_span::source_map::DesugaringKind;
18 use rustc_span::symbol::{kw, sym, Ident};
19 use rustc_span::{Span, Symbol};
20 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
22 use thin_vec::ThinVec;
24 pub(super) struct ItemLowerer<'a, 'hir> {
25 pub(super) tcx: TyCtxt<'hir>,
26 pub(super) resolver: &'a mut ResolverAstLowering,
27 pub(super) ast_arena: &'a Arena<'static>,
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,
63 ast_arena: self.ast_arena,
67 attrs: SortedMap::default(),
68 children: Vec::default(),
69 current_hir_id_owner: hir::CRATE_OWNER_ID,
70 item_local_id_counter: hir::ItemLocalId::new(0),
71 node_id_to_local_id: Default::default(),
72 local_id_to_def_id: SortedMap::new(),
73 trait_map: Default::default(),
78 is_in_loop_condition: false,
79 is_in_trait_impl: false,
80 is_in_dyn_type: false,
84 impl_trait_defs: Vec::new(),
85 impl_trait_bounds: Vec::new(),
86 allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
87 allow_gen_future: Some([sym::gen_future, sym::closure_track_caller][..].into()),
88 allow_into_future: Some([sym::into_future][..].into()),
89 generics_def_id_map: Default::default(),
91 lctx.with_hir_id_owner(owner, |lctx| f(lctx));
93 for (def_id, info) in lctx.children {
94 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
95 debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
96 self.owners[def_id] = info;
100 pub(super) fn lower_node(
103 ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
104 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
105 if let hir::MaybeOwner::Phantom = self.owners[def_id] {
106 let node = self.ast_index[def_id];
108 AstOwner::NonOwner => {}
109 AstOwner::Crate(c) => self.lower_crate(c),
110 AstOwner::Item(item) => self.lower_item(item),
111 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
112 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
119 #[instrument(level = "debug", skip(self, c))]
120 fn lower_crate(&mut self, c: &Crate) {
121 debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
122 self.with_lctx(CRATE_NODE_ID, |lctx| {
123 let module = lctx.lower_mod(&c.items, &c.spans);
124 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
125 hir::OwnerNode::Crate(module)
129 #[instrument(level = "debug", skip(self))]
130 fn lower_item(&mut self, item: &Item) {
131 self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
134 fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
135 let def_id = self.resolver.node_id_to_def_id[&item.id];
137 let parent_id = self.tcx.local_parent(def_id);
138 let parent_hir = self.lower_node(parent_id).unwrap();
139 self.with_lctx(item.id, |lctx| {
140 // Evaluate with the lifetimes in `params` in-scope.
141 // This is used to track which lifetimes have already been defined,
142 // and which need to be replicated when lowering an async fn.
143 match parent_hir.node().expect_item().kind {
144 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
145 lctx.is_in_trait_impl = of_trait.is_some();
151 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
152 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
157 fn lower_foreign_item(&mut self, item: &ForeignItem) {
158 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
162 impl<'hir> LoweringContext<'_, 'hir> {
163 pub(super) fn lower_mod(
167 ) -> &'hir hir::Mod<'hir> {
168 self.arena.alloc(hir::Mod {
169 spans: hir::ModSpans {
170 inner_span: self.lower_span(spans.inner_span),
171 inject_use_span: self.lower_span(spans.inject_use_span),
173 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
177 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
179 smallvec![hir::ItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }];
180 if let ItemKind::Use(use_tree) = &i.kind {
181 self.lower_item_id_use_tree(use_tree, &mut node_ids);
186 fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
188 UseTreeKind::Nested(nested_vec) => {
189 for &(ref nested, id) in nested_vec {
190 vec.push(hir::ItemId {
191 owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
193 self.lower_item_id_use_tree(nested, vec);
196 UseTreeKind::Simple(..) | UseTreeKind::Glob => {}
200 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
201 let mut ident = i.ident;
202 let vis_span = self.lower_span(i.vis.span);
203 let hir_id = self.lower_node_id(i.id);
204 let attrs = self.lower_attrs(hir_id, &i.attrs);
205 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
206 let item = hir::Item {
207 owner_id: hir_id.expect_owner(),
208 ident: self.lower_ident(ident),
211 span: self.lower_span(i.span),
213 self.arena.alloc(item)
222 attrs: Option<&'hir [Attribute]>,
225 ) -> hir::ItemKind<'hir> {
227 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(*orig_name),
228 ItemKind::Use(use_tree) => {
229 // Start with an empty prefix.
230 let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
232 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
234 ItemKind::Static(t, m, e) => {
235 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
236 hir::ItemKind::Static(ty, *m, body_id)
238 ItemKind::Const(_, t, e) => {
239 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
240 hir::ItemKind::Const(ty, body_id)
242 ItemKind::Fn(box Fn {
243 sig: FnSig { decl, header, span: fn_sig_span },
248 self.with_new_scopes(|this| {
249 this.current_item = Some(ident.span);
251 // Note: we don't need to change the return type from `T` to
252 // `impl Future<Output = T>` here because lower_body
253 // only cares about the input argument patterns in the function
254 // declaration (decl), not the return types.
255 let asyncness = header.asyncness;
257 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
259 let mut itctx = ImplTraitContext::Universal;
260 let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
261 let ret_id = asyncness.opt_return_id();
262 this.lower_fn_decl(&decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id)
264 let sig = hir::FnSig {
266 header: this.lower_fn_header(*header),
267 span: this.lower_span(*fn_sig_span),
269 hir::ItemKind::Fn(sig, generics, body_id)
272 ItemKind::Mod(_, mod_kind) => match mod_kind {
273 ModKind::Loaded(items, _, spans) => {
274 hir::ItemKind::Mod(self.lower_mod(items, spans))
276 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
278 ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
279 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
282 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
284 ItemKind::GlobalAsm(asm) => hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm)),
285 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: Some(ty), .. }) => {
288 // type Foo = impl Trait
293 // opaque type Foo1: Trait
294 let mut generics = generics.clone();
295 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
296 let (generics, ty) = self.lower_generics(
299 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
300 |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
302 hir::ItemKind::TyAlias(ty, generics)
304 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: None, .. }) => {
305 let mut generics = generics.clone();
306 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
307 let (generics, ty) = self.lower_generics(
310 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
311 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
313 hir::ItemKind::TyAlias(ty, generics)
315 ItemKind::Enum(enum_definition, generics) => {
316 let (generics, variants) = self.lower_generics(
319 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
321 this.arena.alloc_from_iter(
322 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
326 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
328 ItemKind::Struct(struct_def, generics) => {
329 let (generics, struct_def) = self.lower_generics(
332 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
333 |this| this.lower_variant_data(hir_id, struct_def),
335 hir::ItemKind::Struct(struct_def, generics)
337 ItemKind::Union(vdata, generics) => {
338 let (generics, vdata) = self.lower_generics(
341 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
342 |this| this.lower_variant_data(hir_id, vdata),
344 hir::ItemKind::Union(vdata, generics)
346 ItemKind::Impl(box Impl {
351 generics: ast_generics,
356 // Lower the "impl header" first. This ordering is important
357 // for in-band lifetimes! Consider `'a` here:
359 // impl Foo<'a> for u32 {
360 // fn method(&'a self) { .. }
363 // Because we start by lowering the `Foo<'a> for u32`
364 // part, we will add `'a` to the list of generics on
365 // the impl. When we then encounter it later in the
366 // method, it will not be considered an in-band
367 // lifetime to be added, but rather a reference to a
369 let mut itctx = ImplTraitContext::Universal;
370 let (generics, (trait_ref, lowered_ty)) =
371 self.lower_generics(ast_generics, id, &mut itctx, |this| {
372 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
373 this.lower_trait_ref(
375 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
379 let lowered_ty = this
380 .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
382 (trait_ref, lowered_ty)
385 let new_impl_items = self
387 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
389 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
390 // to not cause an assertion failure inside the `lower_defaultness` function.
392 let (defaultness, defaultness_span) = self.lower_defaultness(*defaultness, has_val);
393 let polarity = match polarity {
394 ImplPolarity::Positive => ImplPolarity::Positive,
395 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)),
397 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
398 unsafety: self.lower_unsafety(*unsafety),
402 constness: self.lower_constness(*constness),
406 items: new_impl_items,
409 ItemKind::Trait(box Trait { is_auto, unsafety, generics, bounds, items }) => {
410 let (generics, (unsafety, items, bounds)) = self.lower_generics(
413 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
415 let bounds = this.lower_param_bounds(
417 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
419 let items = this.arena.alloc_from_iter(
420 items.iter().map(|item| this.lower_trait_item_ref(item)),
422 let unsafety = this.lower_unsafety(*unsafety);
423 (unsafety, items, bounds)
426 hir::ItemKind::Trait(*is_auto, unsafety, generics, bounds, items)
428 ItemKind::TraitAlias(generics, bounds) => {
429 let (generics, bounds) = self.lower_generics(
432 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
434 this.lower_param_bounds(
436 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
440 hir::ItemKind::TraitAlias(generics, bounds)
442 ItemKind::MacroDef(MacroDef { body, macro_rules }) => {
443 let body = P(self.lower_delim_args(body));
444 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
445 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules: *macro_rules }, macro_kind)
447 ItemKind::MacCall(..) => {
448 panic!("`TyMac` should have been expanded by now")
458 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
459 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
460 (ty, self.lower_const_body(span, body))
463 #[instrument(level = "debug", skip(self))]
471 attrs: Option<&'hir [Attribute]>,
472 ) -> hir::ItemKind<'hir> {
473 let path = &tree.prefix;
474 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
477 UseTreeKind::Simple(rename) => {
478 *ident = tree.ident();
480 // First, apply the prefix to the path.
481 let mut path = Path { segments, span: path.span, tokens: None };
483 // Correctly resolve `self` imports.
484 if path.segments.len() > 1
485 && path.segments.last().unwrap().ident.name == kw::SelfLower
487 let _ = path.segments.pop();
488 if rename.is_none() {
489 *ident = path.segments.last().unwrap().ident;
494 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
495 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
496 hir::ItemKind::Use(path, hir::UseKind::Single)
498 UseTreeKind::Glob => {
499 let res = self.expect_full_res(id);
500 let res = smallvec![self.lower_res(res)];
501 let path = Path { segments, span: path.span, tokens: None };
502 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
503 hir::ItemKind::Use(path, hir::UseKind::Glob)
505 UseTreeKind::Nested(ref trees) => {
506 // Nested imports are desugared into simple imports.
507 // So, if we start with
510 // pub(x) use foo::{a, b};
513 // we will create three items:
516 // pub(x) use foo::a;
517 // pub(x) use foo::b;
518 // pub(x) use foo::{}; // <-- this is called the `ListStem`
521 // The first two are produced by recursively invoking
522 // `lower_use_tree` (and indeed there may be things
523 // like `use foo::{a::{b, c}}` and so forth). They
524 // wind up being directly added to
525 // `self.items`. However, the structure of this
526 // function also requires us to return one item, and
527 // for that we return the `{}` import (called the
530 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
532 // Add all the nested `PathListItem`s to the HIR.
533 for &(ref use_tree, id) in trees {
534 let new_hir_id = self.local_def_id(id);
536 let mut prefix = prefix.clone();
538 // Give the segments new node-ids since they are being cloned.
539 for seg in &mut prefix.segments {
540 // Give the cloned segment the same resolution information
541 // as the old one (this is needed for stability checking).
542 let new_id = self.next_node_id();
543 self.resolver.clone_res(seg.id, new_id);
547 // Each `use` import is an item and thus are owners of the
548 // names in the path. Up to this point the nested import is
549 // the current owner, since we want each desugared import to
550 // own its own names, we have to adjust the owner before
551 // lowering the rest of the import.
552 self.with_hir_id_owner(id, |this| {
553 let mut ident = *ident;
556 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
557 if let Some(attrs) = attrs {
558 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
561 let item = hir::Item {
562 owner_id: hir::OwnerId { def_id: new_hir_id },
563 ident: this.lower_ident(ident),
566 span: this.lower_span(use_tree.span),
568 hir::OwnerNode::Item(this.arena.alloc(item))
573 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
574 let path = self.lower_use_path(res, &prefix, ParamMode::Explicit);
575 hir::ItemKind::Use(path, hir::UseKind::ListStem)
580 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
581 let hir_id = self.lower_node_id(i.id);
582 let owner_id = hir_id.expect_owner();
583 self.lower_attrs(hir_id, &i.attrs);
584 let item = hir::ForeignItem {
586 ident: self.lower_ident(i.ident),
587 kind: match &i.kind {
588 ForeignItemKind::Fn(box Fn { sig, generics, .. }) => {
589 let fdec = &sig.decl;
590 let mut itctx = ImplTraitContext::Universal;
591 let (generics, (fn_dec, fn_args)) =
592 self.lower_generics(generics, i.id, &mut itctx, |this| {
594 // Disallow `impl Trait` in foreign items.
599 FnDeclKind::ExternFn,
602 this.lower_fn_params_to_names(fdec),
606 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
608 ForeignItemKind::Static(t, m, _) => {
610 self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
611 hir::ForeignItemKind::Static(ty, *m)
613 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
614 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
616 vis_span: self.lower_span(i.vis.span),
617 span: self.lower_span(i.span),
619 self.arena.alloc(item)
622 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
623 hir::ForeignItemRef {
624 id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
625 ident: self.lower_ident(i.ident),
626 span: self.lower_span(i.span),
630 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
631 let hir_id = self.lower_node_id(v.id);
632 self.lower_attrs(hir_id, &v.attrs);
635 def_id: self.local_def_id(v.id),
636 data: self.lower_variant_data(hir_id, &v.data),
637 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
638 ident: self.lower_ident(v.ident),
639 span: self.lower_span(v.span),
643 fn lower_variant_data(
645 parent_id: hir::HirId,
647 ) -> hir::VariantData<'hir> {
649 VariantData::Struct(fields, recovered) => hir::VariantData::Struct(
651 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
654 VariantData::Tuple(fields, id) => {
655 let ctor_id = self.lower_node_id(*id);
656 self.alias_attrs(ctor_id, parent_id);
657 hir::VariantData::Tuple(
658 self.arena.alloc_from_iter(
659 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
662 self.local_def_id(*id),
665 VariantData::Unit(id) => {
666 let ctor_id = self.lower_node_id(*id);
667 self.alias_attrs(ctor_id, parent_id);
668 hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
673 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
674 let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
675 let t = self.lower_path_ty(
679 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
680 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
684 self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
686 let hir_id = self.lower_node_id(f.id);
687 self.lower_attrs(hir_id, &f.attrs);
689 span: self.lower_span(f.span),
691 def_id: self.local_def_id(f.id),
692 ident: match f.ident {
693 Some(ident) => self.lower_ident(ident),
694 // FIXME(jseyfried): positional field hygiene.
695 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
697 vis_span: self.lower_span(f.vis.span),
702 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
703 let hir_id = self.lower_node_id(i.id);
704 let trait_item_def_id = hir_id.expect_owner();
706 let (generics, kind, has_default) = match &i.kind {
707 AssocItemKind::Const(_, ty, default) => {
708 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
709 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
710 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
712 AssocItemKind::Fn(box Fn { sig, generics, body: None, .. }) => {
713 let asyncness = sig.header.asyncness;
714 let names = self.lower_fn_params_to_names(&sig.decl);
715 let (generics, sig) = self.lower_method_sig(
720 asyncness.opt_return_id(),
722 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
724 AssocItemKind::Fn(box Fn { sig, generics, body: Some(body), .. }) => {
725 let asyncness = sig.header.asyncness;
727 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
728 let (generics, sig) = self.lower_method_sig(
733 asyncness.opt_return_id(),
735 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
737 AssocItemKind::Type(box TyAlias { generics, where_clauses, bounds, ty, .. }) => {
738 let mut generics = generics.clone();
739 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
740 let (generics, kind) = self.lower_generics(
743 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
745 let ty = ty.as_ref().map(|x| {
746 this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
748 hir::TraitItemKind::Type(
749 this.lower_param_bounds(
751 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
757 (generics, kind, ty.is_some())
759 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
762 self.lower_attrs(hir_id, &i.attrs);
763 let item = hir::TraitItem {
764 owner_id: trait_item_def_id,
765 ident: self.lower_ident(i.ident),
768 span: self.lower_span(i.span),
769 defaultness: hir::Defaultness::Default { has_value: has_default },
771 self.arena.alloc(item)
774 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
775 let kind = match &i.kind {
776 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
777 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
778 AssocItemKind::Fn(box Fn { sig, .. }) => {
779 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
781 AssocItemKind::MacCall(..) => unimplemented!(),
783 let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
786 ident: self.lower_ident(i.ident),
787 span: self.lower_span(i.span),
792 /// Construct `ExprKind::Err` for the given `span`.
793 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
794 self.expr(span, hir::ExprKind::Err, AttrVec::new())
797 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
798 // Since `default impl` is not yet implemented, this is always true in impls.
799 let has_value = true;
800 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
802 let (generics, kind) = match &i.kind {
803 AssocItemKind::Const(_, ty, expr) => {
804 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
806 hir::Generics::empty(),
807 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
810 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
811 self.current_item = Some(i.span);
812 let asyncness = sig.header.asyncness;
814 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
815 let (generics, sig) = self.lower_method_sig(
819 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
820 asyncness.opt_return_id(),
823 (generics, hir::ImplItemKind::Fn(sig, body_id))
825 AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
826 let mut generics = generics.clone();
827 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
831 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
834 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
835 hir::ImplItemKind::Type(ty)
838 let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
839 hir::ImplItemKind::Type(ty)
844 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
847 let hir_id = self.lower_node_id(i.id);
848 self.lower_attrs(hir_id, &i.attrs);
849 let item = hir::ImplItem {
850 owner_id: hir_id.expect_owner(),
851 ident: self.lower_ident(i.ident),
854 vis_span: self.lower_span(i.vis.span),
855 span: self.lower_span(i.span),
858 self.arena.alloc(item)
861 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
863 id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
864 ident: self.lower_ident(i.ident),
865 span: self.lower_span(i.span),
866 kind: match &i.kind {
867 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
868 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
869 AssocItemKind::Fn(box Fn { sig, .. }) => {
870 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
872 AssocItemKind::MacCall(..) => unimplemented!(),
874 trait_item_def_id: self
876 .get_partial_res(i.id)
877 .map(|r| r.expect_full_res().def_id()),
881 fn lower_defaultness(
885 ) -> (hir::Defaultness, Option<Span>) {
887 Defaultness::Default(sp) => {
888 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
890 Defaultness::Final => {
892 (hir::Defaultness::Final, None)
899 params: &'hir [hir::Param<'hir>],
900 value: hir::Expr<'hir>,
902 let body = hir::Body {
903 generator_kind: self.generator_kind,
905 value: self.arena.alloc(value),
908 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
909 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
913 pub(super) fn lower_body(
915 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
917 let prev_gen_kind = self.generator_kind.take();
918 let task_context = self.task_context.take();
919 let (parameters, result) = f(self);
920 let body_id = self.record_body(parameters, result);
921 self.task_context = task_context;
922 self.generator_kind = prev_gen_kind;
926 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
927 let hir_id = self.lower_node_id(param.id);
928 self.lower_attrs(hir_id, ¶m.attrs);
931 pat: self.lower_pat(¶m.pat),
932 ty_span: self.lower_span(param.ty.span),
933 span: self.lower_span(param.span),
937 pub(super) fn lower_fn_body(
940 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
942 self.lower_body(|this| {
944 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
950 fn lower_fn_body_block(
954 body: Option<&Block>,
956 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
959 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
961 Some(block) => self.lower_block_expr(block),
962 None => self.expr_err(span),
966 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
967 self.lower_body(|this| {
971 Some(expr) => this.lower_expr_mut(expr),
972 None => this.expr_err(span),
978 fn lower_maybe_async_body(
983 body: Option<&Block>,
985 let (closure_id, body) = match (asyncness, body) {
986 (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
987 _ => return self.lower_fn_body_block(span, decl, body),
990 self.lower_body(|this| {
991 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
992 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
994 // Async function parameters are lowered into the closure body so that they are
995 // captured and so that the drop order matches the equivalent non-async functions.
999 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1005 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1007 // let __arg2 = __arg2;
1008 // let <pattern> = __arg2;
1009 // let __arg1 = __arg1;
1010 // let <pattern> = __arg1;
1011 // let __arg0 = __arg0;
1012 // let <pattern> = __arg0;
1013 // drop-temps { <body> } // see comments later in fn for details
1017 // If `<pattern>` is a simple ident, then it is lowered to a single
1018 // `let <pattern> = <pattern>;` statement as an optimization.
1020 // Note that the body is embedded in `drop-temps`; an
1021 // equivalent desugaring would be `return { <body>
1022 // };`. The key point is that we wish to drop all the
1023 // let-bound variables and temporaries created in the body
1024 // (and its tail expression!) before we drop the
1025 // parameters (c.f. rust-lang/rust#64512).
1026 for (index, parameter) in decl.inputs.iter().enumerate() {
1027 let parameter = this.lower_param(parameter);
1028 let span = parameter.pat.span;
1030 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1031 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1032 let (ident, is_simple_parameter) = match parameter.pat.kind {
1033 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1036 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1037 // we can keep the same name for the parameter.
1038 // This lets rustdoc render it correctly in documentation.
1039 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1040 hir::PatKind::Wild => {
1041 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1044 // Replace the ident for bindings that aren't simple.
1045 let name = format!("__arg{}", index);
1046 let ident = Ident::from_str(&name);
1052 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1054 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1057 // If this is the simple case, this parameter will end up being the same as the
1058 // original parameter, but with a different pattern id.
1059 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1060 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1061 let new_parameter = hir::Param {
1062 hir_id: parameter.hir_id,
1063 pat: new_parameter_pat,
1064 ty_span: this.lower_span(parameter.ty_span),
1065 span: this.lower_span(parameter.span),
1068 if is_simple_parameter {
1069 // If this is the simple case, then we only insert one statement that is
1070 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1071 // `HirId`s are densely assigned.
1072 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1073 let stmt = this.stmt_let_pat(
1078 hir::LocalSource::AsyncFn,
1080 statements.push(stmt);
1082 // If this is not the simple case, then we construct two statements:
1085 // let __argN = __argN;
1086 // let <pat> = __argN;
1089 // The first statement moves the parameter into the closure and thus ensures
1090 // that the drop order is correct.
1092 // The second statement creates the bindings that the user wrote.
1094 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1095 // because the user may have specified a `ref mut` binding in the next
1097 let (move_pat, move_id) = this.pat_ident_binding_mode(
1100 hir::BindingAnnotation::MUT,
1102 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1103 let move_stmt = this.stmt_let_pat(
1108 hir::LocalSource::AsyncFn,
1111 // Construct the `let <pat> = __argN;` statement. We re-use the original
1112 // parameter's pattern so that `HirId`s are densely assigned.
1113 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1114 let pattern_stmt = this.stmt_let_pat(
1119 hir::LocalSource::AsyncFn,
1122 statements.push(move_stmt);
1123 statements.push(pattern_stmt);
1126 parameters.push(new_parameter);
1129 let async_expr = this.make_async_expr(
1134 hir::AsyncGeneratorKind::Fn,
1136 // Create a block from the user's function body:
1137 let user_body = this.lower_block_expr(body);
1139 // Transform into `drop-temps { <user-body> }`, an expression:
1140 let desugared_span =
1141 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1142 let user_body = this.expr_drop_temps(
1144 this.arena.alloc(user_body),
1148 // As noted above, create the final block like
1152 // let $param_pattern = $raw_param;
1154 // drop-temps { <user-body> }
1157 let body = this.block_all(
1159 this.arena.alloc_from_iter(statements),
1163 this.expr_block(body, AttrVec::new())
1168 this.arena.alloc_from_iter(parameters),
1169 this.expr(body.span, async_expr, AttrVec::new()),
1174 fn lower_method_sig(
1176 generics: &Generics,
1180 is_async: Option<(NodeId, Span)>,
1181 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1182 let header = self.lower_fn_header(sig.header);
1183 let mut itctx = ImplTraitContext::Universal;
1184 let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1185 this.lower_fn_decl(&sig.decl, id, sig.span, kind, is_async)
1187 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1190 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1192 unsafety: self.lower_unsafety(h.unsafety),
1193 asyncness: self.lower_asyncness(h.asyncness),
1194 constness: self.lower_constness(h.constness),
1195 abi: self.lower_extern(h.ext),
1199 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1200 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1201 self.error_on_invalid_abi(abi);
1206 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1208 Extern::None => abi::Abi::Rust,
1209 Extern::Implicit(_) => abi::Abi::FALLBACK,
1210 Extern::Explicit(abi, _) => self.lower_abi(abi),
1214 fn error_on_invalid_abi(&self, abi: StrLit) {
1215 let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1217 .map(|s| Symbol::intern(s))
1218 .collect::<Vec<_>>();
1219 let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1220 self.tcx.sess.emit_err(InvalidAbi {
1221 abi: abi.symbol_unescaped,
1223 suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1225 suggestion: format!("\"{suggested_name}\""),
1227 command: "rustc --print=calling-conventions".to_string(),
1231 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1233 Async::Yes { .. } => hir::IsAsync::Async,
1234 Async::No => hir::IsAsync::NotAsync,
1238 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1240 Const::Yes(_) => hir::Constness::Const,
1241 Const::No => hir::Constness::NotConst,
1245 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1247 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1248 Unsafe::No => hir::Unsafety::Normal,
1252 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1253 /// the carried impl trait definitions and bounds.
1254 #[instrument(level = "debug", skip(self, f))]
1255 fn lower_generics<T>(
1257 generics: &Generics,
1258 parent_node_id: NodeId,
1259 itctx: &ImplTraitContext,
1260 f: impl FnOnce(&mut Self) -> T,
1261 ) -> (&'hir hir::Generics<'hir>, T) {
1262 debug_assert!(self.impl_trait_defs.is_empty());
1263 debug_assert!(self.impl_trait_bounds.is_empty());
1265 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1266 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1267 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1268 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1269 // where clauses for `?Sized`.
1270 for pred in &generics.where_clause.predicates {
1271 let WherePredicate::BoundPredicate(bound_pred) = pred else {
1274 let compute_is_param = || {
1275 // Check if the where clause type is a plain type parameter.
1278 .get_partial_res(bound_pred.bounded_ty.id)
1279 .and_then(|r| r.full_res())
1281 Some(Res::Def(DefKind::TyParam, def_id))
1282 if bound_pred.bound_generic_params.is_empty() =>
1287 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1289 // Either the `bounded_ty` is not a plain type parameter, or
1290 // it's not found in the generic type parameters list.
1294 // We only need to compute this once per `WherePredicate`, but don't
1295 // need to compute this at all unless there is a Maybe bound.
1296 let mut is_param: Option<bool> = None;
1297 for bound in &bound_pred.bounds {
1298 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1301 let is_param = *is_param.get_or_insert_with(compute_is_param);
1303 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1308 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1309 predicates.extend(generics.params.iter().filter_map(|param| {
1310 self.lower_generic_bound_predicate(
1316 PredicateOrigin::GenericParam,
1324 .map(|predicate| self.lower_where_predicate(predicate)),
1327 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1328 self.lower_generic_params_mut(&generics.params).collect();
1330 // Introduce extra lifetimes if late resolution tells us to.
1331 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1332 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1333 self.lifetime_res_to_generic_param(ident, node_id, res)
1336 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1337 let where_clause_span = self.lower_span(generics.where_clause.span);
1338 let span = self.lower_span(generics.span);
1341 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1342 params.extend(impl_trait_defs.into_iter());
1344 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1345 predicates.extend(impl_trait_bounds.into_iter());
1347 let lowered_generics = self.arena.alloc(hir::Generics {
1348 params: self.arena.alloc_from_iter(params),
1349 predicates: self.arena.alloc_from_iter(predicates),
1350 has_where_clause_predicates,
1355 (lowered_generics, res)
1358 pub(super) fn lower_generic_bound_predicate(
1362 kind: &GenericParamKind,
1363 bounds: &[GenericBound],
1364 itctx: &ImplTraitContext,
1365 origin: PredicateOrigin,
1366 ) -> Option<hir::WherePredicate<'hir>> {
1367 // Do not create a clause if we do not have anything inside it.
1368 if bounds.is_empty() {
1372 let bounds = self.lower_param_bounds(bounds, itctx);
1374 let ident = self.lower_ident(ident);
1375 let param_span = ident.span;
1378 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1379 let bound_span = bound.span();
1380 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1381 // as we use this method to get a span appropriate for suggestions.
1382 if !bound_span.can_be_used_for_suggestions() {
1384 } else if let Some(span) = span {
1385 Some(span.to(bound_span))
1390 .unwrap_or(param_span.shrink_to_hi());
1392 GenericParamKind::Const { .. } => None,
1393 GenericParamKind::Type { .. } => {
1394 let def_id = self.local_def_id(id).to_def_id();
1395 let hir_id = self.next_id();
1396 let res = Res::Def(DefKind::TyParam, def_id);
1397 let ty_path = self.arena.alloc(hir::Path {
1402 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1404 let ty_id = self.next_id();
1406 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1407 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1408 hir_id: self.next_id(),
1409 bounded_ty: self.arena.alloc(bounded_ty),
1412 bound_generic_params: &[],
1416 GenericParamKind::Lifetime => {
1417 let ident = self.lower_ident(ident);
1418 let lt_id = self.next_node_id();
1419 let lifetime = self.new_named_lifetime(id, lt_id, ident);
1420 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1424 in_where_clause: false,
1430 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1432 WherePredicate::BoundPredicate(WhereBoundPredicate {
1433 bound_generic_params,
1437 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1438 hir_id: self.next_id(),
1439 bound_generic_params: self.lower_generic_params(bound_generic_params),
1441 .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1442 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1443 self.lower_param_bound(
1445 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1448 span: self.lower_span(*span),
1449 origin: PredicateOrigin::WhereClause,
1451 WherePredicate::RegionPredicate(WhereRegionPredicate { lifetime, bounds, span }) => {
1452 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1453 span: self.lower_span(*span),
1454 lifetime: self.lower_lifetime(lifetime),
1455 bounds: self.lower_param_bounds(
1457 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1459 in_where_clause: true,
1462 WherePredicate::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty, span }) => {
1463 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1465 .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1467 .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1468 span: self.lower_span(*span),