1 use super::errors::{InvalidAbi, InvalidAbiSuggestion, 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::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_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
28 pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
31 /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
32 /// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
33 /// clause if it exists.
34 fn add_ty_alias_where_clause(
35 generics: &mut ast::Generics,
36 mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
40 where_clauses = (where_clauses.1, where_clauses.0);
42 if where_clauses.0.0 || !where_clauses.1.0 {
43 generics.where_clause.has_where_token = where_clauses.0.0;
44 generics.where_clause.span = where_clauses.0.1;
46 generics.where_clause.has_where_token = where_clauses.1.0;
47 generics.where_clause.span = where_clauses.1.1;
51 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
55 f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
57 let mut lctx = LoweringContext {
60 resolver: self.resolver,
61 arena: self.tcx.hir_arena,
65 attrs: SortedMap::default(),
66 children: Vec::default(),
67 current_hir_id_owner: hir::CRATE_OWNER_ID,
68 item_local_id_counter: hir::ItemLocalId::new(0),
69 node_id_to_local_id: Default::default(),
70 local_id_to_def_id: SortedMap::new(),
71 trait_map: Default::default(),
76 is_in_loop_condition: false,
77 is_in_trait_impl: false,
78 is_in_dyn_type: false,
82 impl_trait_defs: Vec::new(),
83 impl_trait_bounds: Vec::new(),
84 allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
85 allow_gen_future: Some([sym::gen_future, sym::closure_track_caller][..].into()),
86 allow_into_future: Some([sym::into_future][..].into()),
87 generics_def_id_map: Default::default(),
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(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 { 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(
165 ) -> &'hir hir::Mod<'hir> {
166 self.arena.alloc(hir::Mod {
167 spans: hir::ModSpans {
168 inner_span: self.lower_span(spans.inner_span),
169 inject_use_span: self.lower_span(spans.inject_use_span),
171 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
175 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
177 smallvec![hir::ItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }];
178 if let ItemKind::Use(use_tree) = &i.kind {
179 self.lower_item_id_use_tree(use_tree, &mut node_ids);
184 fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
186 UseTreeKind::Nested(nested_vec) => {
187 for &(ref nested, id) in nested_vec {
188 vec.push(hir::ItemId {
189 owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
191 self.lower_item_id_use_tree(nested, vec);
194 UseTreeKind::Simple(..) | UseTreeKind::Glob => {}
198 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
199 let mut ident = i.ident;
200 let vis_span = self.lower_span(i.vis.span);
201 let hir_id = self.lower_node_id(i.id);
202 let attrs = self.lower_attrs(hir_id, &i.attrs);
203 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
204 let item = hir::Item {
205 owner_id: hir_id.expect_owner(),
206 ident: self.lower_ident(ident),
209 span: self.lower_span(i.span),
211 self.arena.alloc(item)
220 attrs: Option<&'hir [Attribute]>,
223 ) -> hir::ItemKind<'hir> {
225 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(*orig_name),
226 ItemKind::Use(use_tree) => {
227 // Start with an empty prefix.
228 let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
230 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
232 ItemKind::Static(t, m, e) => {
233 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
234 hir::ItemKind::Static(ty, *m, body_id)
236 ItemKind::Const(_, t, e) => {
237 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
238 hir::ItemKind::Const(ty, body_id)
240 ItemKind::Fn(box Fn {
241 sig: FnSig { decl, header, span: fn_sig_span },
246 self.with_new_scopes(|this| {
247 this.current_item = Some(ident.span);
249 // Note: we don't need to change the return type from `T` to
250 // `impl Future<Output = T>` here because lower_body
251 // only cares about the input argument patterns in the function
252 // declaration (decl), not the return types.
253 let asyncness = header.asyncness;
254 let body_id = this.lower_maybe_async_body(
262 let itctx = ImplTraitContext::Universal;
263 let (generics, decl) = this.lower_generics(generics, id, &itctx, |this| {
264 let ret_id = asyncness.opt_return_id();
265 this.lower_fn_decl(&decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id)
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(_, 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(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(asm) => hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm)),
288 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: Some(ty), .. }) => {
291 // type Foo = impl Trait
296 // opaque type Foo1: Trait
297 let mut generics = generics.clone();
298 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
299 let (generics, ty) = self.lower_generics(
302 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
303 |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
305 hir::ItemKind::TyAlias(ty, generics)
307 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: None, .. }) => {
308 let mut generics = generics.clone();
309 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
310 let (generics, ty) = self.lower_generics(
313 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
314 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
316 hir::ItemKind::TyAlias(ty, generics)
318 ItemKind::Enum(enum_definition, generics) => {
319 let (generics, variants) = self.lower_generics(
322 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
324 this.arena.alloc_from_iter(
325 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
329 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
331 ItemKind::Struct(struct_def, generics) => {
332 let (generics, struct_def) = self.lower_generics(
335 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
336 |this| this.lower_variant_data(hir_id, struct_def),
338 hir::ItemKind::Struct(struct_def, generics)
340 ItemKind::Union(vdata, generics) => {
341 let (generics, vdata) = self.lower_generics(
344 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
345 |this| this.lower_variant_data(hir_id, vdata),
347 hir::ItemKind::Union(vdata, generics)
349 ItemKind::Impl(box Impl {
354 generics: ast_generics,
359 // Lower the "impl header" first. This ordering is important
360 // for in-band lifetimes! Consider `'a` here:
362 // impl Foo<'a> for u32 {
363 // fn method(&'a self) { .. }
366 // Because we start by lowering the `Foo<'a> for u32`
367 // part, we will add `'a` to the list of generics on
368 // the impl. When we then encounter it later in the
369 // method, it will not be considered an in-band
370 // lifetime to be added, but rather a reference to a
372 let itctx = ImplTraitContext::Universal;
373 let (generics, (trait_ref, lowered_ty)) =
374 self.lower_generics(ast_generics, id, &itctx, |this| {
375 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
376 this.lower_trait_ref(
378 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
382 let lowered_ty = this
383 .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
385 (trait_ref, lowered_ty)
388 let new_impl_items = self
390 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
392 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
393 // to not cause an assertion failure inside the `lower_defaultness` function.
395 let (defaultness, defaultness_span) = self.lower_defaultness(*defaultness, has_val);
396 let polarity = match polarity {
397 ImplPolarity::Positive => ImplPolarity::Positive,
398 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)),
400 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
401 unsafety: self.lower_unsafety(*unsafety),
405 constness: self.lower_constness(*constness),
409 items: new_impl_items,
412 ItemKind::Trait(box Trait { is_auto, unsafety, generics, bounds, items }) => {
413 let (generics, (unsafety, items, bounds)) = self.lower_generics(
416 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
418 let bounds = this.lower_param_bounds(
420 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
422 let items = this.arena.alloc_from_iter(
423 items.iter().map(|item| this.lower_trait_item_ref(item)),
425 let unsafety = this.lower_unsafety(*unsafety);
426 (unsafety, items, bounds)
429 hir::ItemKind::Trait(*is_auto, unsafety, generics, bounds, items)
431 ItemKind::TraitAlias(generics, bounds) => {
432 let (generics, bounds) = self.lower_generics(
435 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
437 this.lower_param_bounds(
439 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
443 hir::ItemKind::TraitAlias(generics, bounds)
445 ItemKind::MacroDef(MacroDef { body, macro_rules }) => {
446 let body = P(self.lower_delim_args(body));
447 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
448 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules: *macro_rules }, macro_kind)
450 ItemKind::MacCall(..) => {
451 panic!("`TyMac` should have been expanded by now")
461 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
462 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
463 (ty, self.lower_const_body(span, body))
466 #[instrument(level = "debug", skip(self))]
474 attrs: Option<&'hir [Attribute]>,
475 ) -> hir::ItemKind<'hir> {
476 let path = &tree.prefix;
477 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
480 UseTreeKind::Simple(rename) => {
481 *ident = tree.ident();
483 // First, apply the prefix to the path.
484 let mut path = Path { segments, span: path.span, tokens: None };
486 // Correctly resolve `self` imports.
487 if path.segments.len() > 1
488 && path.segments.last().unwrap().ident.name == kw::SelfLower
490 let _ = path.segments.pop();
491 if rename.is_none() {
492 *ident = path.segments.last().unwrap().ident;
497 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
498 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
499 hir::ItemKind::Use(path, hir::UseKind::Single)
501 UseTreeKind::Glob => {
502 let res = self.expect_full_res(id);
503 let res = smallvec![self.lower_res(res)];
504 let path = Path { segments, span: path.span, tokens: None };
505 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
506 hir::ItemKind::Use(path, hir::UseKind::Glob)
508 UseTreeKind::Nested(ref trees) => {
509 // Nested imports are desugared into simple imports.
510 // So, if we start with
513 // pub(x) use foo::{a, b};
516 // we will create three items:
519 // pub(x) use foo::a;
520 // pub(x) use foo::b;
521 // pub(x) use foo::{}; // <-- this is called the `ListStem`
524 // The first two are produced by recursively invoking
525 // `lower_use_tree` (and indeed there may be things
526 // like `use foo::{a::{b, c}}` and so forth). They
527 // wind up being directly added to
528 // `self.items`. However, the structure of this
529 // function also requires us to return one item, and
530 // for that we return the `{}` import (called the
533 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
535 // Add all the nested `PathListItem`s to the HIR.
536 for &(ref use_tree, id) in trees {
537 let new_hir_id = self.local_def_id(id);
539 let mut prefix = prefix.clone();
541 // Give the segments new node-ids since they are being cloned.
542 for seg in &mut prefix.segments {
543 // Give the cloned segment the same resolution information
544 // as the old one (this is needed for stability checking).
545 let new_id = self.next_node_id();
546 self.resolver.clone_res(seg.id, new_id);
550 // Each `use` import is an item and thus are owners of the
551 // names in the path. Up to this point the nested import is
552 // the current owner, since we want each desugared import to
553 // own its own names, we have to adjust the owner before
554 // lowering the rest of the import.
555 self.with_hir_id_owner(id, |this| {
556 let mut ident = *ident;
559 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
560 if let Some(attrs) = attrs {
561 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
564 let item = hir::Item {
565 owner_id: hir::OwnerId { def_id: new_hir_id },
566 ident: this.lower_ident(ident),
569 span: this.lower_span(use_tree.span),
571 hir::OwnerNode::Item(this.arena.alloc(item))
576 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
577 let path = self.lower_use_path(res, &prefix, ParamMode::Explicit);
578 hir::ItemKind::Use(path, hir::UseKind::ListStem)
583 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
584 let hir_id = self.lower_node_id(i.id);
585 let owner_id = hir_id.expect_owner();
586 self.lower_attrs(hir_id, &i.attrs);
587 let item = hir::ForeignItem {
589 ident: self.lower_ident(i.ident),
590 kind: match &i.kind {
591 ForeignItemKind::Fn(box Fn { sig, generics, .. }) => {
592 let fdec = &sig.decl;
593 let itctx = ImplTraitContext::Universal;
594 let (generics, (fn_dec, fn_args)) =
595 self.lower_generics(generics, i.id, &itctx, |this| {
597 // Disallow `impl Trait` in foreign items.
602 FnDeclKind::ExternFn,
605 this.lower_fn_params_to_names(fdec),
609 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
611 ForeignItemKind::Static(t, m, _) => {
613 self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
614 hir::ForeignItemKind::Static(ty, *m)
616 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
617 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
619 vis_span: self.lower_span(i.vis.span),
620 span: self.lower_span(i.span),
622 self.arena.alloc(item)
625 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
626 hir::ForeignItemRef {
627 id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
628 ident: self.lower_ident(i.ident),
629 span: self.lower_span(i.span),
633 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
634 let hir_id = self.lower_node_id(v.id);
635 self.lower_attrs(hir_id, &v.attrs);
638 def_id: self.local_def_id(v.id),
639 data: self.lower_variant_data(hir_id, &v.data),
640 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
641 ident: self.lower_ident(v.ident),
642 span: self.lower_span(v.span),
646 fn lower_variant_data(
648 parent_id: hir::HirId,
650 ) -> hir::VariantData<'hir> {
652 VariantData::Struct(fields, recovered) => hir::VariantData::Struct(
654 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
657 VariantData::Tuple(fields, id) => {
658 let ctor_id = self.lower_node_id(*id);
659 self.alias_attrs(ctor_id, parent_id);
660 hir::VariantData::Tuple(
661 self.arena.alloc_from_iter(
662 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
665 self.local_def_id(*id),
668 VariantData::Unit(id) => {
669 let ctor_id = self.lower_node_id(*id);
670 self.alias_attrs(ctor_id, parent_id);
671 hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
676 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
677 let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
678 let t = self.lower_path_ty(
682 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
683 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
687 self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
689 let hir_id = self.lower_node_id(f.id);
690 self.lower_attrs(hir_id, &f.attrs);
692 span: self.lower_span(f.span),
694 def_id: self.local_def_id(f.id),
695 ident: match f.ident {
696 Some(ident) => self.lower_ident(ident),
697 // FIXME(jseyfried): positional field hygiene.
698 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
700 vis_span: self.lower_span(f.vis.span),
705 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
706 let hir_id = self.lower_node_id(i.id);
707 self.lower_attrs(hir_id, &i.attrs);
708 let trait_item_def_id = hir_id.expect_owner();
710 let (generics, kind, has_default) = match &i.kind {
711 AssocItemKind::Const(_, ty, default) => {
712 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
713 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
714 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
716 AssocItemKind::Fn(box Fn { sig, generics, body: None, .. }) => {
717 let asyncness = sig.header.asyncness;
718 let names = self.lower_fn_params_to_names(&sig.decl);
719 let (generics, sig) = self.lower_method_sig(
724 asyncness.opt_return_id(),
726 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
728 AssocItemKind::Fn(box Fn { sig, generics, body: Some(body), .. }) => {
729 let asyncness = sig.header.asyncness;
731 self.lower_maybe_async_body(i.span, hir_id, &sig.decl, asyncness, Some(&body));
732 let (generics, sig) = self.lower_method_sig(
737 asyncness.opt_return_id(),
739 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
741 AssocItemKind::Type(box TyAlias { generics, where_clauses, bounds, ty, .. }) => {
742 let mut generics = generics.clone();
743 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
744 let (generics, kind) = self.lower_generics(
747 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
749 let ty = ty.as_ref().map(|x| {
750 this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
752 hir::TraitItemKind::Type(
753 this.lower_param_bounds(
755 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
761 (generics, kind, ty.is_some())
763 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
766 let item = hir::TraitItem {
767 owner_id: trait_item_def_id,
768 ident: self.lower_ident(i.ident),
771 span: self.lower_span(i.span),
772 defaultness: hir::Defaultness::Default { has_value: has_default },
774 self.arena.alloc(item)
777 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
778 let kind = match &i.kind {
779 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
780 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
781 AssocItemKind::Fn(box Fn { sig, .. }) => {
782 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
784 AssocItemKind::MacCall(..) => unimplemented!(),
786 let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
789 ident: self.lower_ident(i.ident),
790 span: self.lower_span(i.span),
795 /// Construct `ExprKind::Err` for the given `span`.
796 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
797 self.expr(span, hir::ExprKind::Err)
800 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
801 // Since `default impl` is not yet implemented, this is always true in impls.
802 let has_value = true;
803 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
804 let hir_id = self.lower_node_id(i.id);
805 self.lower_attrs(hir_id, &i.attrs);
807 let (generics, kind) = match &i.kind {
808 AssocItemKind::Const(_, ty, expr) => {
809 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
811 hir::Generics::empty(),
812 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
815 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
816 self.current_item = Some(i.span);
817 let asyncness = sig.header.asyncness;
818 let body_id = self.lower_maybe_async_body(
825 let (generics, sig) = self.lower_method_sig(
829 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
830 asyncness.opt_return_id(),
833 (generics, hir::ImplItemKind::Fn(sig, body_id))
835 AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
836 let mut generics = generics.clone();
837 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
841 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
844 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
845 hir::ImplItemKind::Type(ty)
848 let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
849 hir::ImplItemKind::Type(ty)
854 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
857 let item = hir::ImplItem {
858 owner_id: hir_id.expect_owner(),
859 ident: self.lower_ident(i.ident),
862 vis_span: self.lower_span(i.vis.span),
863 span: self.lower_span(i.span),
866 self.arena.alloc(item)
869 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
871 id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
872 ident: self.lower_ident(i.ident),
873 span: self.lower_span(i.span),
874 kind: match &i.kind {
875 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
876 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
877 AssocItemKind::Fn(box Fn { sig, .. }) => {
878 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
880 AssocItemKind::MacCall(..) => unimplemented!(),
882 trait_item_def_id: self
884 .get_partial_res(i.id)
885 .map(|r| r.expect_full_res().def_id()),
889 fn lower_defaultness(
893 ) -> (hir::Defaultness, Option<Span>) {
895 Defaultness::Default(sp) => {
896 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
898 Defaultness::Final => {
900 (hir::Defaultness::Final, None)
907 params: &'hir [hir::Param<'hir>],
908 value: hir::Expr<'hir>,
910 let body = hir::Body {
911 generator_kind: self.generator_kind,
913 value: self.arena.alloc(value),
916 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
917 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
921 pub(super) fn lower_body(
923 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
925 let prev_gen_kind = self.generator_kind.take();
926 let task_context = self.task_context.take();
927 let (parameters, result) = f(self);
928 let body_id = self.record_body(parameters, result);
929 self.task_context = task_context;
930 self.generator_kind = prev_gen_kind;
934 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
935 let hir_id = self.lower_node_id(param.id);
936 self.lower_attrs(hir_id, ¶m.attrs);
939 pat: self.lower_pat(¶m.pat),
940 ty_span: self.lower_span(param.ty.span),
941 span: self.lower_span(param.span),
945 pub(super) fn lower_fn_body(
948 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
950 self.lower_body(|this| {
952 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
958 fn lower_fn_body_block(
962 body: Option<&Block>,
964 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
967 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
969 Some(block) => self.lower_block_expr(block),
970 None => self.expr_err(span),
974 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
975 self.lower_body(|this| {
979 Some(expr) => this.lower_expr_mut(expr),
980 None => this.expr_err(span),
986 fn lower_maybe_async_body(
992 body: Option<&Block>,
994 let (closure_id, body) = match (asyncness, body) {
995 (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
996 _ => return self.lower_fn_body_block(span, decl, body),
999 self.lower_body(|this| {
1000 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1001 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1003 // Async function parameters are lowered into the closure body so that they are
1004 // captured and so that the drop order matches the equivalent non-async functions.
1008 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1014 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1016 // let __arg2 = __arg2;
1017 // let <pattern> = __arg2;
1018 // let __arg1 = __arg1;
1019 // let <pattern> = __arg1;
1020 // let __arg0 = __arg0;
1021 // let <pattern> = __arg0;
1022 // drop-temps { <body> } // see comments later in fn for details
1026 // If `<pattern>` is a simple ident, then it is lowered to a single
1027 // `let <pattern> = <pattern>;` statement as an optimization.
1029 // Note that the body is embedded in `drop-temps`; an
1030 // equivalent desugaring would be `return { <body>
1031 // };`. The key point is that we wish to drop all the
1032 // let-bound variables and temporaries created in the body
1033 // (and its tail expression!) before we drop the
1034 // parameters (c.f. rust-lang/rust#64512).
1035 for (index, parameter) in decl.inputs.iter().enumerate() {
1036 let parameter = this.lower_param(parameter);
1037 let span = parameter.pat.span;
1039 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1040 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1041 let (ident, is_simple_parameter) = match parameter.pat.kind {
1042 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1045 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1046 // we can keep the same name for the parameter.
1047 // This lets rustdoc render it correctly in documentation.
1048 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1049 hir::PatKind::Wild => {
1050 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1053 // Replace the ident for bindings that aren't simple.
1054 let name = format!("__arg{}", index);
1055 let ident = Ident::from_str(&name);
1061 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1063 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1066 // If this is the simple case, this parameter will end up being the same as the
1067 // original parameter, but with a different pattern id.
1068 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1069 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1070 let new_parameter = hir::Param {
1071 hir_id: parameter.hir_id,
1072 pat: new_parameter_pat,
1073 ty_span: this.lower_span(parameter.ty_span),
1074 span: this.lower_span(parameter.span),
1077 if is_simple_parameter {
1078 // If this is the simple case, then we only insert one statement that is
1079 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1080 // `HirId`s are densely assigned.
1081 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1082 let stmt = this.stmt_let_pat(
1087 hir::LocalSource::AsyncFn,
1089 statements.push(stmt);
1091 // If this is not the simple case, then we construct two statements:
1094 // let __argN = __argN;
1095 // let <pat> = __argN;
1098 // The first statement moves the parameter into the closure and thus ensures
1099 // that the drop order is correct.
1101 // The second statement creates the bindings that the user wrote.
1103 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1104 // because the user may have specified a `ref mut` binding in the next
1106 let (move_pat, move_id) = this.pat_ident_binding_mode(
1109 hir::BindingAnnotation::MUT,
1111 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1112 let move_stmt = this.stmt_let_pat(
1117 hir::LocalSource::AsyncFn,
1120 // Construct the `let <pat> = __argN;` statement. We re-use the original
1121 // parameter's pattern so that `HirId`s are densely assigned.
1122 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1123 let pattern_stmt = this.stmt_let_pat(
1128 hir::LocalSource::AsyncFn,
1131 statements.push(move_stmt);
1132 statements.push(pattern_stmt);
1135 parameters.push(new_parameter);
1138 let async_expr = this.make_async_expr(
1144 hir::AsyncGeneratorKind::Fn,
1146 // Create a block from the user's function body:
1147 let user_body = this.lower_block_expr(body);
1149 // Transform into `drop-temps { <user-body> }`, an expression:
1150 let desugared_span =
1151 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1153 this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1155 // As noted above, create the final block like
1159 // let $param_pattern = $raw_param;
1161 // drop-temps { <user-body> }
1164 let body = this.block_all(
1166 this.arena.alloc_from_iter(statements),
1170 this.expr_block(body)
1174 (this.arena.alloc_from_iter(parameters), this.expr(body.span, async_expr))
1178 fn lower_method_sig(
1180 generics: &Generics,
1184 is_async: Option<(NodeId, Span)>,
1185 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1186 let header = self.lower_fn_header(sig.header);
1187 let itctx = ImplTraitContext::Universal;
1188 let (generics, decl) = self.lower_generics(generics, id, &itctx, |this| {
1189 this.lower_fn_decl(&sig.decl, id, sig.span, kind, is_async)
1191 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1194 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1196 unsafety: self.lower_unsafety(h.unsafety),
1197 asyncness: self.lower_asyncness(h.asyncness),
1198 constness: self.lower_constness(h.constness),
1199 abi: self.lower_extern(h.ext),
1203 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1204 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1205 self.error_on_invalid_abi(abi);
1210 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1212 Extern::None => abi::Abi::Rust,
1213 Extern::Implicit(_) => abi::Abi::FALLBACK,
1214 Extern::Explicit(abi, _) => self.lower_abi(abi),
1218 fn error_on_invalid_abi(&self, abi: StrLit) {
1219 let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1221 .map(|s| Symbol::intern(s))
1222 .collect::<Vec<_>>();
1223 let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1224 self.tcx.sess.emit_err(InvalidAbi {
1225 abi: abi.symbol_unescaped,
1227 suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1229 suggestion: format!("\"{suggested_name}\""),
1231 command: "rustc --print=calling-conventions".to_string(),
1235 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1237 Async::Yes { .. } => hir::IsAsync::Async,
1238 Async::No => hir::IsAsync::NotAsync,
1242 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1244 Const::Yes(_) => hir::Constness::Const,
1245 Const::No => hir::Constness::NotConst,
1249 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1251 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1252 Unsafe::No => hir::Unsafety::Normal,
1256 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1257 /// the carried impl trait definitions and bounds.
1258 #[instrument(level = "debug", skip(self, f))]
1259 fn lower_generics<T>(
1261 generics: &Generics,
1262 parent_node_id: NodeId,
1263 itctx: &ImplTraitContext,
1264 f: impl FnOnce(&mut Self) -> T,
1265 ) -> (&'hir hir::Generics<'hir>, T) {
1266 debug_assert!(self.impl_trait_defs.is_empty());
1267 debug_assert!(self.impl_trait_bounds.is_empty());
1269 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1270 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1271 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1272 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1273 // where clauses for `?Sized`.
1274 for pred in &generics.where_clause.predicates {
1275 let WherePredicate::BoundPredicate(bound_pred) = pred else {
1278 let compute_is_param = || {
1279 // Check if the where clause type is a plain type parameter.
1282 .get_partial_res(bound_pred.bounded_ty.id)
1283 .and_then(|r| r.full_res())
1285 Some(Res::Def(DefKind::TyParam, def_id))
1286 if bound_pred.bound_generic_params.is_empty() =>
1291 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1293 // Either the `bounded_ty` is not a plain type parameter, or
1294 // it's not found in the generic type parameters list.
1298 // We only need to compute this once per `WherePredicate`, but don't
1299 // need to compute this at all unless there is a Maybe bound.
1300 let mut is_param: Option<bool> = None;
1301 for bound in &bound_pred.bounds {
1302 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1305 let is_param = *is_param.get_or_insert_with(compute_is_param);
1307 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1312 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1313 predicates.extend(generics.params.iter().filter_map(|param| {
1314 self.lower_generic_bound_predicate(
1320 PredicateOrigin::GenericParam,
1328 .map(|predicate| self.lower_where_predicate(predicate)),
1331 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1332 self.lower_generic_params_mut(&generics.params).collect();
1334 // Introduce extra lifetimes if late resolution tells us to.
1335 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1336 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1337 self.lifetime_res_to_generic_param(ident, node_id, res)
1340 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1341 let where_clause_span = self.lower_span(generics.where_clause.span);
1342 let span = self.lower_span(generics.span);
1345 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1346 params.extend(impl_trait_defs.into_iter());
1348 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1349 predicates.extend(impl_trait_bounds.into_iter());
1351 let lowered_generics = self.arena.alloc(hir::Generics {
1352 params: self.arena.alloc_from_iter(params),
1353 predicates: self.arena.alloc_from_iter(predicates),
1354 has_where_clause_predicates,
1359 (lowered_generics, res)
1362 pub(super) fn lower_generic_bound_predicate(
1366 kind: &GenericParamKind,
1367 bounds: &[GenericBound],
1368 itctx: &ImplTraitContext,
1369 origin: PredicateOrigin,
1370 ) -> Option<hir::WherePredicate<'hir>> {
1371 // Do not create a clause if we do not have anything inside it.
1372 if bounds.is_empty() {
1376 let bounds = self.lower_param_bounds(bounds, itctx);
1378 let ident = self.lower_ident(ident);
1379 let param_span = ident.span;
1382 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1383 let bound_span = bound.span();
1384 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1385 // as we use this method to get a span appropriate for suggestions.
1386 if !bound_span.can_be_used_for_suggestions() {
1388 } else if let Some(span) = span {
1389 Some(span.to(bound_span))
1394 .unwrap_or(param_span.shrink_to_hi());
1396 GenericParamKind::Const { .. } => None,
1397 GenericParamKind::Type { .. } => {
1398 let def_id = self.local_def_id(id).to_def_id();
1399 let hir_id = self.next_id();
1400 let res = Res::Def(DefKind::TyParam, def_id);
1401 let ty_path = self.arena.alloc(hir::Path {
1406 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1408 let ty_id = self.next_id();
1410 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1411 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1412 hir_id: self.next_id(),
1413 bounded_ty: self.arena.alloc(bounded_ty),
1416 bound_generic_params: &[],
1420 GenericParamKind::Lifetime => {
1421 let ident = self.lower_ident(ident);
1422 let lt_id = self.next_node_id();
1423 let lifetime = self.new_named_lifetime(id, lt_id, ident);
1424 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1428 in_where_clause: false,
1434 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1436 WherePredicate::BoundPredicate(WhereBoundPredicate {
1437 bound_generic_params,
1441 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1442 hir_id: self.next_id(),
1443 bound_generic_params: self.lower_generic_params(bound_generic_params),
1445 .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1446 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1447 self.lower_param_bound(
1449 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1452 span: self.lower_span(*span),
1453 origin: PredicateOrigin::WhereClause,
1455 WherePredicate::RegionPredicate(WhereRegionPredicate { lifetime, bounds, span }) => {
1456 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1457 span: self.lower_span(*span),
1458 lifetime: self.lower_lifetime(lifetime),
1459 bounds: self.lower_param_bounds(
1461 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1463 in_where_clause: true,
1466 WherePredicate::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty, span }) => {
1467 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1469 .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1471 .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1472 span: self.lower_span(*span),