1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition};
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();
249 this.lower_fn_decl(&decl, Some((fn_def_id, idty)), true, ret_id)
252 let sig = hir::FnSig {
254 header: this.lower_fn_header(header),
255 span: this.lower_span(fn_sig_span),
257 hir::ItemKind::Fn(sig, generics, body_id)
260 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
261 ModKind::Loaded(items, _, inner_span) => {
262 hir::ItemKind::Mod(self.lower_mod(items, *inner_span))
264 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
266 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
267 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
270 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
272 ItemKind::GlobalAsm(ref asm) => {
273 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
275 ItemKind::TyAlias(box TyAlias { ref generics, ty: Some(ref ty), .. }) => {
278 // type Foo = impl Trait
283 // opaque type Foo1: Trait
284 let ty = self.lower_ty(
286 ImplTraitContext::TypeAliasesOpaqueTy {
287 capturable_lifetimes: &mut FxHashSet::default(),
290 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
291 hir::ItemKind::TyAlias(ty, generics)
293 ItemKind::TyAlias(box TyAlias { ref generics, ty: None, .. }) => {
294 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
295 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
296 hir::ItemKind::TyAlias(ty, generics)
298 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
300 variants: self.arena.alloc_from_iter(
301 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
304 self.lower_generics(generics, ImplTraitContext::disallowed()),
306 ItemKind::Struct(ref struct_def, ref generics) => {
307 let struct_def = self.lower_variant_data(hir_id, struct_def);
308 hir::ItemKind::Struct(
310 self.lower_generics(generics, ImplTraitContext::disallowed()),
313 ItemKind::Union(ref vdata, ref generics) => {
314 let vdata = self.lower_variant_data(hir_id, vdata);
315 hir::ItemKind::Union(
317 self.lower_generics(generics, ImplTraitContext::disallowed()),
320 ItemKind::Impl(box Impl {
325 generics: ref ast_generics,
326 of_trait: ref trait_ref,
328 items: ref impl_items,
330 // Lower the "impl header" first. This ordering is important
331 // for in-band lifetimes! Consider `'a` here:
333 // impl Foo<'a> for u32 {
334 // fn method(&'a self) { .. }
337 // Because we start by lowering the `Foo<'a> for u32`
338 // part, we will add `'a` to the list of generics on
339 // the impl. When we then encounter it later in the
340 // method, it will not be considered an in-band
341 // lifetime to be added, but rather a reference to a
343 let lowered_trait_def_id = self.lower_node_id(id).expect_owner();
344 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
346 lowered_trait_def_id,
347 AnonymousLifetimeMode::CreateParameter,
349 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
350 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
353 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
355 (trait_ref, lowered_ty)
360 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
361 this.arena.alloc_from_iter(
362 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
366 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
367 // to not cause an assertion failure inside the `lower_defaultness` function.
369 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
370 let polarity = match polarity {
371 ImplPolarity::Positive => ImplPolarity::Positive,
372 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
374 hir::ItemKind::Impl(hir::Impl {
375 unsafety: self.lower_unsafety(unsafety),
379 constness: self.lower_constness(constness),
383 items: new_impl_items,
386 ItemKind::Trait(box Trait {
393 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
396 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
397 hir::ItemKind::Trait(
399 self.lower_unsafety(unsafety),
400 self.lower_generics(generics, ImplTraitContext::disallowed()),
405 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
406 self.lower_generics(generics, ImplTraitContext::disallowed()),
407 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
409 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
410 let body = P(self.lower_mac_args(body));
412 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules })
414 ItemKind::MacCall(..) => {
415 panic!("`TyMac` should have been expanded by now")
425 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
426 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Binding));
427 (ty, self.lower_const_body(span, body))
435 vis: &mut hir::Visibility<'hir>,
437 attrs: Option<&'hir [Attribute]>,
438 ) -> hir::ItemKind<'hir> {
439 debug!("lower_use_tree(tree={:?})", tree);
440 debug!("lower_use_tree: vis = {:?}", vis);
442 let path = &tree.prefix;
443 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
446 UseTreeKind::Simple(rename, id1, id2) => {
447 *ident = tree.ident();
449 // First, apply the prefix to the path.
450 let mut path = Path { segments, span: path.span, tokens: None };
452 // Correctly resolve `self` imports.
453 if path.segments.len() > 1
454 && path.segments.last().unwrap().ident.name == kw::SelfLower
456 let _ = path.segments.pop();
457 if rename.is_none() {
458 *ident = path.segments.last().unwrap().ident;
462 let mut resolutions = self.expect_full_res_from_use(id).fuse();
463 // We want to return *something* from this function, so hold onto the first item
465 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
467 // Here, we are looping over namespaces, if they exist for the definition
468 // being imported. We only handle type and value namespaces because we
469 // won't be dealing with macros in the rest of the compiler.
470 // Essentially a single `use` which imports two names is desugared into
472 for new_node_id in [id1, id2] {
473 let new_id = self.resolver.local_def_id(new_node_id);
474 let Some(res) = resolutions.next() else {
475 // Associate an HirId to both ids even if there is no resolution.
478 .insert(new_node_id, hir::HirId::make_owner(new_id));
479 debug_assert!(_old.is_none());
480 self.owners.ensure_contains_elem(new_id, || hir::MaybeOwner::Phantom);
481 let _old = std::mem::replace(
482 &mut self.owners[new_id],
483 hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
485 debug_assert!(matches!(_old, hir::MaybeOwner::Phantom));
489 let mut path = path.clone();
490 for seg in &mut path.segments {
491 seg.id = self.resolver.next_node_id();
493 let span = path.span;
495 self.with_hir_id_owner(new_node_id, |this| {
496 let res = this.lower_res(res);
497 let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
498 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
499 let vis = this.rebuild_vis(&vis);
500 if let Some(attrs) = attrs {
501 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
504 let item = hir::Item {
506 ident: this.lower_ident(ident),
509 span: this.lower_span(span),
511 hir::OwnerNode::Item(this.arena.alloc(item))
515 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
516 hir::ItemKind::Use(path, hir::UseKind::Single)
518 UseTreeKind::Glob => {
519 let path = self.lower_path(
521 &Path { segments, span: path.span, tokens: None },
524 hir::ItemKind::Use(path, hir::UseKind::Glob)
526 UseTreeKind::Nested(ref trees) => {
527 // Nested imports are desugared into simple imports.
528 // So, if we start with
531 // pub(x) use foo::{a, b};
534 // we will create three items:
537 // pub(x) use foo::a;
538 // pub(x) use foo::b;
539 // pub(x) use foo::{}; // <-- this is called the `ListStem`
542 // The first two are produced by recursively invoking
543 // `lower_use_tree` (and indeed there may be things
544 // like `use foo::{a::{b, c}}` and so forth). They
545 // wind up being directly added to
546 // `self.items`. However, the structure of this
547 // function also requires us to return one item, and
548 // for that we return the `{}` import (called the
551 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
553 // Add all the nested `PathListItem`s to the HIR.
554 for &(ref use_tree, id) in trees {
555 let new_hir_id = self.resolver.local_def_id(id);
557 let mut prefix = prefix.clone();
559 // Give the segments new node-ids since they are being cloned.
560 for seg in &mut prefix.segments {
561 seg.id = self.resolver.next_node_id();
564 // Each `use` import is an item and thus are owners of the
565 // names in the path. Up to this point the nested import is
566 // the current owner, since we want each desugared import to
567 // own its own names, we have to adjust the owner before
568 // lowering the rest of the import.
569 self.with_hir_id_owner(id, |this| {
570 let mut vis = this.rebuild_vis(&vis);
571 let mut ident = *ident;
574 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
575 if let Some(attrs) = attrs {
576 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
579 let item = hir::Item {
581 ident: this.lower_ident(ident),
584 span: this.lower_span(use_tree.span),
586 hir::OwnerNode::Item(this.arena.alloc(item))
590 // Subtle and a bit hacky: we lower the privacy level
591 // of the list stem to "private" most of the time, but
592 // not for "restricted" paths. The key thing is that
593 // we don't want it to stay as `pub` (with no caveats)
594 // because that affects rustdoc and also the lints
595 // about `pub` items. But we can't *always* make it
596 // private -- particularly not for restricted paths --
597 // because it contains node-ids that would then be
598 // unused, failing the check that HirIds are "densely
601 hir::VisibilityKind::Public
602 | hir::VisibilityKind::Crate(_)
603 | hir::VisibilityKind::Inherited => {
605 self.lower_span(prefix.span.shrink_to_lo()),
606 hir::VisibilityKind::Inherited,
609 hir::VisibilityKind::Restricted { .. } => {
610 // Do nothing here, as described in the comment on the match.
614 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
615 let res = self.lower_res(res);
616 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
617 hir::ItemKind::Use(path, hir::UseKind::ListStem)
622 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
623 /// many times in the HIR tree; for each occurrence, we need to assign distinct
624 /// `NodeId`s. (See, e.g., #56128.)
625 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
626 debug!("rebuild_use_path(path = {:?})", path);
628 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
630 hir_id: seg.hir_id.map(|_| self.next_id()),
633 infer_args: seg.infer_args,
635 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
638 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
639 let vis_kind = match vis.node {
640 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
641 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
642 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
643 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
644 hir::VisibilityKind::Restricted {
645 path: self.rebuild_use_path(path),
646 hir_id: self.next_id(),
650 respan(self.lower_span(vis.span), vis_kind)
653 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
654 let hir_id = self.lower_node_id(i.id);
655 let def_id = hir_id.expect_owner();
656 self.lower_attrs(hir_id, &i.attrs);
657 let item = hir::ForeignItem {
659 ident: self.lower_ident(i.ident),
661 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
662 let fdec = &sig.decl;
663 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
666 AnonymousLifetimeMode::PassThrough,
669 // Disallow `impl Trait` in foreign items.
670 this.lower_fn_decl(fdec, None, false, None),
671 this.lower_fn_params_to_names(fdec),
676 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
678 ForeignItemKind::Static(ref t, m, _) => {
679 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
680 hir::ForeignItemKind::Static(ty, m)
682 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
683 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
685 vis: self.lower_visibility(&i.vis),
686 span: self.lower_span(i.span),
688 self.arena.alloc(item)
691 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
692 hir::ForeignItemRef {
693 id: hir::ForeignItemId { def_id: self.resolver.local_def_id(i.id) },
694 ident: self.lower_ident(i.ident),
695 span: self.lower_span(i.span),
699 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
700 let id = self.lower_node_id(v.id);
701 self.lower_attrs(id, &v.attrs);
704 data: self.lower_variant_data(id, &v.data),
705 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
706 ident: self.lower_ident(v.ident),
707 span: self.lower_span(v.span),
711 fn lower_variant_data(
713 parent_id: hir::HirId,
715 ) -> hir::VariantData<'hir> {
717 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
719 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
722 VariantData::Tuple(ref fields, id) => {
723 let ctor_id = self.lower_node_id(id);
724 self.alias_attrs(ctor_id, parent_id);
725 hir::VariantData::Tuple(
726 self.arena.alloc_from_iter(
727 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
732 VariantData::Unit(id) => {
733 let ctor_id = self.lower_node_id(id);
734 self.alias_attrs(ctor_id, parent_id);
735 hir::VariantData::Unit(ctor_id)
740 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
741 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
742 let t = self.lower_path_ty(
746 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
747 ImplTraitContext::disallowed(),
751 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
753 let hir_id = self.lower_node_id(f.id);
754 self.lower_attrs(hir_id, &f.attrs);
756 span: self.lower_span(f.span),
758 ident: match f.ident {
759 Some(ident) => self.lower_ident(ident),
760 // FIXME(jseyfried): positional field hygiene.
761 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
763 vis: self.lower_visibility(&f.vis),
768 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
769 let hir_id = self.lower_node_id(i.id);
770 let trait_item_def_id = hir_id.expect_owner();
772 let (generics, kind) = match i.kind {
773 AssocItemKind::Const(_, ref ty, ref default) => {
774 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
775 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
776 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
778 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
779 let names = self.lower_fn_params_to_names(&sig.decl);
780 let (generics, sig) =
781 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
782 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
784 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
785 let asyncness = sig.header.asyncness;
787 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
788 let (generics, sig) = self.lower_method_sig(
793 asyncness.opt_return_id(),
795 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
797 AssocItemKind::TyAlias(box TyAlias { ref generics, ref bounds, ref ty, .. }) => {
798 let ty = ty.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
799 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
800 let kind = hir::TraitItemKind::Type(
801 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
807 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
810 self.lower_attrs(hir_id, &i.attrs);
811 let item = hir::TraitItem {
812 def_id: trait_item_def_id,
813 ident: self.lower_ident(i.ident),
816 span: self.lower_span(i.span),
818 self.arena.alloc(item)
821 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
822 let (kind, has_default) = match &i.kind {
823 AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
824 AssocItemKind::TyAlias(box TyAlias { ty, .. }) => {
825 (hir::AssocItemKind::Type, ty.is_some())
827 AssocItemKind::Fn(box Fn { sig, body, .. }) => {
828 (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, body.is_some())
830 AssocItemKind::MacCall(..) => unimplemented!(),
832 let id = hir::TraitItemId { def_id: self.resolver.local_def_id(i.id) };
833 let defaultness = hir::Defaultness::Default { has_value: has_default };
836 ident: self.lower_ident(i.ident),
837 span: self.lower_span(i.span),
843 /// Construct `ExprKind::Err` for the given `span`.
844 crate fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
845 self.expr(span, hir::ExprKind::Err, AttrVec::new())
848 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
849 let impl_item_def_id = self.resolver.local_def_id(i.id);
851 let (generics, kind) = match &i.kind {
852 AssocItemKind::Const(_, ty, expr) => {
853 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
855 hir::Generics::empty(),
856 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
859 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
860 self.current_item = Some(i.span);
861 let asyncness = sig.header.asyncness;
863 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
864 let impl_trait_return_allow = !self.is_in_trait_impl;
865 let (generics, sig) = self.lower_method_sig(
869 impl_trait_return_allow,
870 asyncness.opt_return_id(),
873 (generics, hir::ImplItemKind::Fn(sig, body_id))
875 AssocItemKind::TyAlias(box TyAlias { generics, ty, .. }) => {
876 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
877 let kind = match ty {
879 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
880 hir::ImplItemKind::TyAlias(ty)
883 let ty = self.lower_ty(
885 ImplTraitContext::TypeAliasesOpaqueTy {
886 capturable_lifetimes: &mut FxHashSet::default(),
889 hir::ImplItemKind::TyAlias(ty)
894 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
897 // Since `default impl` is not yet implemented, this is always true in impls.
898 let has_value = true;
899 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
900 let hir_id = self.lower_node_id(i.id);
901 self.lower_attrs(hir_id, &i.attrs);
902 let item = hir::ImplItem {
903 def_id: hir_id.expect_owner(),
904 ident: self.lower_ident(i.ident),
906 vis: self.lower_visibility(&i.vis),
909 span: self.lower_span(i.span),
911 self.arena.alloc(item)
914 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
915 // Since `default impl` is not yet implemented, this is always true in impls.
916 let has_value = true;
917 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
919 id: hir::ImplItemId { def_id: self.resolver.local_def_id(i.id) },
920 ident: self.lower_ident(i.ident),
921 span: self.lower_span(i.span),
923 kind: match &i.kind {
924 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
925 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
926 AssocItemKind::Fn(box Fn { sig, .. }) => {
927 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
929 AssocItemKind::MacCall(..) => unimplemented!(),
931 trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
935 /// If an `explicit_owner` is given, this method allocates the `HirId` in
936 /// the address space of that item instead of the item currently being
937 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
938 /// lower a `Visibility` value although we haven't lowered the owning
939 /// `ImplItem` in question yet.
940 fn lower_visibility(&mut self, v: &Visibility) -> hir::Visibility<'hir> {
941 let node = match v.kind {
942 VisibilityKind::Public => hir::VisibilityKind::Public,
943 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
944 VisibilityKind::Restricted { ref path, id } => {
945 debug!("lower_visibility: restricted path id = {:?}", id);
946 let lowered_id = self.lower_node_id(id);
947 hir::VisibilityKind::Restricted {
948 path: self.lower_path(id, path, ParamMode::Explicit),
952 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
954 respan(self.lower_span(v.span), node)
957 fn lower_defaultness(
961 ) -> (hir::Defaultness, Option<Span>) {
963 Defaultness::Default(sp) => {
964 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
966 Defaultness::Final => {
968 (hir::Defaultness::Final, None)
975 params: &'hir [hir::Param<'hir>],
976 value: hir::Expr<'hir>,
978 let body = hir::Body { generator_kind: self.generator_kind, params, value };
980 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
981 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
985 pub(super) fn lower_body(
987 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
989 let prev_gen_kind = self.generator_kind.take();
990 let task_context = self.task_context.take();
991 let (parameters, result) = f(self);
992 let body_id = self.record_body(parameters, result);
993 self.task_context = task_context;
994 self.generator_kind = prev_gen_kind;
998 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
999 let hir_id = self.lower_node_id(param.id);
1000 self.lower_attrs(hir_id, ¶m.attrs);
1003 pat: self.lower_pat(¶m.pat),
1004 ty_span: self.lower_span(param.ty.span),
1005 span: self.lower_span(param.span),
1009 pub(super) fn lower_fn_body(
1012 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1014 self.lower_body(|this| {
1016 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1022 fn lower_fn_body_block(
1026 body: Option<&Block>,
1028 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1031 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1033 Some(block) => self.lower_block_expr(block),
1034 None => self.expr_err(span),
1038 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1039 self.lower_body(|this| {
1043 Some(expr) => this.lower_expr_mut(expr),
1044 None => this.expr_err(span),
1050 fn lower_maybe_async_body(
1055 body: Option<&Block>,
1057 let closure_id = match asyncness {
1058 Async::Yes { closure_id, .. } => closure_id,
1059 Async::No => return self.lower_fn_body_block(span, decl, body),
1062 self.lower_body(|this| {
1063 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1064 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1066 // Async function parameters are lowered into the closure body so that they are
1067 // captured and so that the drop order matches the equivalent non-async functions.
1071 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1077 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1079 // let __arg2 = __arg2;
1080 // let <pattern> = __arg2;
1081 // let __arg1 = __arg1;
1082 // let <pattern> = __arg1;
1083 // let __arg0 = __arg0;
1084 // let <pattern> = __arg0;
1085 // drop-temps { <body> } // see comments later in fn for details
1089 // If `<pattern>` is a simple ident, then it is lowered to a single
1090 // `let <pattern> = <pattern>;` statement as an optimization.
1092 // Note that the body is embedded in `drop-temps`; an
1093 // equivalent desugaring would be `return { <body>
1094 // };`. The key point is that we wish to drop all the
1095 // let-bound variables and temporaries created in the body
1096 // (and its tail expression!) before we drop the
1097 // parameters (c.f. rust-lang/rust#64512).
1098 for (index, parameter) in decl.inputs.iter().enumerate() {
1099 let parameter = this.lower_param(parameter);
1100 let span = parameter.pat.span;
1102 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1103 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1104 let (ident, is_simple_parameter) = match parameter.pat.kind {
1105 hir::PatKind::Binding(
1106 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
1111 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1112 // we can keep the same name for the parameter.
1113 // This lets rustdoc render it correctly in documentation.
1114 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1115 hir::PatKind::Wild => {
1116 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1119 // Replace the ident for bindings that aren't simple.
1120 let name = format!("__arg{}", index);
1121 let ident = Ident::from_str(&name);
1127 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1129 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1132 // If this is the simple case, this parameter will end up being the same as the
1133 // original parameter, but with a different pattern id.
1134 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1135 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1136 let new_parameter = hir::Param {
1137 hir_id: parameter.hir_id,
1138 pat: new_parameter_pat,
1139 ty_span: this.lower_span(parameter.ty_span),
1140 span: this.lower_span(parameter.span),
1143 if is_simple_parameter {
1144 // If this is the simple case, then we only insert one statement that is
1145 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1146 // `HirId`s are densely assigned.
1147 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1148 let stmt = this.stmt_let_pat(
1153 hir::LocalSource::AsyncFn,
1155 statements.push(stmt);
1157 // If this is not the simple case, then we construct two statements:
1160 // let __argN = __argN;
1161 // let <pat> = __argN;
1164 // The first statement moves the parameter into the closure and thus ensures
1165 // that the drop order is correct.
1167 // The second statement creates the bindings that the user wrote.
1169 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1170 // because the user may have specified a `ref mut` binding in the next
1172 let (move_pat, move_id) = this.pat_ident_binding_mode(
1175 hir::BindingAnnotation::Mutable,
1177 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1178 let move_stmt = this.stmt_let_pat(
1183 hir::LocalSource::AsyncFn,
1186 // Construct the `let <pat> = __argN;` statement. We re-use the original
1187 // parameter's pattern so that `HirId`s are densely assigned.
1188 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1189 let pattern_stmt = this.stmt_let_pat(
1194 hir::LocalSource::AsyncFn,
1197 statements.push(move_stmt);
1198 statements.push(pattern_stmt);
1201 parameters.push(new_parameter);
1204 let body_span = body.map_or(span, |b| b.span);
1205 let async_expr = this.make_async_expr(
1210 hir::AsyncGeneratorKind::Fn,
1212 // Create a block from the user's function body:
1213 let user_body = this.lower_block_expr_opt(body_span, body);
1215 // Transform into `drop-temps { <user-body> }`, an expression:
1216 let desugared_span =
1217 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1218 let user_body = this.expr_drop_temps(
1220 this.arena.alloc(user_body),
1224 // As noted above, create the final block like
1228 // let $param_pattern = $raw_param;
1230 // drop-temps { <user-body> }
1233 let body = this.block_all(
1235 this.arena.alloc_from_iter(statements),
1239 this.expr_block(body, AttrVec::new())
1244 this.arena.alloc_from_iter(parameters),
1245 this.expr(body_span, async_expr, AttrVec::new()),
1250 fn lower_method_sig(
1252 generics: &Generics,
1254 fn_def_id: LocalDefId,
1255 impl_trait_return_allow: bool,
1256 is_async: Option<NodeId>,
1257 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1258 let header = self.lower_fn_header(sig.header);
1259 let (generics, decl) = self.add_in_band_defs(
1262 AnonymousLifetimeMode::PassThrough,
1266 Some((fn_def_id, idty)),
1267 impl_trait_return_allow,
1272 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1275 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1277 unsafety: self.lower_unsafety(h.unsafety),
1278 asyncness: self.lower_asyncness(h.asyncness),
1279 constness: self.lower_constness(h.constness),
1280 abi: self.lower_extern(h.ext),
1284 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1285 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1286 self.error_on_invalid_abi(abi);
1291 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1293 Extern::None => abi::Abi::Rust,
1294 Extern::Implicit => abi::Abi::FALLBACK,
1295 Extern::Explicit(abi) => self.lower_abi(abi),
1299 fn error_on_invalid_abi(&self, abi: StrLit) {
1300 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1301 .span_label(abi.span, "invalid ABI")
1302 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1306 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1308 Async::Yes { .. } => hir::IsAsync::Async,
1309 Async::No => hir::IsAsync::NotAsync,
1313 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1315 Const::Yes(_) => hir::Constness::Const,
1316 Const::No => hir::Constness::NotConst,
1320 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1322 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1323 Unsafe::No => hir::Unsafety::Normal,
1327 pub(super) fn lower_generics_mut(
1329 generics: &Generics,
1330 itctx: ImplTraitContext<'_, 'hir>,
1331 ) -> GenericsCtor<'hir> {
1332 // Error if `?Trait` bounds in where clauses don't refer directly to type paramters.
1333 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1334 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1335 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1336 // where clauses for `?Sized`.
1337 for pred in &generics.where_clause.predicates {
1338 let bound_pred = match *pred {
1339 WherePredicate::BoundPredicate(ref bound_pred) => bound_pred,
1342 let compute_is_param = || {
1343 // Check if the where clause type is a plain type parameter.
1346 .get_partial_res(bound_pred.bounded_ty.id)
1347 .map(|d| (d.base_res(), d.unresolved_segments()))
1349 Some((Res::Def(DefKind::TyParam, def_id), 0))
1350 if bound_pred.bound_generic_params.is_empty() =>
1355 .any(|p| def_id == self.resolver.local_def_id(p.id).to_def_id())
1357 // Either the `bounded_ty` is not a plain type parameter, or
1358 // it's not found in the generic type parameters list.
1362 // We only need to compute this once per `WherePredicate`, but don't
1363 // need to compute this at all unless there is a Maybe bound.
1364 let mut is_param: Option<bool> = None;
1365 for bound in &bound_pred.bounds {
1366 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1369 let is_param = *is_param.get_or_insert_with(compute_is_param);
1371 self.diagnostic().span_err(
1373 "`?Trait` bounds are only permitted at the \
1374 point where a type parameter is declared",
1381 params: self.lower_generic_params_mut(&generics.params, itctx).collect(),
1382 where_clause: self.lower_where_clause(&generics.where_clause),
1383 span: self.lower_span(generics.span),
1387 pub(super) fn lower_generics(
1389 generics: &Generics,
1390 itctx: ImplTraitContext<'_, 'hir>,
1391 ) -> hir::Generics<'hir> {
1392 let generics_ctor = self.lower_generics_mut(generics, itctx);
1393 generics_ctor.into_generics(self.arena)
1396 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1397 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1399 predicates: this.arena.alloc_from_iter(
1400 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1402 span: this.lower_span(wc.span),
1407 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1409 WherePredicate::BoundPredicate(WhereBoundPredicate {
1410 ref bound_generic_params,
1414 }) => self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1415 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1416 bound_generic_params: this
1417 .lower_generic_params(bound_generic_params, ImplTraitContext::disallowed()),
1418 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1419 bounds: this.arena.alloc_from_iter(bounds.iter().map(|bound| {
1420 this.lower_param_bound(bound, ImplTraitContext::disallowed())
1422 span: this.lower_span(span),
1425 WherePredicate::RegionPredicate(WhereRegionPredicate {
1429 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1430 span: self.lower_span(span),
1431 lifetime: self.lower_lifetime(lifetime),
1432 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1434 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1435 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1436 hir_id: self.lower_node_id(id),
1437 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1438 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1439 span: self.lower_span(span),
1446 /// Helper struct for delayed construction of Generics.
1447 pub(super) struct GenericsCtor<'hir> {
1448 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1449 where_clause: hir::WhereClause<'hir>,
1453 impl<'hir> GenericsCtor<'hir> {
1454 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1456 params: arena.alloc_from_iter(self.params),
1457 where_clause: self.where_clause,