1 use super::LoweringContext;
2 use super::ImplTraitContext;
3 use super::ImplTraitPosition;
4 use super::ImplTraitTypeIdVisitor;
5 use super::AnonymousLifetimeMode;
9 use crate::hir::ptr::P;
10 use crate::hir::def_id::DefId;
11 use crate::hir::def::{Res, DefKind};
12 use crate::util::nodemap::NodeMap;
14 use rustc_target::spec::abi;
16 use std::collections::BTreeSet;
17 use smallvec::SmallVec;
20 use syntax::visit::{self, Visitor};
21 use syntax::source_map::{respan, DesugaringKind};
22 use syntax::symbol::{kw, sym};
25 use rustc_error_codes::*;
27 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
28 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
31 impl<'a, 'lowering, 'hir> ItemLowerer<'a, 'lowering, 'hir> {
32 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
36 let old = self.lctx.is_in_trait_impl;
37 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
43 self.lctx.is_in_trait_impl = old;
47 impl<'a, 'lowering, 'hir> Visitor<'a> for ItemLowerer<'a, 'lowering, 'hir> {
48 fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
49 let hir_id = self.lctx.lower_node_id(n);
51 self.lctx.modules.insert(hir_id, hir::ModuleItems {
52 items: BTreeSet::new(),
53 trait_items: BTreeSet::new(),
54 impl_items: BTreeSet::new(),
57 let old = self.lctx.current_module;
58 self.lctx.current_module = hir_id;
59 visit::walk_mod(self, m);
60 self.lctx.current_module = old;
63 fn visit_item(&mut self, item: &'a Item) {
64 let mut item_hir_id = None;
65 self.lctx.with_hir_id_owner(item.id, |lctx| {
66 lctx.without_in_scope_lifetime_defs(|lctx| {
67 if let Some(hir_item) = lctx.lower_item(item) {
68 item_hir_id = Some(hir_item.hir_id);
69 lctx.insert_item(hir_item);
74 if let Some(hir_id) = item_hir_id {
75 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
76 let this = &mut ItemLowerer { lctx: this };
77 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.kind {
78 this.with_trait_impl_ref(opt_trait_ref, |this| {
79 visit::walk_item(this, item)
82 visit::walk_item(this, item);
88 fn visit_trait_item(&mut self, item: &'a AssocItem) {
89 self.lctx.with_hir_id_owner(item.id, |lctx| {
90 let hir_item = lctx.lower_trait_item(item);
91 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
92 lctx.trait_items.insert(id, hir_item);
93 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
96 visit::walk_trait_item(self, item);
99 fn visit_impl_item(&mut self, item: &'a AssocItem) {
100 self.lctx.with_hir_id_owner(item.id, |lctx| {
101 let hir_item = lctx.lower_impl_item(item);
102 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
103 lctx.impl_items.insert(id, hir_item);
104 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
106 visit::walk_impl_item(self, item);
110 impl<'hir> LoweringContext<'_, 'hir> {
111 // Same as the method above, but accepts `hir::GenericParam`s
112 // instead of `ast::GenericParam`s.
113 // This should only be used with generics that have already had their
114 // in-band lifetimes added. In practice, this means that this function is
115 // only used when lowering a child item of a trait or impl.
116 fn with_parent_item_lifetime_defs<T>(
118 parent_hir_id: hir::HirId,
119 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
121 let old_len = self.in_scope_lifetimes.len();
123 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
124 hir::ItemKind::Impl(_, _, _, ref generics, ..)
125 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
130 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
131 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
134 self.in_scope_lifetimes.extend(lt_def_names);
138 self.in_scope_lifetimes.truncate(old_len);
142 // Clears (and restores) the `in_scope_lifetimes` field. Used when
143 // visiting nested items, which never inherit in-scope lifetimes
144 // from their surrounding environment.
145 fn without_in_scope_lifetime_defs<T>(
147 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
149 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
151 // this vector is only used when walking over impl headers,
152 // input types, and the like, and should not be non-empty in
154 assert!(self.lifetimes_to_define.is_empty());
158 assert!(self.in_scope_lifetimes.is_empty());
159 self.in_scope_lifetimes = old_in_scope_lifetimes;
164 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
167 item_ids: self.arena.alloc_from_iter(
168 m.items.iter().flat_map(|x| self.lower_item_id(x))
173 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
174 let node_ids = match i.kind {
175 ItemKind::Use(ref use_tree) => {
176 let mut vec = smallvec![i.id];
177 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
180 ItemKind::MacroDef(..) => SmallVec::new(),
182 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
183 ItemKind::Static(ref ty, ..) => {
184 let mut ids = smallvec![i.id];
185 if self.sess.features_untracked().impl_trait_in_bindings {
186 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
187 visitor.visit_ty(ty);
191 ItemKind::Const(ref ty, ..) => {
192 let mut ids = smallvec![i.id];
193 if self.sess.features_untracked().impl_trait_in_bindings {
194 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
195 visitor.visit_ty(ty);
199 _ => smallvec![i.id],
202 node_ids.into_iter().map(|node_id| hir::ItemId {
203 id: self.allocate_hir_id_counter(node_id)
207 fn lower_item_id_use_tree(
211 vec: &mut SmallVec<[NodeId; 1]>
214 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
216 self.lower_item_id_use_tree(nested, id, vec);
218 UseTreeKind::Glob => {}
219 UseTreeKind::Simple(_, id1, id2) => {
220 for (_, &id) in self.expect_full_res_from_use(base_id)
222 .zip([id1, id2].iter())
230 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
231 let mut ident = i.ident;
232 let mut vis = self.lower_visibility(&i.vis, None);
233 let attrs = self.lower_attrs_arena(&i.attrs);
235 if let ItemKind::MacroDef(ref def) = i.kind {
236 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
237 let body = self.lower_token_stream(def.body.inner_tokens());
238 let hir_id = self.lower_node_id(i.id);
239 self.exported_macros.push(hir::MacroDef {
249 self.non_exported_macro_attrs.extend(attrs.iter().cloned());
254 let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind);
257 hir_id: self.lower_node_id(i.id),
271 attrs: &'hir [Attribute],
272 vis: &mut hir::Visibility,
274 ) -> hir::ItemKind<'hir> {
276 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
277 ItemKind::Use(ref use_tree) => {
278 // Start with an empty prefix.
284 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
286 ItemKind::Static(ref t, m, ref e) => {
287 let ty = self.lower_ty(
289 if self.sess.features_untracked().impl_trait_in_bindings {
290 ImplTraitContext::OpaqueTy(None)
292 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
295 hir::ItemKind::Static(
296 self.arena.alloc(ty.into_inner()),
298 self.lower_const_body(span, Some(e)),
301 ItemKind::Const(ref t, ref e) => {
302 let ty = self.lower_ty(
304 if self.sess.features_untracked().impl_trait_in_bindings {
305 ImplTraitContext::OpaqueTy(None)
307 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
310 hir::ItemKind::Const(
311 self.arena.alloc(ty.into_inner()),
312 self.lower_const_body(span, Some(e))
315 ItemKind::Fn(FnSig { ref decl, header }, ref generics, ref body) => {
316 let fn_def_id = self.resolver.definitions().local_def_id(id);
317 self.with_new_scopes(|this| {
318 this.current_item = Some(ident.span);
320 // Note: we don't need to change the return type from `T` to
321 // `impl Future<Output = T>` here because lower_body
322 // only cares about the input argument patterns in the function
323 // declaration (decl), not the return types.
324 let body_id = this.lower_maybe_async_body(
327 header.asyncness.node,
331 let (generics, decl) = this.add_in_band_defs(
334 AnonymousLifetimeMode::PassThrough,
335 |this, idty| this.lower_fn_decl(
337 Some((fn_def_id, idty)),
339 header.asyncness.node.opt_return_id()
342 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
343 hir::ItemKind::Fn(sig, generics, body_id)
346 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
347 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
348 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
349 ItemKind::TyAlias(ref ty, ref generics) => match ty.kind.opaque_top_hack() {
351 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
352 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
353 hir::ItemKind::TyAlias(self.arena.alloc(ty.into_inner()), generics)
356 let ty = hir::OpaqueTy {
357 generics: self.lower_generics(generics, ImplTraitContext::OpaqueTy(None)),
358 bounds: self.lower_param_bounds(bounds, ImplTraitContext::OpaqueTy(None)),
360 origin: hir::OpaqueTyOrigin::TypeAlias,
362 hir::ItemKind::OpaqueTy(ty)
365 ItemKind::Enum(ref enum_definition, ref generics) => {
368 variants: self.arena.alloc_from_iter(
372 .map(|x| self.lower_variant(x))
375 self.lower_generics(generics, ImplTraitContext::disallowed()),
378 ItemKind::Struct(ref struct_def, ref generics) => {
379 let struct_def = self.lower_variant_data(struct_def);
380 hir::ItemKind::Struct(
382 self.lower_generics(generics, ImplTraitContext::disallowed()),
385 ItemKind::Union(ref vdata, ref generics) => {
386 let vdata = self.lower_variant_data(vdata);
387 hir::ItemKind::Union(
389 self.lower_generics(generics, ImplTraitContext::disallowed()),
401 let def_id = self.resolver.definitions().local_def_id(id);
403 // Lower the "impl header" first. This ordering is important
404 // for in-band lifetimes! Consider `'a` here:
406 // impl Foo<'a> for u32 {
407 // fn method(&'a self) { .. }
410 // Because we start by lowering the `Foo<'a> for u32`
411 // part, we will add `'a` to the list of generics on
412 // the impl. When we then encounter it later in the
413 // method, it will not be considered an in-band
414 // lifetime to be added, but rather a reference to a
416 let lowered_trait_impl_id = self.lower_node_id(id);
417 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
420 AnonymousLifetimeMode::CreateParameter,
422 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
423 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
426 if let Some(ref trait_ref) = trait_ref {
427 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
428 this.trait_impls.entry(def_id).or_default().push(
429 lowered_trait_impl_id);
433 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
435 (trait_ref, lowered_ty)
439 let new_impl_items = self.with_in_scope_lifetime_defs(
440 &ast_generics.params,
442 this.arena.alloc_from_iter(
445 .map(|item| this.lower_impl_item_ref(item))
453 self.lower_defaultness(defaultness, true /* [1] */),
456 self.arena.alloc(lowered_ty.into_inner()),
460 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
461 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
462 let items = self.arena.alloc_from_iter(items
464 .map(|item| self.lower_trait_item_ref(item))
466 hir::ItemKind::Trait(
469 self.lower_generics(generics, ImplTraitContext::disallowed()),
474 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
475 self.lower_generics(generics, ImplTraitContext::disallowed()),
476 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
478 ItemKind::MacroDef(..)
479 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
482 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
483 // not cause an assertion failure inside the `lower_defaultness` function.
491 vis: &mut hir::Visibility,
493 attrs: &'hir [Attribute],
494 ) -> hir::ItemKind<'hir> {
495 debug!("lower_use_tree(tree={:?})", tree);
496 debug!("lower_use_tree: vis = {:?}", vis);
498 let path = &tree.prefix;
499 let segments = prefix
502 .chain(path.segments.iter())
507 UseTreeKind::Simple(rename, id1, id2) => {
508 *ident = tree.ident();
510 // First, apply the prefix to the path.
511 let mut path = Path {
516 // Correctly resolve `self` imports.
517 if path.segments.len() > 1
518 && path.segments.last().unwrap().ident.name == kw::SelfLower
520 let _ = path.segments.pop();
521 if rename.is_none() {
522 *ident = path.segments.last().unwrap().ident;
526 let mut resolutions = self.expect_full_res_from_use(id);
527 // We want to return *something* from this function, so hold onto the first item
529 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
531 // Here, we are looping over namespaces, if they exist for the definition
532 // being imported. We only handle type and value namespaces because we
533 // won't be dealing with macros in the rest of the compiler.
534 // Essentially a single `use` which imports two names is desugared into
536 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
538 let mut path = path.clone();
539 for seg in &mut path.segments {
540 seg.id = self.resolver.next_node_id();
542 let span = path.span;
544 self.with_hir_id_owner(new_node_id, |this| {
545 let new_id = this.lower_node_id(new_node_id);
546 let res = this.lower_res(res);
548 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
549 let kind = hir::ItemKind::Use(this.arena.alloc(path), hir::UseKind::Single);
550 let vis = this.rebuild_vis(&vis);
565 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
566 let path = self.arena.alloc(path);
567 hir::ItemKind::Use(path, hir::UseKind::Single)
569 UseTreeKind::Glob => {
570 let path = self.arena.alloc(self.lower_path(
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
607 span: prefix.span.to(path.span),
610 // Add all the nested `PathListItem`s to the HIR.
611 for &(ref use_tree, id) in trees {
612 let new_hir_id = self.lower_node_id(id);
614 let mut prefix = prefix.clone();
616 // Give the segments new node-ids since they are being cloned.
617 for seg in &mut prefix.segments {
618 seg.id = self.resolver.next_node_id();
621 // Each `use` import is an item and thus are owners of the
622 // names in the path. Up to this point the nested import is
623 // the current owner, since we want each desugared import to
624 // own its own names, we have to adjust the owner before
625 // lowering the rest of the import.
626 self.with_hir_id_owner(id, |this| {
627 let mut vis = this.rebuild_vis(&vis);
628 let mut ident = *ident;
630 let kind = this.lower_use_tree(use_tree,
650 // Subtle and a bit hacky: we lower the privacy level
651 // of the list stem to "private" most of the time, but
652 // not for "restricted" paths. The key thing is that
653 // we don't want it to stay as `pub` (with no caveats)
654 // because that affects rustdoc and also the lints
655 // about `pub` items. But we can't *always* make it
656 // private -- particularly not for restricted paths --
657 // because it contains node-ids that would then be
658 // unused, failing the check that HirIds are "densely
661 hir::VisibilityKind::Public |
662 hir::VisibilityKind::Crate(_) |
663 hir::VisibilityKind::Inherited => {
664 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
666 hir::VisibilityKind::Restricted { .. } => {
667 // Do nothing here, as described in the comment on the match.
671 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
672 let res = self.lower_res(res);
673 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
674 let path = self.arena.alloc(path);
675 hir::ItemKind::Use(path, hir::UseKind::ListStem)
680 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
681 /// many times in the HIR tree; for each occurrence, we need to assign distinct
682 /// `NodeId`s. (See, e.g., #56128.)
683 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
684 debug!("rebuild_use_path(path = {:?})", path);
685 let segments = path.segments.iter().map(|seg| hir::PathSegment {
687 hir_id: seg.hir_id.map(|_| self.next_id()),
690 infer_args: seg.infer_args,
699 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
700 let vis_kind = match vis.node {
701 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
702 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
703 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
704 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
705 hir::VisibilityKind::Restricted {
706 path: P(self.rebuild_use_path(path)),
707 hir_id: self.next_id(),
711 respan(vis.span, vis_kind)
714 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
715 let def_id = self.resolver.definitions().local_def_id(i.id);
717 hir_id: self.lower_node_id(i.id),
719 attrs: self.lower_attrs_arena(&i.attrs),
721 ForeignItemKind::Fn(ref fdec, ref generics) => {
722 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
725 AnonymousLifetimeMode::PassThrough,
728 // Disallow `impl Trait` in foreign items.
729 this.lower_fn_decl(fdec, None, false, None),
730 this.lower_fn_params_to_names(fdec),
734 let fn_dec = self.arena.alloc(fn_dec.into_inner());
735 let fn_args = self.arena.alloc_from_iter(fn_args.into_iter());
737 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
739 ForeignItemKind::Static(ref t, m) => {
740 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
741 hir::ForeignItemKind::Static(self.arena.alloc(ty.into_inner()), m)
743 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
744 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
746 vis: self.lower_visibility(&i.vis, None),
751 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'hir> {
753 abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
754 items: self.arena.alloc_from_iter(fm.items
756 .map(|x| self.lower_foreign_item(x))),
760 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
761 self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
764 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
766 attrs: self.lower_attrs_arena(&v.attrs),
767 data: self.lower_variant_data(&v.data),
768 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
769 id: self.lower_node_id(v.id),
775 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> {
777 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
778 self.arena.alloc_from_iter(
779 fields.iter().enumerate().map(|f| self.lower_struct_field(f))
783 VariantData::Tuple(ref fields, id) => {
784 hir::VariantData::Tuple(
785 self.arena.alloc_from_iter(
789 .map(|f| self.lower_struct_field(f))
791 self.lower_node_id(id),
794 VariantData::Unit(id) => {
795 hir::VariantData::Unit(self.lower_node_id(id))
800 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'hir> {
801 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
802 let t = self.lower_path_ty(
806 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
807 ImplTraitContext::disallowed()
811 let t = self.lower_ty(&f.ty, ImplTraitContext::disallowed());
812 self.arena.alloc(t.into_inner())
816 hir_id: self.lower_node_id(f.id),
817 ident: match f.ident {
818 Some(ident) => ident,
819 // FIXME(jseyfried): positional field hygiene.
820 None => Ident::new(sym::integer(index), f.span),
822 vis: self.lower_visibility(&f.vis, None),
824 attrs: self.lower_attrs_arena(&f.attrs),
828 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
829 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
831 let (generics, kind) = match i.kind {
832 AssocItemKind::Const(ref ty, ref default) => {
833 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
834 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
835 let ty = self.arena.alloc(ty.into_inner());
836 (generics, hir::TraitItemKind::Const(
840 .map(|x| self.lower_const_body(i.span, Some(x))),
843 AssocItemKind::Fn(ref sig, None) => {
844 let names = self.lower_fn_params_to_names(&sig.decl);
845 let (generics, sig) = self.lower_method_sig(
852 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
854 AssocItemKind::Fn(ref sig, Some(ref body)) => {
855 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
856 let (generics, sig) = self.lower_method_sig(
863 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
865 AssocItemKind::TyAlias(ref bounds, ref default) => {
866 let ty = default.as_ref().map(|x| -> &'hir hir::Ty { self.arena.alloc(
867 self.lower_ty(x, ImplTraitContext::disallowed()).into_inner())
869 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
870 let kind = hir::TraitItemKind::Type(
871 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
877 AssocItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
881 hir_id: self.lower_node_id(i.id),
883 attrs: self.lower_attrs_arena(&i.attrs),
890 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
891 let (kind, has_default) = match i.kind {
892 AssocItemKind::Const(_, ref default) => {
893 (hir::AssocItemKind::Const, default.is_some())
895 AssocItemKind::TyAlias(_, ref default) => {
896 (hir::AssocItemKind::Type, default.is_some())
898 AssocItemKind::Fn(ref sig, ref default) => (
899 hir::AssocItemKind::Method {
900 has_self: sig.decl.has_self(),
904 AssocItemKind::Macro(..) => unimplemented!(),
907 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
910 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
915 /// Construct `ExprKind::Err` for the given `span`.
916 fn expr_err(&mut self, span: Span) -> hir::Expr {
917 self.expr(span, hir::ExprKind::Err, AttrVec::new())
920 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
921 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
923 let (generics, kind) = match i.kind {
924 AssocItemKind::Const(ref ty, ref expr) => {
925 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
926 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
927 let ty = self.arena.alloc(ty.into_inner());
928 (generics, hir::ImplItemKind::Const(
930 self.lower_const_body(i.span, expr.as_deref()),
933 AssocItemKind::Fn(ref sig, ref body) => {
934 self.current_item = Some(i.span);
935 let body_id = self.lower_maybe_async_body(
938 sig.header.asyncness.node,
941 let impl_trait_return_allow = !self.is_in_trait_impl;
942 let (generics, sig) = self.lower_method_sig(
946 impl_trait_return_allow,
947 sig.header.asyncness.node.opt_return_id(),
950 (generics, hir::ImplItemKind::Method(sig, body_id))
952 AssocItemKind::TyAlias(_, ref ty) => {
953 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
954 let kind = match ty {
956 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
957 hir::ImplItemKind::TyAlias(ty)
959 Some(ty) => match ty.kind.opaque_top_hack() {
961 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
962 let ty = self.arena.alloc(ty.into_inner());
963 hir::ImplItemKind::TyAlias(ty)
966 let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
967 hir::ImplItemKind::OpaqueTy(bs)
973 AssocItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
977 hir_id: self.lower_node_id(i.id),
979 attrs: self.lower_attrs_arena(&i.attrs),
981 vis: self.lower_visibility(&i.vis, None),
982 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
987 // [1] since `default impl` is not yet implemented, this is always true in impls
990 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
992 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
995 vis: self.lower_visibility(&i.vis, Some(i.id)),
996 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
997 kind: match &i.kind {
998 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
999 AssocItemKind::TyAlias(_, ty) => match ty
1001 .and_then(|ty| ty.kind.opaque_top_hack())
1003 None => hir::AssocItemKind::Type,
1004 Some(_) => hir::AssocItemKind::OpaqueTy,
1006 AssocItemKind::Fn(sig, _) => hir::AssocItemKind::Method {
1007 has_self: sig.decl.has_self(),
1009 AssocItemKind::Macro(..) => unimplemented!(),
1013 // [1] since `default impl` is not yet implemented, this is always true in impls
1016 /// If an `explicit_owner` is given, this method allocates the `HirId` in
1017 /// the address space of that item instead of the item currently being
1018 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
1019 /// lower a `Visibility` value although we haven't lowered the owning
1020 /// `ImplItem` in question yet.
1021 fn lower_visibility(
1024 explicit_owner: Option<NodeId>,
1025 ) -> hir::Visibility {
1026 let node = match v.node {
1027 VisibilityKind::Public => hir::VisibilityKind::Public,
1028 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
1029 VisibilityKind::Restricted { ref path, id } => {
1030 debug!("lower_visibility: restricted path id = {:?}", id);
1031 let lowered_id = if let Some(owner) = explicit_owner {
1032 self.lower_node_id_with_owner(id, owner)
1034 self.lower_node_id(id)
1036 let res = self.expect_full_res(id);
1037 let res = self.lower_res(res);
1038 hir::VisibilityKind::Restricted {
1039 path: P(self.lower_path_extra(
1042 ParamMode::Explicit,
1048 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
1050 respan(v.span, node)
1053 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
1055 Defaultness::Default => hir::Defaultness::Default {
1056 has_value: has_value,
1058 Defaultness::Final => {
1060 hir::Defaultness::Final
1065 fn record_body(&mut self, params: &'hir [hir::Param], value: hir::Expr) -> hir::BodyId {
1066 let body = hir::Body {
1067 generator_kind: self.generator_kind,
1072 self.bodies.insert(id, body);
1078 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param], hir::Expr),
1080 let prev_gen_kind = self.generator_kind.take();
1081 let (parameters, result) = f(self);
1082 let body_id = self.record_body(parameters, result);
1083 self.generator_kind = prev_gen_kind;
1087 fn lower_param(&mut self, param: &Param) -> hir::Param {
1089 attrs: self.lower_attrs(¶m.attrs),
1090 hir_id: self.lower_node_id(param.id),
1091 pat: self.lower_pat(¶m.pat),
1096 pub(super) fn lower_fn_body(
1099 body: impl FnOnce(&mut LoweringContext<'_, '_>) -> hir::Expr,
1101 self.lower_body(|this| (
1102 this.arena.alloc_from_iter(
1103 decl.inputs.iter().map(|x| this.lower_param(x))
1109 fn lower_fn_body_block(
1113 body: Option<&Block>,
1115 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1118 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr {
1120 Some(block) => self.lower_block_expr(block),
1121 None => self.expr_err(span),
1125 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1126 self.lower_body(|this| (&[], match expr {
1127 Some(expr) => this.lower_expr(expr),
1128 None => this.expr_err(span),
1132 fn lower_maybe_async_body(
1137 body: Option<&Block>,
1139 let closure_id = match asyncness {
1140 IsAsync::Async { closure_id, .. } => closure_id,
1141 IsAsync::NotAsync => return self.lower_fn_body_block(span, decl, body),
1144 self.lower_body(|this| {
1145 let mut parameters: Vec<hir::Param> = Vec::new();
1146 let mut statements: Vec<hir::Stmt> = Vec::new();
1148 // Async function parameters are lowered into the closure body so that they are
1149 // captured and so that the drop order matches the equivalent non-async functions.
1153 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1159 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1161 // let __arg2 = __arg2;
1162 // let <pattern> = __arg2;
1163 // let __arg1 = __arg1;
1164 // let <pattern> = __arg1;
1165 // let __arg0 = __arg0;
1166 // let <pattern> = __arg0;
1167 // drop-temps { <body> } // see comments later in fn for details
1171 // If `<pattern>` is a simple ident, then it is lowered to a single
1172 // `let <pattern> = <pattern>;` statement as an optimization.
1174 // Note that the body is embedded in `drop-temps`; an
1175 // equivalent desugaring would be `return { <body>
1176 // };`. The key point is that we wish to drop all the
1177 // let-bound variables and temporaries created in the body
1178 // (and its tail expression!) before we drop the
1179 // parameters (c.f. rust-lang/rust#64512).
1180 for (index, parameter) in decl.inputs.iter().enumerate() {
1181 let parameter = this.lower_param(parameter);
1182 let span = parameter.pat.span;
1184 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1185 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1186 let (ident, is_simple_parameter) = match parameter.pat.kind {
1187 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
1190 // Replace the ident for bindings that aren't simple.
1191 let name = format!("__arg{}", index);
1192 let ident = Ident::from_str(&name);
1198 let desugared_span =
1199 this.mark_span_with_reason(DesugaringKind::Async, span, None);
1201 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1204 // If this is the simple case, this parameter will end up being the same as the
1205 // original parameter, but with a different pattern id.
1206 let mut stmt_attrs = AttrVec::new();
1207 stmt_attrs.extend(parameter.attrs.iter().cloned());
1208 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1209 let new_parameter = hir::Param {
1210 attrs: parameter.attrs,
1211 hir_id: parameter.hir_id,
1212 pat: new_parameter_pat,
1213 span: parameter.span,
1217 if is_simple_parameter {
1218 // If this is the simple case, then we only insert one statement that is
1219 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1220 // `HirId`s are densely assigned.
1221 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1222 let stmt = this.stmt_let_pat(
1227 hir::LocalSource::AsyncFn
1229 statements.push(stmt);
1231 // If this is not the simple case, then we construct two statements:
1234 // let __argN = __argN;
1235 // let <pat> = __argN;
1238 // The first statement moves the parameter into the closure and thus ensures
1239 // that the drop order is correct.
1241 // The second statement creates the bindings that the user wrote.
1243 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1244 // because the user may have specified a `ref mut` binding in the next
1246 let (move_pat, move_id) = this.pat_ident_binding_mode(
1247 desugared_span, ident, hir::BindingAnnotation::Mutable);
1248 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1249 let move_stmt = this.stmt_let_pat(
1254 hir::LocalSource::AsyncFn
1257 // Construct the `let <pat> = __argN;` statement. We re-use the original
1258 // parameter's pattern so that `HirId`s are densely assigned.
1259 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1260 let pattern_stmt = this.stmt_let_pat(
1263 Some(P(pattern_expr)),
1265 hir::LocalSource::AsyncFn
1268 statements.push(move_stmt);
1269 statements.push(pattern_stmt);
1272 parameters.push(new_parameter);
1275 let body_span = body.map_or(span, |b| b.span);
1276 let async_expr = this.make_async_expr(
1281 hir::AsyncGeneratorKind::Fn,
1283 // Create a block from the user's function body:
1284 let user_body = this.lower_block_expr_opt(body_span, body);
1286 // Transform into `drop-temps { <user-body> }`, an expression:
1287 let desugared_span = this.mark_span_with_reason(
1288 DesugaringKind::Async,
1292 let user_body = this.expr_drop_temps(
1298 // As noted above, create the final block like
1302 // let $param_pattern = $raw_param;
1304 // drop-temps { <user-body> }
1307 let body = this.block_all(
1312 this.expr_block(P(body), AttrVec::new())
1316 this.arena.alloc_from_iter(parameters),
1317 this.expr(body_span, async_expr, AttrVec::new()),
1322 fn lower_method_sig(
1324 generics: &Generics,
1327 impl_trait_return_allow: bool,
1328 is_async: Option<NodeId>,
1329 ) -> (hir::Generics, hir::FnSig) {
1330 let header = self.lower_fn_header(sig.header);
1331 let (generics, decl) = self.add_in_band_defs(
1334 AnonymousLifetimeMode::PassThrough,
1335 |this, idty| this.lower_fn_decl(
1337 Some((fn_def_id, idty)),
1338 impl_trait_return_allow,
1342 (generics, hir::FnSig { header, decl })
1345 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1347 unsafety: h.unsafety,
1348 asyncness: self.lower_asyncness(h.asyncness.node),
1349 constness: h.constness.node,
1350 abi: self.lower_extern(h.ext),
1354 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1355 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1356 self.error_on_invalid_abi(abi);
1361 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1363 Extern::None => abi::Abi::Rust,
1364 Extern::Implicit => abi::Abi::C,
1365 Extern::Explicit(abi) => self.lower_abi(abi),
1369 fn error_on_invalid_abi(&self, abi: StrLit) {
1374 "invalid ABI: found `{}`",
1377 .span_label(abi.span, "invalid ABI")
1378 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1382 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1384 IsAsync::Async { .. } => hir::IsAsync::Async,
1385 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1389 pub(super) fn lower_generics(
1391 generics: &Generics,
1392 itctx: ImplTraitContext<'_>)
1395 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1396 // FIXME: this could probably be done with less rightward drift. It also looks like two
1397 // control paths where `report_error` is called are the only paths that advance to after the
1398 // match statement, so the error reporting could probably just be moved there.
1399 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1400 for pred in &generics.where_clause.predicates {
1401 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1402 'next_bound: for bound in &bound_pred.bounds {
1403 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1404 let report_error = |this: &mut Self| {
1405 this.diagnostic().span_err(
1406 bound_pred.bounded_ty.span,
1407 "`?Trait` bounds are only permitted at the \
1408 point where a type parameter is declared",
1411 // Check if the where clause type is a plain type parameter.
1412 match bound_pred.bounded_ty.kind {
1413 TyKind::Path(None, ref path)
1414 if path.segments.len() == 1
1415 && bound_pred.bound_generic_params.is_empty() =>
1417 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
1418 .get_partial_res(bound_pred.bounded_ty.id)
1419 .map(|d| d.base_res())
1421 if let Some(node_id) =
1422 self.resolver.definitions().as_local_node_id(def_id)
1424 for param in &generics.params {
1426 GenericParamKind::Type { .. } => {
1427 if node_id == param.id {
1428 add_bounds.entry(param.id)
1430 .push(bound.clone());
1431 continue 'next_bound;
1441 _ => report_error(self),
1449 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
1450 where_clause: self.lower_where_clause(&generics.where_clause),
1451 span: generics.span,
1455 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1456 self.with_anonymous_lifetime_mode(
1457 AnonymousLifetimeMode::ReportError,
1460 predicates: wc.predicates
1462 .map(|predicate| this.lower_where_predicate(predicate))
1470 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1472 WherePredicate::BoundPredicate(WhereBoundPredicate {
1473 ref bound_generic_params,
1478 self.with_in_scope_lifetime_defs(
1479 &bound_generic_params,
1481 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1482 bound_generic_params: this.lower_generic_params(
1483 bound_generic_params,
1484 &NodeMap::default(),
1485 ImplTraitContext::disallowed(),
1487 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1490 .filter_map(|bound| match *bound {
1491 // Ignore `?Trait` bounds.
1492 // They were copied into type parameters already.
1493 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1494 _ => Some(this.lower_param_bound(
1496 ImplTraitContext::disallowed(),
1505 WherePredicate::RegionPredicate(WhereRegionPredicate {
1509 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1511 lifetime: self.lower_lifetime(lifetime),
1512 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1514 WherePredicate::EqPredicate(WhereEqPredicate {
1520 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1521 hir_id: self.lower_node_id(id),
1522 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1523 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),