1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition};
5 use rustc_ast::node_id::NodeMap;
7 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_errors::struct_span_err;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::LocalDefId;
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(&mut self, impl_ref: &Option<TraitRef>, f: impl FnOnce(&mut Self)) {
30 let old = self.lctx.is_in_trait_impl;
31 self.lctx.is_in_trait_impl = impl_ref.is_some();
33 self.lctx.is_in_trait_impl = old;
37 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
38 fn visit_item(&mut self, item: &'a Item) {
39 let mut item_hir_id = None;
40 self.lctx.with_hir_id_owner(item.id, |lctx| {
41 lctx.without_in_scope_lifetime_defs(|lctx| {
42 if let Some(hir_item) = lctx.lower_item(item) {
43 let id = lctx.insert_item(hir_item);
44 item_hir_id = Some(id);
49 if let Some(hir_id) = item_hir_id {
50 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
51 let this = &mut ItemLowerer { lctx: this };
53 ItemKind::Mod(..) => {
54 let def_id = this.lctx.lower_node_id(item.id).expect_owner();
55 let old_current_module =
56 mem::replace(&mut this.lctx.current_module, def_id);
57 visit::walk_item(this, item);
58 this.lctx.current_module = old_current_module;
60 ItemKind::Impl(box ImplKind { ref of_trait, .. }) => {
61 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
63 _ => visit::walk_item(this, item),
69 fn visit_fn(&mut self, fk: FnKind<'a>, sp: Span, _: NodeId) {
71 FnKind::Fn(FnCtxt::Foreign, _, sig, _, _) => {
72 self.visit_fn_header(&sig.header);
73 visit::walk_fn_decl(self, &sig.decl);
74 // Don't visit the foreign function body even if it has one, since lowering the
75 // body would have no meaning and will have already been caught as a parse error.
77 _ => visit::walk_fn(self, fk, sp),
81 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
82 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
84 let hir_item = lctx.lower_trait_item(item);
85 let id = hir_item.trait_item_id();
86 lctx.trait_items.insert(id, hir_item);
87 lctx.modules.entry(lctx.current_module).or_default().trait_items.insert(id);
90 let hir_item = lctx.lower_impl_item(item);
91 let id = hir_item.impl_item_id();
92 lctx.impl_items.insert(id, hir_item);
93 lctx.modules.entry(lctx.current_module).or_default().impl_items.insert(id);
97 visit::walk_assoc_item(self, item, ctxt);
100 fn visit_foreign_item(&mut self, item: &'a ForeignItem) {
101 self.lctx.allocate_hir_id_counter(item.id);
102 self.lctx.with_hir_id_owner(item.id, |lctx| {
103 let hir_item = lctx.lower_foreign_item(item);
104 let id = hir_item.foreign_item_id();
105 lctx.foreign_items.insert(id, hir_item);
106 lctx.modules.entry(lctx.current_module).or_default().foreign_items.insert(id);
109 visit::walk_foreign_item(self, item);
113 impl<'hir> LoweringContext<'_, 'hir> {
114 // Same as the method above, but accepts `hir::GenericParam`s
115 // instead of `ast::GenericParam`s.
116 // This should only be used with generics that have already had their
117 // in-band lifetimes added. In practice, this means that this function is
118 // only used when lowering a child item of a trait or impl.
119 fn with_parent_item_lifetime_defs<T>(
121 parent_hir_id: hir::ItemId,
122 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
124 let old_len = self.in_scope_lifetimes.len();
126 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
127 hir::ItemKind::Impl(hir::Impl { ref generics, .. })
128 | hir::ItemKind::Trait(_, _, ref generics, ..) => generics.params,
131 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
132 hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()),
135 self.in_scope_lifetimes.extend(lt_def_names);
139 self.in_scope_lifetimes.truncate(old_len);
143 // Clears (and restores) the `in_scope_lifetimes` field. Used when
144 // visiting nested items, which never inherit in-scope lifetimes
145 // from their surrounding environment.
146 fn without_in_scope_lifetime_defs<T>(
148 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
150 let old_in_scope_lifetimes = mem::replace(&mut self.in_scope_lifetimes, vec![]);
152 // this vector is only used when walking over impl headers,
153 // input types, and the like, and should not be non-empty in
155 assert!(self.lifetimes_to_define.is_empty());
159 assert!(self.in_scope_lifetimes.is_empty());
160 self.in_scope_lifetimes = old_in_scope_lifetimes;
165 pub(super) fn lower_mod(&mut self, items: &[P<Item>], inner: Span) -> hir::Mod<'hir> {
168 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_id(x))),
172 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
173 let node_ids = match i.kind {
174 ItemKind::Use(ref use_tree) => {
175 let mut vec = smallvec![i.id];
176 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
179 ItemKind::MacroDef(..) => SmallVec::new(),
180 ItemKind::Fn(..) | ItemKind::Impl(box ImplKind { of_trait: None, .. }) => {
183 _ => smallvec![i.id],
188 .map(|node_id| hir::ItemId {
189 def_id: self.allocate_hir_id_counter(node_id).expect_owner(),
194 fn lower_item_id_use_tree(
198 vec: &mut SmallVec<[NodeId; 1]>,
201 UseTreeKind::Nested(ref nested_vec) => {
202 for &(ref nested, id) in nested_vec {
204 self.lower_item_id_use_tree(nested, id, vec);
207 UseTreeKind::Glob => {}
208 UseTreeKind::Simple(_, id1, id2) => {
210 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
218 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
219 let mut ident = i.ident;
220 let mut vis = self.lower_visibility(&i.vis, None);
222 if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind {
223 if !macro_rules || self.sess.contains_name(&i.attrs, sym::macro_export) {
224 let hir_id = self.lower_node_id(i.id);
225 self.lower_attrs(hir_id, &i.attrs);
226 let body = P(self.lower_mac_args(body));
227 self.exported_macros.push(hir::MacroDef {
230 def_id: hir_id.expect_owner(),
232 ast: MacroDef { body, macro_rules },
235 for a in i.attrs.iter() {
236 let a = self.lower_attr(a);
237 self.non_exported_macro_attrs.push(a);
243 let hir_id = self.lower_node_id(i.id);
244 let attrs = self.lower_attrs(hir_id, &i.attrs);
245 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
246 Some(hir::Item { def_id: hir_id.expect_owner(), ident, kind, vis, span: i.span })
255 attrs: Option<&'hir [Attribute]>,
256 vis: &mut hir::Visibility<'hir>,
258 ) -> hir::ItemKind<'hir> {
260 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
261 ItemKind::Use(ref use_tree) => {
262 // Start with an empty prefix.
263 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
265 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
267 ItemKind::Static(ref t, m, ref e) => {
268 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
269 hir::ItemKind::Static(ty, m, body_id)
271 ItemKind::Const(_, ref t, ref e) => {
272 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
273 hir::ItemKind::Const(ty, body_id)
275 ItemKind::Fn(box FnKind(
277 FnSig { ref decl, header, span: fn_sig_span },
281 let fn_def_id = self.resolver.local_def_id(id);
282 self.with_new_scopes(|this| {
283 this.current_item = Some(ident.span);
285 // Note: we don't need to change the return type from `T` to
286 // `impl Future<Output = T>` here because lower_body
287 // only cares about the input argument patterns in the function
288 // declaration (decl), not the return types.
289 let asyncness = header.asyncness;
291 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
293 let (generics, decl) = this.add_in_band_defs(
296 AnonymousLifetimeMode::PassThrough,
298 let ret_id = asyncness.opt_return_id();
301 Some((fn_def_id.to_def_id(), idty)),
307 let sig = hir::FnSig {
309 header: this.lower_fn_header(header, fn_sig_span, id),
312 hir::ItemKind::Fn(sig, generics, body_id)
315 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
316 ModKind::Loaded(items, _, inner_span) => {
317 hir::ItemKind::Mod(self.lower_mod(items, *inner_span))
319 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
321 ItemKind::ForeignMod(ref fm) => {
322 if fm.abi.is_none() {
323 self.maybe_lint_missing_abi(span, id, abi::Abi::C { unwind: false });
325 hir::ItemKind::ForeignMod {
326 abi: fm.abi.map_or(abi::Abi::C { unwind: false }, |abi| self.lower_abi(abi)),
329 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
332 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
333 ItemKind::TyAlias(box TyAliasKind(_, ref gen, _, Some(ref ty))) => {
336 // type Foo = impl Trait
341 // opaque type Foo1: Trait
342 let ty = self.lower_ty(
344 ImplTraitContext::OtherOpaqueTy {
345 capturable_lifetimes: &mut FxHashSet::default(),
346 origin: hir::OpaqueTyOrigin::TyAlias,
349 let generics = self.lower_generics(gen, ImplTraitContext::disallowed());
350 hir::ItemKind::TyAlias(ty, generics)
352 ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, None)) => {
353 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
354 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
355 hir::ItemKind::TyAlias(ty, generics)
357 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
359 variants: self.arena.alloc_from_iter(
360 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
363 self.lower_generics(generics, ImplTraitContext::disallowed()),
365 ItemKind::Struct(ref struct_def, ref generics) => {
366 let struct_def = self.lower_variant_data(hir_id, struct_def);
367 hir::ItemKind::Struct(
369 self.lower_generics(generics, ImplTraitContext::disallowed()),
372 ItemKind::Union(ref vdata, ref generics) => {
373 let vdata = self.lower_variant_data(hir_id, vdata);
374 hir::ItemKind::Union(
376 self.lower_generics(generics, ImplTraitContext::disallowed()),
379 ItemKind::Impl(box ImplKind {
384 generics: ref ast_generics,
385 of_trait: ref trait_ref,
387 items: ref impl_items,
389 // Lower the "impl header" first. This ordering is important
390 // for in-band lifetimes! Consider `'a` here:
392 // impl Foo<'a> for u32 {
393 // fn method(&'a self) { .. }
396 // Because we start by lowering the `Foo<'a> for u32`
397 // part, we will add `'a` to the list of generics on
398 // the impl. When we then encounter it later in the
399 // method, it will not be considered an in-band
400 // lifetime to be added, but rather a reference to a
402 let lowered_trait_def_id = self.lower_node_id(id).expect_owner();
403 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
405 lowered_trait_def_id,
406 AnonymousLifetimeMode::CreateParameter,
408 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
409 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
412 if let Some(ref trait_ref) = trait_ref {
413 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
417 .push(lowered_trait_def_id);
421 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
423 (trait_ref, lowered_ty)
428 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
429 this.arena.alloc_from_iter(
430 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
434 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
435 // to not cause an assertion failure inside the `lower_defaultness` function.
437 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
438 hir::ItemKind::Impl(hir::Impl {
439 unsafety: self.lower_unsafety(unsafety),
443 constness: self.lower_constness(constness),
447 items: new_impl_items,
450 ItemKind::Trait(box TraitKind(
457 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
460 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
461 hir::ItemKind::Trait(
463 self.lower_unsafety(unsafety),
464 self.lower_generics(generics, ImplTraitContext::disallowed()),
469 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
470 self.lower_generics(generics, ImplTraitContext::disallowed()),
471 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
473 ItemKind::MacroDef(..) | ItemKind::MacCall(..) => {
474 panic!("`TyMac` should have been expanded by now")
484 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
485 let mut capturable_lifetimes;
486 let itctx = if self.sess.features_untracked().impl_trait_in_bindings {
487 capturable_lifetimes = FxHashSet::default();
488 ImplTraitContext::OtherOpaqueTy {
489 capturable_lifetimes: &mut capturable_lifetimes,
490 origin: hir::OpaqueTyOrigin::Misc,
493 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
495 let ty = self.lower_ty(ty, itctx);
496 (ty, self.lower_const_body(span, body))
504 vis: &mut hir::Visibility<'hir>,
506 attrs: Option<&'hir [Attribute]>,
507 ) -> hir::ItemKind<'hir> {
508 debug!("lower_use_tree(tree={:?})", tree);
509 debug!("lower_use_tree: vis = {:?}", vis);
511 let path = &tree.prefix;
512 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
515 UseTreeKind::Simple(rename, id1, id2) => {
516 *ident = tree.ident();
518 // First, apply the prefix to the path.
519 let mut path = Path { segments, span: path.span, tokens: None };
521 // Correctly resolve `self` imports.
522 if path.segments.len() > 1
523 && path.segments.last().unwrap().ident.name == kw::SelfLower
525 let _ = path.segments.pop();
526 if rename.is_none() {
527 *ident = path.segments.last().unwrap().ident;
531 let mut resolutions = self.expect_full_res_from_use(id);
532 // We want to return *something* from this function, so hold onto the first item
534 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
536 // Here, we are looping over namespaces, if they exist for the definition
537 // being imported. We only handle type and value namespaces because we
538 // won't be dealing with macros in the rest of the compiler.
539 // Essentially a single `use` which imports two names is desugared into
541 for (res, &new_node_id) in iter::zip(resolutions, &[id1, id2]) {
543 let mut path = path.clone();
544 for seg in &mut path.segments {
545 seg.id = self.resolver.next_node_id();
547 let span = path.span;
549 self.with_hir_id_owner(new_node_id, |this| {
550 let new_id = this.lower_node_id(new_node_id);
551 let res = this.lower_res(res);
552 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
553 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
554 let vis = this.rebuild_vis(&vis);
555 if let Some(attrs) = attrs {
556 this.attrs.insert(new_id, attrs);
559 this.insert_item(hir::Item {
560 def_id: new_id.expect_owner(),
569 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
570 hir::ItemKind::Use(path, hir::UseKind::Single)
572 UseTreeKind::Glob => {
573 let path = self.lower_path(
575 &Path { segments, span: path.span, tokens: None },
578 hir::ItemKind::Use(path, hir::UseKind::Glob)
580 UseTreeKind::Nested(ref trees) => {
581 // Nested imports are desugared into simple imports.
582 // So, if we start with
585 // pub(x) use foo::{a, b};
588 // we will create three items:
591 // pub(x) use foo::a;
592 // pub(x) use foo::b;
593 // pub(x) use foo::{}; // <-- this is called the `ListStem`
596 // The first two are produced by recursively invoking
597 // `lower_use_tree` (and indeed there may be things
598 // like `use foo::{a::{b, c}}` and so forth). They
599 // wind up being directly added to
600 // `self.items`. However, the structure of this
601 // function also requires us to return one item, and
602 // for that we return the `{}` import (called the
605 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
607 // Add all the nested `PathListItem`s to the HIR.
608 for &(ref use_tree, id) in trees {
609 let new_hir_id = self.lower_node_id(id);
611 let mut prefix = prefix.clone();
613 // Give the segments new node-ids since they are being cloned.
614 for seg in &mut prefix.segments {
615 seg.id = self.resolver.next_node_id();
618 // Each `use` import is an item and thus are owners of the
619 // names in the path. Up to this point the nested import is
620 // the current owner, since we want each desugared import to
621 // own its own names, we have to adjust the owner before
622 // lowering the rest of the import.
623 self.with_hir_id_owner(id, |this| {
624 let mut vis = this.rebuild_vis(&vis);
625 let mut ident = *ident;
628 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
629 if let Some(attrs) = attrs {
630 this.attrs.insert(new_hir_id, attrs);
633 this.insert_item(hir::Item {
634 def_id: new_hir_id.expect_owner(),
643 // Subtle and a bit hacky: we lower the privacy level
644 // of the list stem to "private" most of the time, but
645 // not for "restricted" paths. The key thing is that
646 // we don't want it to stay as `pub` (with no caveats)
647 // because that affects rustdoc and also the lints
648 // about `pub` items. But we can't *always* make it
649 // private -- particularly not for restricted paths --
650 // because it contains node-ids that would then be
651 // unused, failing the check that HirIds are "densely
654 hir::VisibilityKind::Public
655 | hir::VisibilityKind::Crate(_)
656 | hir::VisibilityKind::Inherited => {
657 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
659 hir::VisibilityKind::Restricted { .. } => {
660 // Do nothing here, as described in the comment on the match.
664 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
665 let res = self.lower_res(res);
666 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
667 hir::ItemKind::Use(path, hir::UseKind::ListStem)
672 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
673 /// many times in the HIR tree; for each occurrence, we need to assign distinct
674 /// `NodeId`s. (See, e.g., #56128.)
675 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
676 debug!("rebuild_use_path(path = {:?})", path);
678 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
680 hir_id: seg.hir_id.map(|_| self.next_id()),
683 infer_args: seg.infer_args,
685 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
688 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
689 let vis_kind = match vis.node {
690 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
691 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
692 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
693 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
694 hir::VisibilityKind::Restricted {
695 path: self.rebuild_use_path(path),
696 hir_id: self.next_id(),
700 respan(vis.span, vis_kind)
703 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
704 let hir_id = self.lower_node_id(i.id);
705 let def_id = hir_id.expect_owner();
706 self.lower_attrs(hir_id, &i.attrs);
711 ForeignItemKind::Fn(box FnKind(_, ref sig, ref generics, _)) => {
712 let fdec = &sig.decl;
713 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
716 AnonymousLifetimeMode::PassThrough,
719 // Disallow `impl Trait` in foreign items.
720 this.lower_fn_decl(fdec, None, false, None),
721 this.lower_fn_params_to_names(fdec),
726 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
728 ForeignItemKind::Static(ref t, m, _) => {
729 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
730 hir::ForeignItemKind::Static(ty, m)
732 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
733 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
735 vis: self.lower_visibility(&i.vis, None),
740 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef<'hir> {
741 hir::ForeignItemRef {
742 id: hir::ForeignItemId { def_id: self.lower_node_id(i.id).expect_owner() },
745 vis: self.lower_visibility(&i.vis, Some(i.id)),
749 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
750 self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
753 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
754 let id = self.lower_node_id(v.id);
755 self.lower_attrs(id, &v.attrs);
758 data: self.lower_variant_data(id, &v.data),
759 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
765 fn lower_variant_data(
767 parent_id: hir::HirId,
769 ) -> hir::VariantData<'hir> {
771 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
773 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
776 VariantData::Tuple(ref fields, id) => {
777 let ctor_id = self.lower_node_id(id);
778 self.alias_attrs(ctor_id, parent_id);
779 hir::VariantData::Tuple(
780 self.arena.alloc_from_iter(
781 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
786 VariantData::Unit(id) => {
787 let ctor_id = self.lower_node_id(id);
788 self.alias_attrs(ctor_id, parent_id);
789 hir::VariantData::Unit(ctor_id)
794 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
795 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
796 let t = self.lower_path_ty(
800 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
801 ImplTraitContext::disallowed(),
805 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
807 let hir_id = self.lower_node_id(f.id);
808 self.lower_attrs(hir_id, &f.attrs);
812 ident: match f.ident {
813 Some(ident) => ident,
814 // FIXME(jseyfried): positional field hygiene.
815 None => Ident::new(sym::integer(index), f.span),
817 vis: self.lower_visibility(&f.vis, None),
822 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
823 let hir_id = self.lower_node_id(i.id);
824 let trait_item_def_id = hir_id.expect_owner();
826 let (generics, kind) = match i.kind {
827 AssocItemKind::Const(_, ref ty, ref default) => {
828 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
829 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
830 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
832 AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, None)) => {
833 let names = self.lower_fn_params_to_names(&sig.decl);
834 let (generics, sig) =
835 self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id);
836 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
838 AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, Some(ref body))) => {
839 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
840 let (generics, sig) =
841 self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id);
842 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
844 AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref default)) => {
845 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
846 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
847 let kind = hir::TraitItemKind::Type(
848 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
854 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
857 self.lower_attrs(hir_id, &i.attrs);
858 hir::TraitItem { def_id: trait_item_def_id, ident: i.ident, generics, kind, span: i.span }
861 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
862 let (kind, has_default) = match &i.kind {
863 AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
864 AssocItemKind::TyAlias(box TyAliasKind(_, _, _, default)) => {
865 (hir::AssocItemKind::Type, default.is_some())
867 AssocItemKind::Fn(box FnKind(_, sig, _, default)) => {
868 (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, default.is_some())
870 AssocItemKind::MacCall(..) => unimplemented!(),
872 let id = hir::TraitItemId { def_id: self.lower_node_id(i.id).expect_owner() };
873 let defaultness = hir::Defaultness::Default { has_value: has_default };
874 hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind }
877 /// Construct `ExprKind::Err` for the given `span`.
878 crate fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
879 self.expr(span, hir::ExprKind::Err, AttrVec::new())
882 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
883 let impl_item_def_id = self.resolver.local_def_id(i.id);
885 let (generics, kind) = match &i.kind {
886 AssocItemKind::Const(_, ty, expr) => {
887 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
889 hir::Generics::empty(),
890 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
893 AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => {
894 self.current_item = Some(i.span);
895 let asyncness = sig.header.asyncness;
897 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
898 let impl_trait_return_allow = !self.is_in_trait_impl;
899 let (generics, sig) = self.lower_method_sig(
903 impl_trait_return_allow,
904 asyncness.opt_return_id(),
908 (generics, hir::ImplItemKind::Fn(sig, body_id))
910 AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, ty)) => {
911 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
912 let kind = match ty {
914 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
915 hir::ImplItemKind::TyAlias(ty)
918 let ty = self.lower_ty(
920 ImplTraitContext::OtherOpaqueTy {
921 capturable_lifetimes: &mut FxHashSet::default(),
922 origin: hir::OpaqueTyOrigin::TyAlias,
925 hir::ImplItemKind::TyAlias(ty)
930 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
933 // Since `default impl` is not yet implemented, this is always true in impls.
934 let has_value = true;
935 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
936 let hir_id = self.lower_node_id(i.id);
937 self.lower_attrs(hir_id, &i.attrs);
939 def_id: hir_id.expect_owner(),
942 vis: self.lower_visibility(&i.vis, None),
949 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
950 // Since `default impl` is not yet implemented, this is always true in impls.
951 let has_value = true;
952 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
954 id: hir::ImplItemId { def_id: self.lower_node_id(i.id).expect_owner() },
957 vis: self.lower_visibility(&i.vis, Some(i.id)),
959 kind: match &i.kind {
960 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
961 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
962 AssocItemKind::Fn(box FnKind(_, sig, ..)) => {
963 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
965 AssocItemKind::MacCall(..) => unimplemented!(),
970 /// If an `explicit_owner` is given, this method allocates the `HirId` in
971 /// the address space of that item instead of the item currently being
972 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
973 /// lower a `Visibility` value although we haven't lowered the owning
974 /// `ImplItem` in question yet.
978 explicit_owner: Option<NodeId>,
979 ) -> hir::Visibility<'hir> {
980 let node = match v.kind {
981 VisibilityKind::Public => hir::VisibilityKind::Public,
982 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
983 VisibilityKind::Restricted { ref path, id } => {
984 debug!("lower_visibility: restricted path id = {:?}", id);
985 let lowered_id = if let Some(owner) = explicit_owner {
986 self.lower_node_id_with_owner(id, owner)
988 self.lower_node_id(id)
990 let res = self.expect_full_res(id);
991 let res = self.lower_res(res);
992 hir::VisibilityKind::Restricted {
993 path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
997 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
1002 fn lower_defaultness(
1006 ) -> (hir::Defaultness, Option<Span>) {
1008 Defaultness::Default(sp) => (hir::Defaultness::Default { has_value }, Some(sp)),
1009 Defaultness::Final => {
1011 (hir::Defaultness::Final, None)
1018 params: &'hir [hir::Param<'hir>],
1019 value: hir::Expr<'hir>,
1021 let body = hir::Body { generator_kind: self.generator_kind, params, value };
1023 self.bodies.insert(id, body);
1027 pub(super) fn lower_body(
1029 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1031 let prev_gen_kind = self.generator_kind.take();
1032 let task_context = self.task_context.take();
1033 let (parameters, result) = f(self);
1034 let body_id = self.record_body(parameters, result);
1035 self.task_context = task_context;
1036 self.generator_kind = prev_gen_kind;
1040 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1041 let hir_id = self.lower_node_id(param.id);
1042 self.lower_attrs(hir_id, ¶m.attrs);
1045 pat: self.lower_pat(¶m.pat),
1046 ty_span: param.ty.span,
1051 pub(super) fn lower_fn_body(
1054 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1056 self.lower_body(|this| {
1058 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1064 fn lower_fn_body_block(
1068 body: Option<&Block>,
1070 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1073 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1075 Some(block) => self.lower_block_expr(block),
1076 None => self.expr_err(span),
1080 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1081 self.lower_body(|this| {
1085 Some(expr) => this.lower_expr_mut(expr),
1086 None => this.expr_err(span),
1092 fn lower_maybe_async_body(
1097 body: Option<&Block>,
1099 let closure_id = match asyncness {
1100 Async::Yes { closure_id, .. } => closure_id,
1101 Async::No => return self.lower_fn_body_block(span, decl, body),
1104 self.lower_body(|this| {
1105 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1106 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1108 // Async function parameters are lowered into the closure body so that they are
1109 // captured and so that the drop order matches the equivalent non-async functions.
1113 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1119 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1121 // let __arg2 = __arg2;
1122 // let <pattern> = __arg2;
1123 // let __arg1 = __arg1;
1124 // let <pattern> = __arg1;
1125 // let __arg0 = __arg0;
1126 // let <pattern> = __arg0;
1127 // drop-temps { <body> } // see comments later in fn for details
1131 // If `<pattern>` is a simple ident, then it is lowered to a single
1132 // `let <pattern> = <pattern>;` statement as an optimization.
1134 // Note that the body is embedded in `drop-temps`; an
1135 // equivalent desugaring would be `return { <body>
1136 // };`. The key point is that we wish to drop all the
1137 // let-bound variables and temporaries created in the body
1138 // (and its tail expression!) before we drop the
1139 // parameters (c.f. rust-lang/rust#64512).
1140 for (index, parameter) in decl.inputs.iter().enumerate() {
1141 let parameter = this.lower_param(parameter);
1142 let span = parameter.pat.span;
1144 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1145 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1146 let (ident, is_simple_parameter) = match parameter.pat.kind {
1147 hir::PatKind::Binding(
1148 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
1153 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1154 // we can keep the same name for the parameter.
1155 // This lets rustdoc render it correctly in documentation.
1156 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1157 hir::PatKind::Wild => {
1158 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1161 // Replace the ident for bindings that aren't simple.
1162 let name = format!("__arg{}", index);
1163 let ident = Ident::from_str(&name);
1169 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1171 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1174 // If this is the simple case, this parameter will end up being the same as the
1175 // original parameter, but with a different pattern id.
1176 let stmt_attrs = this.attrs.get(¶meter.hir_id).copied();
1177 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1178 let new_parameter = hir::Param {
1179 hir_id: parameter.hir_id,
1180 pat: new_parameter_pat,
1181 ty_span: parameter.ty_span,
1182 span: parameter.span,
1185 if is_simple_parameter {
1186 // If this is the simple case, then we only insert one statement that is
1187 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1188 // `HirId`s are densely assigned.
1189 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1190 let stmt = this.stmt_let_pat(
1195 hir::LocalSource::AsyncFn,
1197 statements.push(stmt);
1199 // If this is not the simple case, then we construct two statements:
1202 // let __argN = __argN;
1203 // let <pat> = __argN;
1206 // The first statement moves the parameter into the closure and thus ensures
1207 // that the drop order is correct.
1209 // The second statement creates the bindings that the user wrote.
1211 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1212 // because the user may have specified a `ref mut` binding in the next
1214 let (move_pat, move_id) = this.pat_ident_binding_mode(
1217 hir::BindingAnnotation::Mutable,
1219 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1220 let move_stmt = this.stmt_let_pat(
1225 hir::LocalSource::AsyncFn,
1228 // Construct the `let <pat> = __argN;` statement. We re-use the original
1229 // parameter's pattern so that `HirId`s are densely assigned.
1230 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1231 let pattern_stmt = this.stmt_let_pat(
1236 hir::LocalSource::AsyncFn,
1239 statements.push(move_stmt);
1240 statements.push(pattern_stmt);
1243 parameters.push(new_parameter);
1246 let body_span = body.map_or(span, |b| b.span);
1247 let async_expr = this.make_async_expr(
1252 hir::AsyncGeneratorKind::Fn,
1254 // Create a block from the user's function body:
1255 let user_body = this.lower_block_expr_opt(body_span, body);
1257 // Transform into `drop-temps { <user-body> }`, an expression:
1258 let desugared_span =
1259 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1260 let user_body = this.expr_drop_temps(
1262 this.arena.alloc(user_body),
1266 // As noted above, create the final block like
1270 // let $param_pattern = $raw_param;
1272 // drop-temps { <user-body> }
1275 let body = this.block_all(
1277 this.arena.alloc_from_iter(statements),
1281 this.expr_block(body, AttrVec::new())
1286 this.arena.alloc_from_iter(parameters),
1287 this.expr(body_span, async_expr, AttrVec::new()),
1292 fn lower_method_sig(
1294 generics: &Generics,
1296 fn_def_id: LocalDefId,
1297 impl_trait_return_allow: bool,
1298 is_async: Option<NodeId>,
1300 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1301 let header = self.lower_fn_header(sig.header, sig.span, id);
1302 let (generics, decl) = self.add_in_band_defs(
1305 AnonymousLifetimeMode::PassThrough,
1309 Some((fn_def_id.to_def_id(), idty)),
1310 impl_trait_return_allow,
1315 (generics, hir::FnSig { header, decl, span: sig.span })
1318 fn lower_fn_header(&mut self, h: FnHeader, span: Span, id: NodeId) -> hir::FnHeader {
1320 unsafety: self.lower_unsafety(h.unsafety),
1321 asyncness: self.lower_asyncness(h.asyncness),
1322 constness: self.lower_constness(h.constness),
1323 abi: self.lower_extern(h.ext, span, id),
1327 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1328 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1329 self.error_on_invalid_abi(abi);
1334 pub(super) fn lower_extern(&mut self, ext: Extern, span: Span, id: NodeId) -> abi::Abi {
1336 Extern::None => abi::Abi::Rust,
1337 Extern::Implicit => {
1338 self.maybe_lint_missing_abi(span, id, abi::Abi::C { unwind: false });
1339 abi::Abi::C { unwind: false }
1341 Extern::Explicit(abi) => self.lower_abi(abi),
1345 fn error_on_invalid_abi(&self, abi: StrLit) {
1346 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1347 .span_label(abi.span, "invalid ABI")
1348 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1352 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1354 Async::Yes { .. } => hir::IsAsync::Async,
1355 Async::No => hir::IsAsync::NotAsync,
1359 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1361 Const::Yes(_) => hir::Constness::Const,
1362 Const::No => hir::Constness::NotConst,
1366 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1368 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1369 Unsafe::No => hir::Unsafety::Normal,
1373 pub(super) fn lower_generics_mut(
1375 generics: &Generics,
1376 itctx: ImplTraitContext<'_, 'hir>,
1377 ) -> GenericsCtor<'hir> {
1378 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1379 // FIXME: this could probably be done with less rightward drift. It also looks like two
1380 // control paths where `report_error` is called are the only paths that advance to after the
1381 // match statement, so the error reporting could probably just be moved there.
1382 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1383 for pred in &generics.where_clause.predicates {
1384 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1385 'next_bound: for bound in &bound_pred.bounds {
1386 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1387 let report_error = |this: &mut Self| {
1388 this.diagnostic().span_err(
1389 bound_pred.bounded_ty.span,
1390 "`?Trait` bounds are only permitted at the \
1391 point where a type parameter is declared",
1394 // Check if the where clause type is a plain type parameter.
1395 match bound_pred.bounded_ty.kind {
1396 TyKind::Path(None, ref path)
1397 if path.segments.len() == 1
1398 && bound_pred.bound_generic_params.is_empty() =>
1400 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1402 .get_partial_res(bound_pred.bounded_ty.id)
1403 .map(|d| d.base_res())
1405 if let Some(def_id) = def_id.as_local() {
1406 for param in &generics.params {
1407 if let GenericParamKind::Type { .. } = param.kind {
1408 if def_id == self.resolver.local_def_id(param.id) {
1412 .push(bound.clone());
1413 continue 'next_bound;
1421 _ => report_error(self),
1429 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1430 where_clause: self.lower_where_clause(&generics.where_clause),
1431 span: generics.span,
1435 pub(super) fn lower_generics(
1437 generics: &Generics,
1438 itctx: ImplTraitContext<'_, 'hir>,
1439 ) -> hir::Generics<'hir> {
1440 let generics_ctor = self.lower_generics_mut(generics, itctx);
1441 generics_ctor.into_generics(self.arena)
1444 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1445 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1447 predicates: this.arena.alloc_from_iter(
1448 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1455 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1457 WherePredicate::BoundPredicate(WhereBoundPredicate {
1458 ref bound_generic_params,
1463 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1464 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1465 bound_generic_params: this.lower_generic_params(
1466 bound_generic_params,
1467 &NodeMap::default(),
1468 ImplTraitContext::disallowed(),
1470 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1471 bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1473 // Ignore `?Trait` bounds.
1474 // They were copied into type parameters already.
1475 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1477 this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1485 WherePredicate::RegionPredicate(WhereRegionPredicate {
1489 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1491 lifetime: self.lower_lifetime(lifetime),
1492 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1494 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1495 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1496 hir_id: self.lower_node_id(id),
1497 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1498 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1506 /// Helper struct for delayed construction of Generics.
1507 pub(super) struct GenericsCtor<'hir> {
1508 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1509 where_clause: hir::WhereClause<'hir>,
1513 impl<'hir> GenericsCtor<'hir> {
1514 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1516 params: arena.alloc_from_iter(self.params),
1517 where_clause: self.where_clause,