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;
256 let body_id = this.lower_maybe_async_body(
264 let mut itctx = ImplTraitContext::Universal;
265 let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
266 let ret_id = asyncness.opt_return_id();
267 this.lower_fn_decl(&decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id)
269 let sig = hir::FnSig {
271 header: this.lower_fn_header(*header),
272 span: this.lower_span(*fn_sig_span),
274 hir::ItemKind::Fn(sig, generics, body_id)
277 ItemKind::Mod(_, mod_kind) => match mod_kind {
278 ModKind::Loaded(items, _, spans) => {
279 hir::ItemKind::Mod(self.lower_mod(items, spans))
281 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
283 ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
284 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
287 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
289 ItemKind::GlobalAsm(asm) => hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm)),
290 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: Some(ty), .. }) => {
293 // type Foo = impl Trait
298 // opaque type Foo1: Trait
299 let mut generics = generics.clone();
300 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
301 let (generics, ty) = self.lower_generics(
304 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
305 |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
307 hir::ItemKind::TyAlias(ty, generics)
309 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: None, .. }) => {
310 let mut generics = generics.clone();
311 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
312 let (generics, ty) = self.lower_generics(
315 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
316 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
318 hir::ItemKind::TyAlias(ty, generics)
320 ItemKind::Enum(enum_definition, generics) => {
321 let (generics, variants) = self.lower_generics(
324 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
326 this.arena.alloc_from_iter(
327 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
331 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
333 ItemKind::Struct(struct_def, generics) => {
334 let (generics, struct_def) = self.lower_generics(
337 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
338 |this| this.lower_variant_data(hir_id, struct_def),
340 hir::ItemKind::Struct(struct_def, generics)
342 ItemKind::Union(vdata, generics) => {
343 let (generics, vdata) = self.lower_generics(
346 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
347 |this| this.lower_variant_data(hir_id, vdata),
349 hir::ItemKind::Union(vdata, generics)
351 ItemKind::Impl(box Impl {
356 generics: ast_generics,
361 // Lower the "impl header" first. This ordering is important
362 // for in-band lifetimes! Consider `'a` here:
364 // impl Foo<'a> for u32 {
365 // fn method(&'a self) { .. }
368 // Because we start by lowering the `Foo<'a> for u32`
369 // part, we will add `'a` to the list of generics on
370 // the impl. When we then encounter it later in the
371 // method, it will not be considered an in-band
372 // lifetime to be added, but rather a reference to a
374 let mut itctx = ImplTraitContext::Universal;
375 let (generics, (trait_ref, lowered_ty)) =
376 self.lower_generics(ast_generics, id, &mut itctx, |this| {
377 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
378 this.lower_trait_ref(
380 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
384 let lowered_ty = this
385 .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
387 (trait_ref, lowered_ty)
390 let new_impl_items = self
392 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
394 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
395 // to not cause an assertion failure inside the `lower_defaultness` function.
397 let (defaultness, defaultness_span) = self.lower_defaultness(*defaultness, has_val);
398 let polarity = match polarity {
399 ImplPolarity::Positive => ImplPolarity::Positive,
400 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)),
402 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
403 unsafety: self.lower_unsafety(*unsafety),
407 constness: self.lower_constness(*constness),
411 items: new_impl_items,
414 ItemKind::Trait(box Trait { is_auto, unsafety, generics, bounds, items }) => {
415 let (generics, (unsafety, items, bounds)) = self.lower_generics(
418 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
420 let bounds = this.lower_param_bounds(
422 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
424 let items = this.arena.alloc_from_iter(
425 items.iter().map(|item| this.lower_trait_item_ref(item)),
427 let unsafety = this.lower_unsafety(*unsafety);
428 (unsafety, items, bounds)
431 hir::ItemKind::Trait(*is_auto, unsafety, generics, bounds, items)
433 ItemKind::TraitAlias(generics, bounds) => {
434 let (generics, bounds) = self.lower_generics(
437 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
439 this.lower_param_bounds(
441 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
445 hir::ItemKind::TraitAlias(generics, bounds)
447 ItemKind::MacroDef(MacroDef { body, macro_rules }) => {
448 let body = P(self.lower_delim_args(body));
449 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
450 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules: *macro_rules }, macro_kind)
452 ItemKind::MacCall(..) => {
453 panic!("`TyMac` should have been expanded by now")
463 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
464 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
465 (ty, self.lower_const_body(span, body))
468 #[instrument(level = "debug", skip(self))]
476 attrs: Option<&'hir [Attribute]>,
477 ) -> hir::ItemKind<'hir> {
478 let path = &tree.prefix;
479 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
482 UseTreeKind::Simple(rename) => {
483 *ident = tree.ident();
485 // First, apply the prefix to the path.
486 let mut path = Path { segments, span: path.span, tokens: None };
488 // Correctly resolve `self` imports.
489 if path.segments.len() > 1
490 && path.segments.last().unwrap().ident.name == kw::SelfLower
492 let _ = path.segments.pop();
493 if rename.is_none() {
494 *ident = path.segments.last().unwrap().ident;
499 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
500 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
501 hir::ItemKind::Use(path, hir::UseKind::Single)
503 UseTreeKind::Glob => {
504 let res = self.expect_full_res(id);
505 let res = smallvec![self.lower_res(res)];
506 let path = Path { segments, span: path.span, tokens: None };
507 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
508 hir::ItemKind::Use(path, hir::UseKind::Glob)
510 UseTreeKind::Nested(ref trees) => {
511 // Nested imports are desugared into simple imports.
512 // So, if we start with
515 // pub(x) use foo::{a, b};
518 // we will create three items:
521 // pub(x) use foo::a;
522 // pub(x) use foo::b;
523 // pub(x) use foo::{}; // <-- this is called the `ListStem`
526 // The first two are produced by recursively invoking
527 // `lower_use_tree` (and indeed there may be things
528 // like `use foo::{a::{b, c}}` and so forth). They
529 // wind up being directly added to
530 // `self.items`. However, the structure of this
531 // function also requires us to return one item, and
532 // for that we return the `{}` import (called the
535 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
537 // Add all the nested `PathListItem`s to the HIR.
538 for &(ref use_tree, id) in trees {
539 let new_hir_id = self.local_def_id(id);
541 let mut prefix = prefix.clone();
543 // Give the segments new node-ids since they are being cloned.
544 for seg in &mut prefix.segments {
545 // Give the cloned segment the same resolution information
546 // as the old one (this is needed for stability checking).
547 let new_id = self.next_node_id();
548 self.resolver.clone_res(seg.id, new_id);
552 // Each `use` import is an item and thus are owners of the
553 // names in the path. Up to this point the nested import is
554 // the current owner, since we want each desugared import to
555 // own its own names, we have to adjust the owner before
556 // lowering the rest of the import.
557 self.with_hir_id_owner(id, |this| {
558 let mut ident = *ident;
561 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
562 if let Some(attrs) = attrs {
563 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
566 let item = hir::Item {
567 owner_id: hir::OwnerId { def_id: new_hir_id },
568 ident: this.lower_ident(ident),
571 span: this.lower_span(use_tree.span),
573 hir::OwnerNode::Item(this.arena.alloc(item))
578 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
579 let path = self.lower_use_path(res, &prefix, ParamMode::Explicit);
580 hir::ItemKind::Use(path, hir::UseKind::ListStem)
585 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
586 let hir_id = self.lower_node_id(i.id);
587 let owner_id = hir_id.expect_owner();
588 self.lower_attrs(hir_id, &i.attrs);
589 let item = hir::ForeignItem {
591 ident: self.lower_ident(i.ident),
592 kind: match &i.kind {
593 ForeignItemKind::Fn(box Fn { sig, generics, .. }) => {
594 let fdec = &sig.decl;
595 let mut itctx = ImplTraitContext::Universal;
596 let (generics, (fn_dec, fn_args)) =
597 self.lower_generics(generics, i.id, &mut itctx, |this| {
599 // Disallow `impl Trait` in foreign items.
604 FnDeclKind::ExternFn,
607 this.lower_fn_params_to_names(fdec),
611 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
613 ForeignItemKind::Static(t, m, _) => {
615 self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
616 hir::ForeignItemKind::Static(ty, *m)
618 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
619 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
621 vis_span: self.lower_span(i.vis.span),
622 span: self.lower_span(i.span),
624 self.arena.alloc(item)
627 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
628 hir::ForeignItemRef {
629 id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
630 ident: self.lower_ident(i.ident),
631 span: self.lower_span(i.span),
635 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
636 let hir_id = self.lower_node_id(v.id);
637 self.lower_attrs(hir_id, &v.attrs);
640 def_id: self.local_def_id(v.id),
641 data: self.lower_variant_data(hir_id, &v.data),
642 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
643 ident: self.lower_ident(v.ident),
644 span: self.lower_span(v.span),
648 fn lower_variant_data(
650 parent_id: hir::HirId,
652 ) -> hir::VariantData<'hir> {
654 VariantData::Struct(fields, recovered) => hir::VariantData::Struct(
656 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
659 VariantData::Tuple(fields, id) => {
660 let ctor_id = self.lower_node_id(*id);
661 self.alias_attrs(ctor_id, parent_id);
662 hir::VariantData::Tuple(
663 self.arena.alloc_from_iter(
664 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
667 self.local_def_id(*id),
670 VariantData::Unit(id) => {
671 let ctor_id = self.lower_node_id(*id);
672 self.alias_attrs(ctor_id, parent_id);
673 hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
678 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
679 let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
680 let t = self.lower_path_ty(
684 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
685 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
689 self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
691 let hir_id = self.lower_node_id(f.id);
692 self.lower_attrs(hir_id, &f.attrs);
694 span: self.lower_span(f.span),
696 def_id: self.local_def_id(f.id),
697 ident: match f.ident {
698 Some(ident) => self.lower_ident(ident),
699 // FIXME(jseyfried): positional field hygiene.
700 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
702 vis_span: self.lower_span(f.vis.span),
707 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
708 let hir_id = self.lower_node_id(i.id);
709 self.lower_attrs(hir_id, &i.attrs);
710 let trait_item_def_id = hir_id.expect_owner();
712 let (generics, kind, has_default) = match &i.kind {
713 AssocItemKind::Const(_, ty, default) => {
714 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
715 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
716 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
718 AssocItemKind::Fn(box Fn { sig, generics, body: None, .. }) => {
719 let asyncness = sig.header.asyncness;
720 let names = self.lower_fn_params_to_names(&sig.decl);
721 let (generics, sig) = self.lower_method_sig(
726 asyncness.opt_return_id(),
728 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
730 AssocItemKind::Fn(box Fn { sig, generics, body: Some(body), .. }) => {
731 let asyncness = sig.header.asyncness;
733 self.lower_maybe_async_body(i.span, hir_id, &sig.decl, asyncness, Some(&body));
734 let (generics, sig) = self.lower_method_sig(
739 asyncness.opt_return_id(),
741 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
743 AssocItemKind::Type(box TyAlias { generics, where_clauses, bounds, ty, .. }) => {
744 let mut generics = generics.clone();
745 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
746 let (generics, kind) = self.lower_generics(
749 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
751 let ty = ty.as_ref().map(|x| {
752 this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
754 hir::TraitItemKind::Type(
755 this.lower_param_bounds(
757 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
763 (generics, kind, ty.is_some())
765 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
768 let item = hir::TraitItem {
769 owner_id: trait_item_def_id,
770 ident: self.lower_ident(i.ident),
773 span: self.lower_span(i.span),
774 defaultness: hir::Defaultness::Default { has_value: has_default },
776 self.arena.alloc(item)
779 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
780 let kind = match &i.kind {
781 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
782 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
783 AssocItemKind::Fn(box Fn { sig, .. }) => {
784 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
786 AssocItemKind::MacCall(..) => unimplemented!(),
788 let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
791 ident: self.lower_ident(i.ident),
792 span: self.lower_span(i.span),
797 /// Construct `ExprKind::Err` for the given `span`.
798 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
799 self.expr(span, hir::ExprKind::Err)
802 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
803 // Since `default impl` is not yet implemented, this is always true in impls.
804 let has_value = true;
805 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
806 let hir_id = self.lower_node_id(i.id);
807 self.lower_attrs(hir_id, &i.attrs);
809 let (generics, kind) = match &i.kind {
810 AssocItemKind::Const(_, ty, expr) => {
811 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
813 hir::Generics::empty(),
814 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
817 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
818 self.current_item = Some(i.span);
819 let asyncness = sig.header.asyncness;
820 let body_id = self.lower_maybe_async_body(
827 let (generics, sig) = self.lower_method_sig(
831 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
832 asyncness.opt_return_id(),
835 (generics, hir::ImplItemKind::Fn(sig, body_id))
837 AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
838 let mut generics = generics.clone();
839 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
843 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
846 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
847 hir::ImplItemKind::Type(ty)
850 let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
851 hir::ImplItemKind::Type(ty)
856 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
859 let item = hir::ImplItem {
860 owner_id: hir_id.expect_owner(),
861 ident: self.lower_ident(i.ident),
864 vis_span: self.lower_span(i.vis.span),
865 span: self.lower_span(i.span),
868 self.arena.alloc(item)
871 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
873 id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
874 ident: self.lower_ident(i.ident),
875 span: self.lower_span(i.span),
876 kind: match &i.kind {
877 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
878 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
879 AssocItemKind::Fn(box Fn { sig, .. }) => {
880 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
882 AssocItemKind::MacCall(..) => unimplemented!(),
884 trait_item_def_id: self
886 .get_partial_res(i.id)
887 .map(|r| r.expect_full_res().def_id()),
891 fn lower_defaultness(
895 ) -> (hir::Defaultness, Option<Span>) {
897 Defaultness::Default(sp) => {
898 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
900 Defaultness::Final => {
902 (hir::Defaultness::Final, None)
909 params: &'hir [hir::Param<'hir>],
910 value: hir::Expr<'hir>,
912 let body = hir::Body {
913 generator_kind: self.generator_kind,
915 value: self.arena.alloc(value),
918 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
919 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
923 pub(super) fn lower_body(
925 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
927 let prev_gen_kind = self.generator_kind.take();
928 let task_context = self.task_context.take();
929 let (parameters, result) = f(self);
930 let body_id = self.record_body(parameters, result);
931 self.task_context = task_context;
932 self.generator_kind = prev_gen_kind;
936 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
937 let hir_id = self.lower_node_id(param.id);
938 self.lower_attrs(hir_id, ¶m.attrs);
941 pat: self.lower_pat(¶m.pat),
942 ty_span: self.lower_span(param.ty.span),
943 span: self.lower_span(param.span),
947 pub(super) fn lower_fn_body(
950 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
952 self.lower_body(|this| {
954 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
960 fn lower_fn_body_block(
964 body: Option<&Block>,
966 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
969 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
971 Some(block) => self.lower_block_expr(block),
972 None => self.expr_err(span),
976 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
977 self.lower_body(|this| {
981 Some(expr) => this.lower_expr_mut(expr),
982 None => this.expr_err(span),
988 fn lower_maybe_async_body(
994 body: Option<&Block>,
996 let (closure_id, body) = match (asyncness, body) {
997 (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
998 _ => return self.lower_fn_body_block(span, decl, body),
1001 self.lower_body(|this| {
1002 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1003 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1005 // Async function parameters are lowered into the closure body so that they are
1006 // captured and so that the drop order matches the equivalent non-async functions.
1010 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1016 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1018 // let __arg2 = __arg2;
1019 // let <pattern> = __arg2;
1020 // let __arg1 = __arg1;
1021 // let <pattern> = __arg1;
1022 // let __arg0 = __arg0;
1023 // let <pattern> = __arg0;
1024 // drop-temps { <body> } // see comments later in fn for details
1028 // If `<pattern>` is a simple ident, then it is lowered to a single
1029 // `let <pattern> = <pattern>;` statement as an optimization.
1031 // Note that the body is embedded in `drop-temps`; an
1032 // equivalent desugaring would be `return { <body>
1033 // };`. The key point is that we wish to drop all the
1034 // let-bound variables and temporaries created in the body
1035 // (and its tail expression!) before we drop the
1036 // parameters (c.f. rust-lang/rust#64512).
1037 for (index, parameter) in decl.inputs.iter().enumerate() {
1038 let parameter = this.lower_param(parameter);
1039 let span = parameter.pat.span;
1041 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1042 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1043 let (ident, is_simple_parameter) = match parameter.pat.kind {
1044 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1047 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1048 // we can keep the same name for the parameter.
1049 // This lets rustdoc render it correctly in documentation.
1050 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1051 hir::PatKind::Wild => {
1052 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1055 // Replace the ident for bindings that aren't simple.
1056 let name = format!("__arg{}", index);
1057 let ident = Ident::from_str(&name);
1063 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1065 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1068 // If this is the simple case, this parameter will end up being the same as the
1069 // original parameter, but with a different pattern id.
1070 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1071 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1072 let new_parameter = hir::Param {
1073 hir_id: parameter.hir_id,
1074 pat: new_parameter_pat,
1075 ty_span: this.lower_span(parameter.ty_span),
1076 span: this.lower_span(parameter.span),
1079 if is_simple_parameter {
1080 // If this is the simple case, then we only insert one statement that is
1081 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1082 // `HirId`s are densely assigned.
1083 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1084 let stmt = this.stmt_let_pat(
1089 hir::LocalSource::AsyncFn,
1091 statements.push(stmt);
1093 // If this is not the simple case, then we construct two statements:
1096 // let __argN = __argN;
1097 // let <pat> = __argN;
1100 // The first statement moves the parameter into the closure and thus ensures
1101 // that the drop order is correct.
1103 // The second statement creates the bindings that the user wrote.
1105 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1106 // because the user may have specified a `ref mut` binding in the next
1108 let (move_pat, move_id) = this.pat_ident_binding_mode(
1111 hir::BindingAnnotation::MUT,
1113 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1114 let move_stmt = this.stmt_let_pat(
1119 hir::LocalSource::AsyncFn,
1122 // Construct the `let <pat> = __argN;` statement. We re-use the original
1123 // parameter's pattern so that `HirId`s are densely assigned.
1124 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1125 let pattern_stmt = this.stmt_let_pat(
1130 hir::LocalSource::AsyncFn,
1133 statements.push(move_stmt);
1134 statements.push(pattern_stmt);
1137 parameters.push(new_parameter);
1140 let async_expr = this.make_async_expr(
1146 hir::AsyncGeneratorKind::Fn,
1148 // Create a block from the user's function body:
1149 let user_body = this.lower_block_expr(body);
1151 // Transform into `drop-temps { <user-body> }`, an expression:
1152 let desugared_span =
1153 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1155 this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1157 // As noted above, create the final block like
1161 // let $param_pattern = $raw_param;
1163 // drop-temps { <user-body> }
1166 let body = this.block_all(
1168 this.arena.alloc_from_iter(statements),
1172 this.expr_block(body)
1176 (this.arena.alloc_from_iter(parameters), this.expr(body.span, async_expr))
1180 fn lower_method_sig(
1182 generics: &Generics,
1186 is_async: Option<(NodeId, Span)>,
1187 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1188 let header = self.lower_fn_header(sig.header);
1189 let mut itctx = ImplTraitContext::Universal;
1190 let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1191 this.lower_fn_decl(&sig.decl, id, sig.span, kind, is_async)
1193 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1196 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1198 unsafety: self.lower_unsafety(h.unsafety),
1199 asyncness: self.lower_asyncness(h.asyncness),
1200 constness: self.lower_constness(h.constness),
1201 abi: self.lower_extern(h.ext),
1205 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1206 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1207 self.error_on_invalid_abi(abi);
1212 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1214 Extern::None => abi::Abi::Rust,
1215 Extern::Implicit(_) => abi::Abi::FALLBACK,
1216 Extern::Explicit(abi, _) => self.lower_abi(abi),
1220 fn error_on_invalid_abi(&self, abi: StrLit) {
1221 let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1223 .map(|s| Symbol::intern(s))
1224 .collect::<Vec<_>>();
1225 let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1226 self.tcx.sess.emit_err(InvalidAbi {
1227 abi: abi.symbol_unescaped,
1229 suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1231 suggestion: format!("\"{suggested_name}\""),
1233 command: "rustc --print=calling-conventions".to_string(),
1237 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1239 Async::Yes { .. } => hir::IsAsync::Async,
1240 Async::No => hir::IsAsync::NotAsync,
1244 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1246 Const::Yes(_) => hir::Constness::Const,
1247 Const::No => hir::Constness::NotConst,
1251 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1253 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1254 Unsafe::No => hir::Unsafety::Normal,
1258 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1259 /// the carried impl trait definitions and bounds.
1260 #[instrument(level = "debug", skip(self, f))]
1261 fn lower_generics<T>(
1263 generics: &Generics,
1264 parent_node_id: NodeId,
1265 itctx: &ImplTraitContext,
1266 f: impl FnOnce(&mut Self) -> T,
1267 ) -> (&'hir hir::Generics<'hir>, T) {
1268 debug_assert!(self.impl_trait_defs.is_empty());
1269 debug_assert!(self.impl_trait_bounds.is_empty());
1271 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1272 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1273 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1274 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1275 // where clauses for `?Sized`.
1276 for pred in &generics.where_clause.predicates {
1277 let WherePredicate::BoundPredicate(bound_pred) = pred else {
1280 let compute_is_param = || {
1281 // Check if the where clause type is a plain type parameter.
1284 .get_partial_res(bound_pred.bounded_ty.id)
1285 .and_then(|r| r.full_res())
1287 Some(Res::Def(DefKind::TyParam, def_id))
1288 if bound_pred.bound_generic_params.is_empty() =>
1293 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1295 // Either the `bounded_ty` is not a plain type parameter, or
1296 // it's not found in the generic type parameters list.
1300 // We only need to compute this once per `WherePredicate`, but don't
1301 // need to compute this at all unless there is a Maybe bound.
1302 let mut is_param: Option<bool> = None;
1303 for bound in &bound_pred.bounds {
1304 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1307 let is_param = *is_param.get_or_insert_with(compute_is_param);
1309 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1314 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1315 predicates.extend(generics.params.iter().filter_map(|param| {
1316 self.lower_generic_bound_predicate(
1322 PredicateOrigin::GenericParam,
1330 .map(|predicate| self.lower_where_predicate(predicate)),
1333 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1334 self.lower_generic_params_mut(&generics.params).collect();
1336 // Introduce extra lifetimes if late resolution tells us to.
1337 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1338 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1339 self.lifetime_res_to_generic_param(ident, node_id, res)
1342 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1343 let where_clause_span = self.lower_span(generics.where_clause.span);
1344 let span = self.lower_span(generics.span);
1347 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1348 params.extend(impl_trait_defs.into_iter());
1350 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1351 predicates.extend(impl_trait_bounds.into_iter());
1353 let lowered_generics = self.arena.alloc(hir::Generics {
1354 params: self.arena.alloc_from_iter(params),
1355 predicates: self.arena.alloc_from_iter(predicates),
1356 has_where_clause_predicates,
1361 (lowered_generics, res)
1364 pub(super) fn lower_generic_bound_predicate(
1368 kind: &GenericParamKind,
1369 bounds: &[GenericBound],
1370 itctx: &ImplTraitContext,
1371 origin: PredicateOrigin,
1372 ) -> Option<hir::WherePredicate<'hir>> {
1373 // Do not create a clause if we do not have anything inside it.
1374 if bounds.is_empty() {
1378 let bounds = self.lower_param_bounds(bounds, itctx);
1380 let ident = self.lower_ident(ident);
1381 let param_span = ident.span;
1384 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1385 let bound_span = bound.span();
1386 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1387 // as we use this method to get a span appropriate for suggestions.
1388 if !bound_span.can_be_used_for_suggestions() {
1390 } else if let Some(span) = span {
1391 Some(span.to(bound_span))
1396 .unwrap_or(param_span.shrink_to_hi());
1398 GenericParamKind::Const { .. } => None,
1399 GenericParamKind::Type { .. } => {
1400 let def_id = self.local_def_id(id).to_def_id();
1401 let hir_id = self.next_id();
1402 let res = Res::Def(DefKind::TyParam, def_id);
1403 let ty_path = self.arena.alloc(hir::Path {
1408 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1410 let ty_id = self.next_id();
1412 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1413 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1414 hir_id: self.next_id(),
1415 bounded_ty: self.arena.alloc(bounded_ty),
1418 bound_generic_params: &[],
1422 GenericParamKind::Lifetime => {
1423 let ident = self.lower_ident(ident);
1424 let lt_id = self.next_node_id();
1425 let lifetime = self.new_named_lifetime(id, lt_id, ident);
1426 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1430 in_where_clause: false,
1436 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1438 WherePredicate::BoundPredicate(WhereBoundPredicate {
1439 bound_generic_params,
1443 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1444 hir_id: self.next_id(),
1445 bound_generic_params: self.lower_generic_params(bound_generic_params),
1447 .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1448 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1449 self.lower_param_bound(
1451 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1454 span: self.lower_span(*span),
1455 origin: PredicateOrigin::WhereClause,
1457 WherePredicate::RegionPredicate(WhereRegionPredicate { lifetime, bounds, span }) => {
1458 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1459 span: self.lower_span(*span),
1460 lifetime: self.lower_lifetime(lifetime),
1461 bounds: self.lower_param_bounds(
1463 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1465 in_where_clause: true,
1468 WherePredicate::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty, span }) => {
1469 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1471 .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1473 .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1474 span: self.lower_span(*span),