1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition};
3 use crate::{Arena, FnDeclKind};
6 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::LocalDefId;
13 use rustc_index::vec::Idx;
14 use rustc_span::source_map::{respan, DesugaringKind};
15 use rustc_span::symbol::{kw, sym, Ident};
17 use rustc_target::spec::abi;
18 use smallvec::{smallvec, SmallVec};
24 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
25 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
28 impl ItemLowerer<'_, '_, '_> {
29 fn with_trait_impl_ref<T>(
31 impl_ref: &Option<TraitRef>,
32 f: impl FnOnce(&mut Self) -> T,
34 let old = self.lctx.is_in_trait_impl;
35 self.lctx.is_in_trait_impl = impl_ref.is_some();
37 self.lctx.is_in_trait_impl = old;
42 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
43 fn visit_attribute(&mut self, _: &'a Attribute) {
44 // We do not want to lower expressions that appear in attributes,
45 // as they are not accessible to the rest of the HIR.
48 fn visit_item(&mut self, item: &'a Item) {
49 let hir_id = self.lctx.with_hir_id_owner(item.id, |lctx| {
50 let node = lctx.without_in_scope_lifetime_defs(|lctx| lctx.lower_item(item));
51 hir::OwnerNode::Item(node)
54 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
55 let this = &mut ItemLowerer { lctx: this };
57 ItemKind::Impl(box Impl { ref of_trait, .. }) => {
58 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
60 _ => visit::walk_item(this, item),
65 fn visit_fn(&mut self, fk: FnKind<'a>, sp: Span, _: NodeId) {
67 FnKind::Fn(FnCtxt::Foreign, _, sig, _, _) => {
68 self.visit_fn_header(&sig.header);
69 visit::walk_fn_decl(self, &sig.decl);
70 // Don't visit the foreign function body even if it has one, since lowering the
71 // body would have no meaning and will have already been caught as a parse error.
73 _ => visit::walk_fn(self, fk, sp),
77 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
78 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
79 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
80 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
83 visit::walk_assoc_item(self, item, ctxt);
86 fn visit_foreign_item(&mut self, item: &'a ForeignItem) {
87 self.lctx.with_hir_id_owner(item.id, |lctx| {
88 hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))
91 visit::walk_foreign_item(self, item);
95 impl<'hir> LoweringContext<'_, 'hir> {
96 // Same as the method above, but accepts `hir::GenericParam`s
97 // instead of `ast::GenericParam`s.
98 // This should only be used with generics that have already had their
99 // in-band lifetimes added. In practice, this means that this function is
100 // only used when lowering a child item of a trait or impl.
101 fn with_parent_item_lifetime_defs<T>(
103 parent_hir_id: LocalDefId,
104 f: impl FnOnce(&mut Self) -> T,
106 let old_len = self.in_scope_lifetimes.len();
108 let parent_generics = match self.owners[parent_hir_id].unwrap().node().expect_item().kind {
109 hir::ItemKind::Impl(hir::Impl { ref generics, .. })
110 | hir::ItemKind::Trait(_, _, ref generics, ..) => generics.params,
113 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
114 hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()),
117 self.in_scope_lifetimes.extend(lt_def_names);
121 self.in_scope_lifetimes.truncate(old_len);
125 // Clears (and restores) the `in_scope_lifetimes` field. Used when
126 // visiting nested items, which never inherit in-scope lifetimes
127 // from their surrounding environment.
128 fn without_in_scope_lifetime_defs<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
129 let old_in_scope_lifetimes = mem::replace(&mut self.in_scope_lifetimes, vec![]);
131 // this vector is only used when walking over impl headers,
132 // input types, and the like, and should not be non-empty in
134 assert!(self.lifetimes_to_define.is_empty());
138 assert!(self.in_scope_lifetimes.is_empty());
139 self.in_scope_lifetimes = old_in_scope_lifetimes;
144 pub(super) fn lower_mod(&mut self, items: &[P<Item>], inner: Span) -> hir::Mod<'hir> {
146 inner: self.lower_span(inner),
147 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
151 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
152 let mut node_ids = smallvec![hir::ItemId { def_id: self.resolver.local_def_id(i.id) }];
153 if let ItemKind::Use(ref use_tree) = &i.kind {
154 self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
159 fn lower_item_id_use_tree(
163 vec: &mut SmallVec<[hir::ItemId; 1]>,
166 UseTreeKind::Nested(ref nested_vec) => {
167 for &(ref nested, id) in nested_vec {
168 vec.push(hir::ItemId { def_id: self.resolver.local_def_id(id) });
169 self.lower_item_id_use_tree(nested, id, vec);
172 UseTreeKind::Glob => {}
173 UseTreeKind::Simple(_, id1, id2) => {
175 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
177 vec.push(hir::ItemId { def_id: self.resolver.local_def_id(id) });
183 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
184 let mut ident = i.ident;
185 let mut vis = self.lower_visibility(&i.vis);
186 let hir_id = self.lower_node_id(i.id);
187 let attrs = self.lower_attrs(hir_id, &i.attrs);
188 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
189 let item = hir::Item {
190 def_id: hir_id.expect_owner(),
191 ident: self.lower_ident(ident),
194 span: self.lower_span(i.span),
196 self.arena.alloc(item)
205 attrs: Option<&'hir [Attribute]>,
206 vis: &mut hir::Visibility<'hir>,
208 ) -> hir::ItemKind<'hir> {
210 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
211 ItemKind::Use(ref use_tree) => {
212 // Start with an empty prefix.
213 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
215 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
217 ItemKind::Static(ref t, m, ref e) => {
218 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
219 hir::ItemKind::Static(ty, m, body_id)
221 ItemKind::Const(_, ref t, ref e) => {
222 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
223 hir::ItemKind::Const(ty, body_id)
225 ItemKind::Fn(box Fn {
226 sig: FnSig { ref decl, header, span: fn_sig_span },
231 let fn_def_id = self.resolver.local_def_id(id);
232 self.with_new_scopes(|this| {
233 this.current_item = Some(ident.span);
235 // Note: we don't need to change the return type from `T` to
236 // `impl Future<Output = T>` here because lower_body
237 // only cares about the input argument patterns in the function
238 // declaration (decl), not the return types.
239 let asyncness = header.asyncness;
241 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
243 let (generics, decl) = this.add_in_band_defs(
246 AnonymousLifetimeMode::PassThrough,
248 let ret_id = asyncness.opt_return_id();
251 Some((fn_def_id, idty)),
257 let sig = hir::FnSig {
259 header: this.lower_fn_header(header),
260 span: this.lower_span(fn_sig_span),
262 hir::ItemKind::Fn(sig, generics, body_id)
265 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
266 ModKind::Loaded(items, _, inner_span) => {
267 hir::ItemKind::Mod(self.lower_mod(items, *inner_span))
269 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
271 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
272 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
275 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
277 ItemKind::GlobalAsm(ref asm) => {
278 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
280 ItemKind::TyAlias(box TyAlias {
288 // type Foo = impl Trait
293 // opaque type Foo1: Trait
294 let ty = self.lower_ty(
296 ImplTraitContext::TypeAliasesOpaqueTy {
297 capturable_lifetimes: &mut FxHashSet::default(),
300 let mut generics = generics.clone();
301 generics.where_clause.has_where_token = where_clauses.0.0;
302 generics.where_clause.span = where_clauses.0.1;
303 let generics = self.lower_generics(
305 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
307 hir::ItemKind::TyAlias(ty, generics)
309 ItemKind::TyAlias(box TyAlias {
310 ref generics, ref where_clauses, ty: None, ..
312 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
313 let mut generics = generics.clone();
314 generics.where_clause.has_where_token = where_clauses.0.0;
315 generics.where_clause.span = where_clauses.0.1;
316 let generics = self.lower_generics(
318 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
320 hir::ItemKind::TyAlias(ty, generics)
322 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
324 variants: self.arena.alloc_from_iter(
325 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
330 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
333 ItemKind::Struct(ref struct_def, ref generics) => {
334 let struct_def = self.lower_variant_data(hir_id, struct_def);
335 hir::ItemKind::Struct(
339 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
343 ItemKind::Union(ref vdata, ref generics) => {
344 let vdata = self.lower_variant_data(hir_id, vdata);
345 hir::ItemKind::Union(
349 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
353 ItemKind::Impl(box Impl {
358 generics: ref ast_generics,
359 of_trait: ref trait_ref,
361 items: ref impl_items,
363 // Lower the "impl header" first. This ordering is important
364 // for in-band lifetimes! Consider `'a` here:
366 // impl Foo<'a> for u32 {
367 // fn method(&'a self) { .. }
370 // Because we start by lowering the `Foo<'a> for u32`
371 // part, we will add `'a` to the list of generics on
372 // the impl. When we then encounter it later in the
373 // method, it will not be considered an in-band
374 // lifetime to be added, but rather a reference to a
376 let lowered_trait_def_id = hir_id.expect_owner();
377 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
379 lowered_trait_def_id,
380 AnonymousLifetimeMode::CreateParameter,
382 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
383 this.lower_trait_ref(
385 ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
389 let lowered_ty = this
390 .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
392 (trait_ref, lowered_ty)
397 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
398 this.arena.alloc_from_iter(
399 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
403 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
404 // to not cause an assertion failure inside the `lower_defaultness` function.
406 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
407 let polarity = match polarity {
408 ImplPolarity::Positive => ImplPolarity::Positive,
409 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
411 hir::ItemKind::Impl(hir::Impl {
412 unsafety: self.lower_unsafety(unsafety),
416 constness: self.lower_constness(constness),
420 items: new_impl_items,
423 ItemKind::Trait(box Trait {
430 let bounds = self.lower_param_bounds(
432 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
436 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
437 hir::ItemKind::Trait(
439 self.lower_unsafety(unsafety),
442 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
448 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
451 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
453 self.lower_param_bounds(
455 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
458 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
459 let body = P(self.lower_mac_args(body));
460 let macro_kind = self.resolver.decl_macro_kind(self.resolver.local_def_id(id));
461 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
463 ItemKind::MacCall(..) => {
464 panic!("`TyMac` should have been expanded by now")
474 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
475 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
476 (ty, self.lower_const_body(span, body))
484 vis: &mut hir::Visibility<'hir>,
486 attrs: Option<&'hir [Attribute]>,
487 ) -> hir::ItemKind<'hir> {
488 debug!("lower_use_tree(tree={:?})", tree);
489 debug!("lower_use_tree: vis = {:?}", vis);
491 let path = &tree.prefix;
492 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
495 UseTreeKind::Simple(rename, id1, id2) => {
496 *ident = tree.ident();
498 // First, apply the prefix to the path.
499 let mut path = Path { segments, span: path.span, tokens: None };
501 // Correctly resolve `self` imports.
502 if path.segments.len() > 1
503 && path.segments.last().unwrap().ident.name == kw::SelfLower
505 let _ = path.segments.pop();
506 if rename.is_none() {
507 *ident = path.segments.last().unwrap().ident;
511 let mut resolutions = self.expect_full_res_from_use(id).fuse();
512 // We want to return *something* from this function, so hold onto the first item
514 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
516 // Here, we are looping over namespaces, if they exist for the definition
517 // being imported. We only handle type and value namespaces because we
518 // won't be dealing with macros in the rest of the compiler.
519 // Essentially a single `use` which imports two names is desugared into
521 for new_node_id in [id1, id2] {
522 let new_id = self.resolver.local_def_id(new_node_id);
523 let Some(res) = resolutions.next() else {
524 // Associate an HirId to both ids even if there is no resolution.
525 self.owners.ensure_contains_elem(new_id, || hir::MaybeOwner::Phantom);
526 let _old = std::mem::replace(
527 &mut self.owners[new_id],
528 hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
530 debug_assert!(matches!(_old, hir::MaybeOwner::Phantom));
534 let mut path = path.clone();
535 for seg in &mut path.segments {
536 seg.id = self.resolver.next_node_id();
538 let span = path.span;
540 self.with_hir_id_owner(new_node_id, |this| {
541 let res = this.lower_res(res);
542 let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
543 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
544 let vis = this.rebuild_vis(&vis);
545 if let Some(attrs) = attrs {
546 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
549 let item = hir::Item {
551 ident: this.lower_ident(ident),
554 span: this.lower_span(span),
556 hir::OwnerNode::Item(this.arena.alloc(item))
560 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
561 hir::ItemKind::Use(path, hir::UseKind::Single)
563 UseTreeKind::Glob => {
564 let path = self.lower_path(
566 &Path { segments, span: path.span, tokens: None },
569 hir::ItemKind::Use(path, hir::UseKind::Glob)
571 UseTreeKind::Nested(ref trees) => {
572 // Nested imports are desugared into simple imports.
573 // So, if we start with
576 // pub(x) use foo::{a, b};
579 // we will create three items:
582 // pub(x) use foo::a;
583 // pub(x) use foo::b;
584 // pub(x) use foo::{}; // <-- this is called the `ListStem`
587 // The first two are produced by recursively invoking
588 // `lower_use_tree` (and indeed there may be things
589 // like `use foo::{a::{b, c}}` and so forth). They
590 // wind up being directly added to
591 // `self.items`. However, the structure of this
592 // function also requires us to return one item, and
593 // for that we return the `{}` import (called the
596 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
598 // Add all the nested `PathListItem`s to the HIR.
599 for &(ref use_tree, id) in trees {
600 let new_hir_id = self.resolver.local_def_id(id);
602 let mut prefix = prefix.clone();
604 // Give the segments new node-ids since they are being cloned.
605 for seg in &mut prefix.segments {
606 seg.id = self.resolver.next_node_id();
609 // Each `use` import is an item and thus are owners of the
610 // names in the path. Up to this point the nested import is
611 // the current owner, since we want each desugared import to
612 // own its own names, we have to adjust the owner before
613 // lowering the rest of the import.
614 self.with_hir_id_owner(id, |this| {
615 let mut vis = this.rebuild_vis(&vis);
616 let mut ident = *ident;
619 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
620 if let Some(attrs) = attrs {
621 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
624 let item = hir::Item {
626 ident: this.lower_ident(ident),
629 span: this.lower_span(use_tree.span),
631 hir::OwnerNode::Item(this.arena.alloc(item))
635 // Subtle and a bit hacky: we lower the privacy level
636 // of the list stem to "private" most of the time, but
637 // not for "restricted" paths. The key thing is that
638 // we don't want it to stay as `pub` (with no caveats)
639 // because that affects rustdoc and also the lints
640 // about `pub` items. But we can't *always* make it
641 // private -- particularly not for restricted paths --
642 // because it contains node-ids that would then be
643 // unused, failing the check that HirIds are "densely
646 hir::VisibilityKind::Public
647 | hir::VisibilityKind::Crate(_)
648 | hir::VisibilityKind::Inherited => {
650 self.lower_span(prefix.span.shrink_to_lo()),
651 hir::VisibilityKind::Inherited,
654 hir::VisibilityKind::Restricted { .. } => {
655 // Do nothing here, as described in the comment on the match.
659 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
660 let res = self.lower_res(res);
661 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
662 hir::ItemKind::Use(path, hir::UseKind::ListStem)
667 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
668 /// many times in the HIR tree; for each occurrence, we need to assign distinct
669 /// `NodeId`s. (See, e.g., #56128.)
670 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
671 debug!("rebuild_use_path(path = {:?})", path);
673 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
675 hir_id: seg.hir_id.map(|_| self.next_id()),
678 infer_args: seg.infer_args,
680 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
683 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
684 let vis_kind = match vis.node {
685 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
686 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
687 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
688 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
689 hir::VisibilityKind::Restricted {
690 path: self.rebuild_use_path(path),
691 hir_id: self.next_id(),
695 respan(self.lower_span(vis.span), vis_kind)
698 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
699 let hir_id = self.lower_node_id(i.id);
700 let def_id = hir_id.expect_owner();
701 self.lower_attrs(hir_id, &i.attrs);
702 let item = hir::ForeignItem {
704 ident: self.lower_ident(i.ident),
706 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
707 let fdec = &sig.decl;
708 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
711 AnonymousLifetimeMode::PassThrough,
714 // Disallow `impl Trait` in foreign items.
715 this.lower_fn_decl(fdec, None, FnDeclKind::ExternFn, None),
716 this.lower_fn_params_to_names(fdec),
721 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
723 ForeignItemKind::Static(ref t, m, _) => {
725 self.lower_ty(t, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
726 hir::ForeignItemKind::Static(ty, m)
728 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
729 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
731 vis: self.lower_visibility(&i.vis),
732 span: self.lower_span(i.span),
734 self.arena.alloc(item)
737 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
738 hir::ForeignItemRef {
739 id: hir::ForeignItemId { def_id: self.resolver.local_def_id(i.id) },
740 ident: self.lower_ident(i.ident),
741 span: self.lower_span(i.span),
745 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
746 let id = self.lower_node_id(v.id);
747 self.lower_attrs(id, &v.attrs);
750 data: self.lower_variant_data(id, &v.data),
751 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
752 ident: self.lower_ident(v.ident),
753 span: self.lower_span(v.span),
757 fn lower_variant_data(
759 parent_id: hir::HirId,
761 ) -> hir::VariantData<'hir> {
763 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
765 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
768 VariantData::Tuple(ref fields, id) => {
769 let ctor_id = self.lower_node_id(id);
770 self.alias_attrs(ctor_id, parent_id);
771 hir::VariantData::Tuple(
772 self.arena.alloc_from_iter(
773 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
778 VariantData::Unit(id) => {
779 let ctor_id = self.lower_node_id(id);
780 self.alias_attrs(ctor_id, parent_id);
781 hir::VariantData::Unit(ctor_id)
786 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
787 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
788 let t = self.lower_path_ty(
792 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
793 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
797 self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
799 let hir_id = self.lower_node_id(f.id);
800 self.lower_attrs(hir_id, &f.attrs);
802 span: self.lower_span(f.span),
804 ident: match f.ident {
805 Some(ident) => self.lower_ident(ident),
806 // FIXME(jseyfried): positional field hygiene.
807 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
809 vis: self.lower_visibility(&f.vis),
814 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
815 let hir_id = self.lower_node_id(i.id);
816 let trait_item_def_id = hir_id.expect_owner();
818 let (generics, kind) = match i.kind {
819 AssocItemKind::Const(_, ref ty, ref default) => {
820 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
821 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
822 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
824 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
825 let names = self.lower_fn_params_to_names(&sig.decl);
826 let (generics, sig) = self.lower_method_sig(
833 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
835 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
836 let asyncness = sig.header.asyncness;
838 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
839 let (generics, sig) = self.lower_method_sig(
844 asyncness.opt_return_id(),
846 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
848 AssocItemKind::TyAlias(box TyAlias {
855 let ty = ty.as_ref().map(|x| {
856 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
858 let mut generics = generics.clone();
859 generics.where_clause.has_where_token = where_clauses.1.0;
860 generics.where_clause.span = where_clauses.1.1;
861 let generics = self.lower_generics(
863 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
865 let kind = hir::TraitItemKind::Type(
866 self.lower_param_bounds(
868 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
875 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
878 self.lower_attrs(hir_id, &i.attrs);
879 let item = hir::TraitItem {
880 def_id: trait_item_def_id,
881 ident: self.lower_ident(i.ident),
884 span: self.lower_span(i.span),
886 self.arena.alloc(item)
889 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
890 let (kind, has_default) = match &i.kind {
891 AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
892 AssocItemKind::TyAlias(box TyAlias { ty, .. }) => {
893 (hir::AssocItemKind::Type, ty.is_some())
895 AssocItemKind::Fn(box Fn { sig, body, .. }) => {
896 (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, body.is_some())
898 AssocItemKind::MacCall(..) => unimplemented!(),
900 let id = hir::TraitItemId { def_id: self.resolver.local_def_id(i.id) };
901 let defaultness = hir::Defaultness::Default { has_value: has_default };
904 ident: self.lower_ident(i.ident),
905 span: self.lower_span(i.span),
911 /// Construct `ExprKind::Err` for the given `span`.
912 crate fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
913 self.expr(span, hir::ExprKind::Err, AttrVec::new())
916 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
917 let impl_item_def_id = self.resolver.local_def_id(i.id);
919 let (generics, kind) = match &i.kind {
920 AssocItemKind::Const(_, ty, expr) => {
921 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
923 hir::Generics::empty(),
924 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
927 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
928 self.current_item = Some(i.span);
929 let asyncness = sig.header.asyncness;
931 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
932 let (generics, sig) = self.lower_method_sig(
936 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
937 asyncness.opt_return_id(),
940 (generics, hir::ImplItemKind::Fn(sig, body_id))
942 AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
943 let mut generics = generics.clone();
944 generics.where_clause.has_where_token = where_clauses.1.0;
945 generics.where_clause.span = where_clauses.1.1;
946 let generics = self.lower_generics(
948 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
950 let kind = match ty {
952 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
953 hir::ImplItemKind::TyAlias(ty)
956 let ty = self.lower_ty(
958 ImplTraitContext::TypeAliasesOpaqueTy {
959 capturable_lifetimes: &mut FxHashSet::default(),
962 hir::ImplItemKind::TyAlias(ty)
967 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
970 let hir_id = self.lower_node_id(i.id);
971 self.lower_attrs(hir_id, &i.attrs);
972 let item = hir::ImplItem {
973 def_id: hir_id.expect_owner(),
974 ident: self.lower_ident(i.ident),
976 vis: self.lower_visibility(&i.vis),
978 span: self.lower_span(i.span),
980 self.arena.alloc(item)
983 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
984 // Since `default impl` is not yet implemented, this is always true in impls.
985 let has_value = true;
986 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
988 id: hir::ImplItemId { def_id: self.resolver.local_def_id(i.id) },
989 ident: self.lower_ident(i.ident),
990 span: self.lower_span(i.span),
992 kind: match &i.kind {
993 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
994 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
995 AssocItemKind::Fn(box Fn { sig, .. }) => {
996 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
998 AssocItemKind::MacCall(..) => unimplemented!(),
1000 trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
1004 /// If an `explicit_owner` is given, this method allocates the `HirId` in
1005 /// the address space of that item instead of the item currently being
1006 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
1007 /// lower a `Visibility` value although we haven't lowered the owning
1008 /// `ImplItem` in question yet.
1009 fn lower_visibility(&mut self, v: &Visibility) -> hir::Visibility<'hir> {
1010 let node = match v.kind {
1011 VisibilityKind::Public => hir::VisibilityKind::Public,
1012 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
1013 VisibilityKind::Restricted { ref path, id } => {
1014 debug!("lower_visibility: restricted path id = {:?}", id);
1015 let lowered_id = self.lower_node_id(id);
1016 hir::VisibilityKind::Restricted {
1017 path: self.lower_path(id, path, ParamMode::Explicit),
1021 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
1023 respan(self.lower_span(v.span), node)
1026 fn lower_defaultness(
1030 ) -> (hir::Defaultness, Option<Span>) {
1032 Defaultness::Default(sp) => {
1033 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1035 Defaultness::Final => {
1037 (hir::Defaultness::Final, None)
1044 params: &'hir [hir::Param<'hir>],
1045 value: hir::Expr<'hir>,
1047 let body = hir::Body { generator_kind: self.generator_kind, params, value };
1049 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
1050 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1054 pub(super) fn lower_body(
1056 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1058 let prev_gen_kind = self.generator_kind.take();
1059 let task_context = self.task_context.take();
1060 let (parameters, result) = f(self);
1061 let body_id = self.record_body(parameters, result);
1062 self.task_context = task_context;
1063 self.generator_kind = prev_gen_kind;
1067 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1068 let hir_id = self.lower_node_id(param.id);
1069 self.lower_attrs(hir_id, ¶m.attrs);
1072 pat: self.lower_pat(¶m.pat),
1073 ty_span: self.lower_span(param.ty.span),
1074 span: self.lower_span(param.span),
1078 pub(super) fn lower_fn_body(
1081 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1083 self.lower_body(|this| {
1085 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1091 fn lower_fn_body_block(
1095 body: Option<&Block>,
1097 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1100 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1102 Some(block) => self.lower_block_expr(block),
1103 None => self.expr_err(span),
1107 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1108 self.lower_body(|this| {
1112 Some(expr) => this.lower_expr_mut(expr),
1113 None => this.expr_err(span),
1119 fn lower_maybe_async_body(
1124 body: Option<&Block>,
1126 let closure_id = match asyncness {
1127 Async::Yes { closure_id, .. } => closure_id,
1128 Async::No => return self.lower_fn_body_block(span, decl, body),
1131 self.lower_body(|this| {
1132 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1133 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1135 // Async function parameters are lowered into the closure body so that they are
1136 // captured and so that the drop order matches the equivalent non-async functions.
1140 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1146 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1148 // let __arg2 = __arg2;
1149 // let <pattern> = __arg2;
1150 // let __arg1 = __arg1;
1151 // let <pattern> = __arg1;
1152 // let __arg0 = __arg0;
1153 // let <pattern> = __arg0;
1154 // drop-temps { <body> } // see comments later in fn for details
1158 // If `<pattern>` is a simple ident, then it is lowered to a single
1159 // `let <pattern> = <pattern>;` statement as an optimization.
1161 // Note that the body is embedded in `drop-temps`; an
1162 // equivalent desugaring would be `return { <body>
1163 // };`. The key point is that we wish to drop all the
1164 // let-bound variables and temporaries created in the body
1165 // (and its tail expression!) before we drop the
1166 // parameters (c.f. rust-lang/rust#64512).
1167 for (index, parameter) in decl.inputs.iter().enumerate() {
1168 let parameter = this.lower_param(parameter);
1169 let span = parameter.pat.span;
1171 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1172 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1173 let (ident, is_simple_parameter) = match parameter.pat.kind {
1174 hir::PatKind::Binding(
1175 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
1180 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1181 // we can keep the same name for the parameter.
1182 // This lets rustdoc render it correctly in documentation.
1183 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1184 hir::PatKind::Wild => {
1185 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1188 // Replace the ident for bindings that aren't simple.
1189 let name = format!("__arg{}", index);
1190 let ident = Ident::from_str(&name);
1196 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1198 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1201 // If this is the simple case, this parameter will end up being the same as the
1202 // original parameter, but with a different pattern id.
1203 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1204 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1205 let new_parameter = hir::Param {
1206 hir_id: parameter.hir_id,
1207 pat: new_parameter_pat,
1208 ty_span: this.lower_span(parameter.ty_span),
1209 span: this.lower_span(parameter.span),
1212 if is_simple_parameter {
1213 // If this is the simple case, then we only insert one statement that is
1214 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1215 // `HirId`s are densely assigned.
1216 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1217 let stmt = this.stmt_let_pat(
1222 hir::LocalSource::AsyncFn,
1224 statements.push(stmt);
1226 // If this is not the simple case, then we construct two statements:
1229 // let __argN = __argN;
1230 // let <pat> = __argN;
1233 // The first statement moves the parameter into the closure and thus ensures
1234 // that the drop order is correct.
1236 // The second statement creates the bindings that the user wrote.
1238 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1239 // because the user may have specified a `ref mut` binding in the next
1241 let (move_pat, move_id) = this.pat_ident_binding_mode(
1244 hir::BindingAnnotation::Mutable,
1246 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1247 let move_stmt = this.stmt_let_pat(
1252 hir::LocalSource::AsyncFn,
1255 // Construct the `let <pat> = __argN;` statement. We re-use the original
1256 // parameter's pattern so that `HirId`s are densely assigned.
1257 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1258 let pattern_stmt = this.stmt_let_pat(
1263 hir::LocalSource::AsyncFn,
1266 statements.push(move_stmt);
1267 statements.push(pattern_stmt);
1270 parameters.push(new_parameter);
1273 let body_span = body.map_or(span, |b| b.span);
1274 let async_expr = this.make_async_expr(
1279 hir::AsyncGeneratorKind::Fn,
1281 // Create a block from the user's function body:
1282 let user_body = this.lower_block_expr_opt(body_span, body);
1284 // Transform into `drop-temps { <user-body> }`, an expression:
1285 let desugared_span =
1286 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1287 let user_body = this.expr_drop_temps(
1289 this.arena.alloc(user_body),
1293 // As noted above, create the final block like
1297 // let $param_pattern = $raw_param;
1299 // drop-temps { <user-body> }
1302 let body = this.block_all(
1304 this.arena.alloc_from_iter(statements),
1308 this.expr_block(body, AttrVec::new())
1313 this.arena.alloc_from_iter(parameters),
1314 this.expr(body_span, async_expr, AttrVec::new()),
1319 fn lower_method_sig(
1321 generics: &Generics,
1323 fn_def_id: LocalDefId,
1325 is_async: Option<NodeId>,
1326 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1327 let header = self.lower_fn_header(sig.header);
1328 let (generics, decl) = self.add_in_band_defs(
1331 AnonymousLifetimeMode::PassThrough,
1332 |this, idty| this.lower_fn_decl(&sig.decl, Some((fn_def_id, idty)), kind, is_async),
1334 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1337 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1339 unsafety: self.lower_unsafety(h.unsafety),
1340 asyncness: self.lower_asyncness(h.asyncness),
1341 constness: self.lower_constness(h.constness),
1342 abi: self.lower_extern(h.ext),
1346 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1347 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1348 self.error_on_invalid_abi(abi);
1353 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1355 Extern::None => abi::Abi::Rust,
1356 Extern::Implicit => abi::Abi::FALLBACK,
1357 Extern::Explicit(abi) => self.lower_abi(abi),
1361 fn error_on_invalid_abi(&self, abi: StrLit) {
1362 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1363 .span_label(abi.span, "invalid ABI")
1364 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1368 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1370 Async::Yes { .. } => hir::IsAsync::Async,
1371 Async::No => hir::IsAsync::NotAsync,
1375 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1377 Const::Yes(_) => hir::Constness::Const,
1378 Const::No => hir::Constness::NotConst,
1382 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1384 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1385 Unsafe::No => hir::Unsafety::Normal,
1389 pub(super) fn lower_generics_mut(
1391 generics: &Generics,
1392 itctx: ImplTraitContext<'_, 'hir>,
1393 ) -> GenericsCtor<'hir> {
1394 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1395 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1396 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1397 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1398 // where clauses for `?Sized`.
1399 for pred in &generics.where_clause.predicates {
1400 let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1403 let compute_is_param = || {
1404 // Check if the where clause type is a plain type parameter.
1407 .get_partial_res(bound_pred.bounded_ty.id)
1408 .map(|d| (d.base_res(), d.unresolved_segments()))
1410 Some((Res::Def(DefKind::TyParam, def_id), 0))
1411 if bound_pred.bound_generic_params.is_empty() =>
1416 .any(|p| def_id == self.resolver.local_def_id(p.id).to_def_id())
1418 // Either the `bounded_ty` is not a plain type parameter, or
1419 // it's not found in the generic type parameters list.
1423 // We only need to compute this once per `WherePredicate`, but don't
1424 // need to compute this at all unless there is a Maybe bound.
1425 let mut is_param: Option<bool> = None;
1426 for bound in &bound_pred.bounds {
1427 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1430 let is_param = *is_param.get_or_insert_with(compute_is_param);
1432 self.diagnostic().span_err(
1434 "`?Trait` bounds are only permitted at the \
1435 point where a type parameter is declared",
1442 params: self.lower_generic_params_mut(&generics.params, itctx).collect(),
1443 where_clause: self.lower_where_clause(&generics.where_clause),
1444 span: self.lower_span(generics.span),
1448 pub(super) fn lower_generics(
1450 generics: &Generics,
1451 itctx: ImplTraitContext<'_, 'hir>,
1452 ) -> hir::Generics<'hir> {
1453 let generics_ctor = self.lower_generics_mut(generics, itctx);
1454 generics_ctor.into_generics(self.arena)
1457 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1458 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1460 predicates: this.arena.alloc_from_iter(
1461 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1463 span: this.lower_span(wc.span),
1468 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1470 WherePredicate::BoundPredicate(WhereBoundPredicate {
1471 ref bound_generic_params,
1475 }) => self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1476 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1477 bound_generic_params: this.lower_generic_params(
1478 bound_generic_params,
1479 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1481 bounded_ty: this.lower_ty(
1483 ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1485 bounds: this.arena.alloc_from_iter(bounds.iter().map(|bound| {
1486 this.lower_param_bound(
1488 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1491 span: this.lower_span(span),
1494 WherePredicate::RegionPredicate(WhereRegionPredicate {
1498 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1499 span: self.lower_span(span),
1500 lifetime: self.lower_lifetime(lifetime),
1501 bounds: self.lower_param_bounds(
1503 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1506 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1507 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1508 hir_id: self.lower_node_id(id),
1510 .lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1512 .lower_ty(rhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1513 span: self.lower_span(span),
1520 /// Helper struct for delayed construction of Generics.
1521 pub(super) struct GenericsCtor<'hir> {
1522 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1523 where_clause: hir::WhereClause<'hir>,
1527 impl<'hir> GenericsCtor<'hir> {
1528 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1530 params: arena.alloc_from_iter(self.params),
1531 where_clause: self.where_clause,