1 use super::LoweringContext;
2 use super::ImplTraitContext;
3 use super::ImplTraitPosition;
4 use super::ImplTraitTypeIdVisitor;
5 use super::AnonymousLifetimeMode;
8 use crate::hir::{self, HirVec};
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_data_structures::thin_vec::ThinVec;
16 use std::collections::BTreeSet;
17 use smallvec::SmallVec;
20 use syntax::visit::{self, Visitor};
21 use syntax::ext::base::SpecialDerives;
22 use syntax::source_map::{respan, DesugaringKind, Spanned};
23 use syntax::symbol::{kw, sym};
26 pub(super) struct ItemLowerer<'tcx, 'interner> {
27 pub(super) lctx: &'tcx mut LoweringContext<'interner>,
30 impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> {
31 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
35 let old = self.lctx.is_in_trait_impl;
36 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
42 self.lctx.is_in_trait_impl = old;
46 impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> {
47 fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
48 self.lctx.modules.insert(n, hir::ModuleItems {
49 items: BTreeSet::new(),
50 trait_items: BTreeSet::new(),
51 impl_items: BTreeSet::new(),
54 let old = self.lctx.current_module;
55 self.lctx.current_module = n;
56 visit::walk_mod(self, m);
57 self.lctx.current_module = old;
60 fn visit_item(&mut self, item: &'tcx Item) {
61 let mut item_hir_id = None;
62 self.lctx.with_hir_id_owner(item.id, |lctx| {
63 lctx.without_in_scope_lifetime_defs(|lctx| {
64 if let Some(hir_item) = lctx.lower_item(item) {
65 item_hir_id = Some(hir_item.hir_id);
66 lctx.insert_item(hir_item);
71 if let Some(hir_id) = item_hir_id {
72 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
73 let this = &mut ItemLowerer { lctx: this };
74 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
75 this.with_trait_impl_ref(opt_trait_ref, |this| {
76 visit::walk_item(this, item)
79 visit::walk_item(this, item);
85 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
86 self.lctx.with_hir_id_owner(item.id, |lctx| {
87 let hir_item = lctx.lower_trait_item(item);
88 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
89 lctx.trait_items.insert(id, hir_item);
90 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
93 visit::walk_trait_item(self, item);
96 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
97 self.lctx.with_hir_id_owner(item.id, |lctx| {
98 let hir_item = lctx.lower_impl_item(item);
99 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
100 lctx.impl_items.insert(id, hir_item);
101 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
103 visit::walk_impl_item(self, item);
107 impl LoweringContext<'_> {
108 // Same as the method above, but accepts `hir::GenericParam`s
109 // instead of `ast::GenericParam`s.
110 // This should only be used with generics that have already had their
111 // in-band lifetimes added. In practice, this means that this function is
112 // only used when lowering a child item of a trait or impl.
113 fn with_parent_item_lifetime_defs<T>(
115 parent_hir_id: hir::HirId,
116 f: impl FnOnce(&mut LoweringContext<'_>) -> T,
118 let old_len = self.in_scope_lifetimes.len();
120 let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
121 hir::ItemKind::Impl(_, _, _, ref generics, ..)
122 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
127 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
128 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
131 self.in_scope_lifetimes.extend(lt_def_names);
135 self.in_scope_lifetimes.truncate(old_len);
139 // Clears (and restores) the `in_scope_lifetimes` field. Used when
140 // visiting nested items, which never inherit in-scope lifetimes
141 // from their surrounding environment.
142 fn without_in_scope_lifetime_defs<T>(
144 f: impl FnOnce(&mut LoweringContext<'_>) -> T,
146 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
148 // this vector is only used when walking over impl headers,
149 // input types, and the like, and should not be non-empty in
151 assert!(self.lifetimes_to_define.is_empty());
155 assert!(self.in_scope_lifetimes.is_empty());
156 self.in_scope_lifetimes = old_in_scope_lifetimes;
161 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
164 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
168 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
169 let node_ids = match i.node {
170 ItemKind::Use(ref use_tree) => {
171 let mut vec = smallvec![i.id];
172 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
175 ItemKind::MacroDef(..) => SmallVec::new(),
177 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
178 ItemKind::Static(ref ty, ..) => {
179 let mut ids = smallvec![i.id];
180 if self.sess.features_untracked().impl_trait_in_bindings {
181 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
182 visitor.visit_ty(ty);
186 ItemKind::Const(ref ty, ..) => {
187 let mut ids = smallvec![i.id];
188 if self.sess.features_untracked().impl_trait_in_bindings {
189 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
190 visitor.visit_ty(ty);
194 _ => smallvec![i.id],
197 node_ids.into_iter().map(|node_id| hir::ItemId {
198 id: self.allocate_hir_id_counter(node_id)
202 fn lower_item_id_use_tree(
206 vec: &mut SmallVec<[NodeId; 1]>
209 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
211 self.lower_item_id_use_tree(nested, id, vec);
213 UseTreeKind::Glob => {}
214 UseTreeKind::Simple(_, id1, id2) => {
215 for (_, &id) in self.expect_full_res_from_use(base_id)
217 .zip([id1, id2].iter())
225 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
226 let mut ident = i.ident;
227 let mut vis = self.lower_visibility(&i.vis, None);
228 let mut attrs = self.lower_attrs_extendable(&i.attrs);
229 if self.resolver.has_derives(i.id, SpecialDerives::PARTIAL_EQ | SpecialDerives::EQ) {
230 // Add `#[structural_match]` if the item derived both `PartialEq` and `Eq`.
231 let ident = Ident::new(sym::structural_match, i.span);
232 attrs.push(attr::mk_attr_outer(attr::mk_word_item(ident)));
234 let attrs = attrs.into();
236 if let ItemKind::MacroDef(ref def) = i.node {
237 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
238 let body = self.lower_token_stream(def.stream());
239 let hir_id = self.lower_node_id(i.id);
240 self.exported_macros.push(hir::MacroDef {
250 self.non_exported_macro_attrs.extend(attrs.into_iter());
255 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
258 hir_id: self.lower_node_id(i.id),
271 attrs: &hir::HirVec<Attribute>,
272 vis: &mut hir::Visibility,
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 hir::ItemKind::Static(
290 if self.sess.features_untracked().impl_trait_in_bindings {
291 ImplTraitContext::OpaqueTy(None)
293 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
296 self.lower_mutability(m),
297 self.lower_const_body(e),
300 ItemKind::Const(ref t, ref e) => {
301 hir::ItemKind::Const(
304 if self.sess.features_untracked().impl_trait_in_bindings {
305 ImplTraitContext::OpaqueTy(None)
307 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
310 self.lower_const_body(e)
313 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
314 let fn_def_id = self.resolver.definitions().local_def_id(id);
315 self.with_new_scopes(|this| {
316 this.current_item = Some(ident.span);
318 // Note: we don't need to change the return type from `T` to
319 // `impl Future<Output = T>` here because lower_body
320 // only cares about the input argument patterns in the function
321 // declaration (decl), not the return types.
322 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
324 let (generics, fn_decl) = this.add_in_band_defs(
327 AnonymousLifetimeMode::PassThrough,
328 |this, idty| this.lower_fn_decl(
330 Some((fn_def_id, idty)),
332 header.asyncness.node.opt_return_id()
338 this.lower_fn_header(header),
344 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
345 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
346 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
347 ItemKind::TyAlias(ref t, ref generics) => hir::ItemKind::TyAlias(
348 self.lower_ty(t, ImplTraitContext::disallowed()),
349 self.lower_generics(generics, ImplTraitContext::disallowed()),
351 ItemKind::OpaqueTy(ref b, ref generics) => hir::ItemKind::OpaqueTy(
353 generics: self.lower_generics(generics,
354 ImplTraitContext::OpaqueTy(None)),
355 bounds: self.lower_param_bounds(b,
356 ImplTraitContext::OpaqueTy(None)),
358 origin: hir::OpaqueTyOrigin::TypeAlias,
361 ItemKind::Enum(ref enum_definition, ref generics) => {
364 variants: enum_definition
367 .map(|x| self.lower_variant(x))
370 self.lower_generics(generics, ImplTraitContext::disallowed()),
373 ItemKind::Struct(ref struct_def, ref generics) => {
374 let struct_def = self.lower_variant_data(struct_def);
375 hir::ItemKind::Struct(
377 self.lower_generics(generics, ImplTraitContext::disallowed()),
380 ItemKind::Union(ref vdata, ref generics) => {
381 let vdata = self.lower_variant_data(vdata);
382 hir::ItemKind::Union(
384 self.lower_generics(generics, ImplTraitContext::disallowed()),
396 let def_id = self.resolver.definitions().local_def_id(id);
398 // Lower the "impl header" first. This ordering is important
399 // for in-band lifetimes! Consider `'a` here:
401 // impl Foo<'a> for u32 {
402 // fn method(&'a self) { .. }
405 // Because we start by lowering the `Foo<'a> for u32`
406 // part, we will add `'a` to the list of generics on
407 // the impl. When we then encounter it later in the
408 // method, it will not be considered an in-band
409 // lifetime to be added, but rather a reference to a
411 let lowered_trait_impl_id = self.lower_node_id(id);
412 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
415 AnonymousLifetimeMode::CreateParameter,
417 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
418 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
421 if let Some(ref trait_ref) = trait_ref {
422 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
423 this.trait_impls.entry(def_id).or_default().push(
424 lowered_trait_impl_id);
428 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
430 (trait_ref, lowered_ty)
434 let new_impl_items = self.with_in_scope_lifetime_defs(
435 &ast_generics.params,
439 .map(|item| this.lower_impl_item_ref(item))
445 self.lower_unsafety(unsafety),
446 self.lower_impl_polarity(polarity),
447 self.lower_defaultness(defaultness, true /* [1] */),
454 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
455 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
458 .map(|item| self.lower_trait_item_ref(item))
460 hir::ItemKind::Trait(
461 self.lower_is_auto(is_auto),
462 self.lower_unsafety(unsafety),
463 self.lower_generics(generics, ImplTraitContext::disallowed()),
468 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
469 self.lower_generics(generics, ImplTraitContext::disallowed()),
470 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
472 ItemKind::MacroDef(..)
473 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
476 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
477 // not cause an assertion failure inside the `lower_defaultness` function.
485 vis: &mut hir::Visibility,
487 attrs: &hir::HirVec<Attribute>,
489 debug!("lower_use_tree(tree={:?})", tree);
490 debug!("lower_use_tree: vis = {:?}", vis);
492 let path = &tree.prefix;
493 let segments = prefix
496 .chain(path.segments.iter())
501 UseTreeKind::Simple(rename, id1, id2) => {
502 *ident = tree.ident();
504 // First, apply the prefix to the path.
505 let mut path = Path {
510 // Correctly resolve `self` imports.
511 if path.segments.len() > 1
512 && path.segments.last().unwrap().ident.name == kw::SelfLower
514 let _ = path.segments.pop();
515 if rename.is_none() {
516 *ident = path.segments.last().unwrap().ident;
520 let mut resolutions = self.expect_full_res_from_use(id);
521 // We want to return *something* from this function, so hold onto the first item
523 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
525 // Here, we are looping over namespaces, if they exist for the definition
526 // being imported. We only handle type and value namespaces because we
527 // won't be dealing with macros in the rest of the compiler.
528 // Essentially a single `use` which imports two names is desugared into
530 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
532 let mut path = path.clone();
533 for seg in &mut path.segments {
534 seg.id = self.sess.next_node_id();
536 let span = path.span;
538 self.with_hir_id_owner(new_node_id, |this| {
539 let new_id = this.lower_node_id(new_node_id);
540 let res = this.lower_res(res);
542 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
543 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
544 let vis = this.rebuild_vis(&vis);
550 attrs: attrs.into_iter().cloned().collect(),
560 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
561 hir::ItemKind::Use(path, hir::UseKind::Single)
563 UseTreeKind::Glob => {
564 let path = P(self.lower_path(
572 hir::ItemKind::Use(path, hir::UseKind::Glob)
574 UseTreeKind::Nested(ref trees) => {
575 // Nested imports are desugared into simple imports.
576 // So, if we start with
579 // pub(x) use foo::{a, b};
582 // we will create three items:
585 // pub(x) use foo::a;
586 // pub(x) use foo::b;
587 // pub(x) use foo::{}; // <-- this is called the `ListStem`
590 // The first two are produced by recursively invoking
591 // `lower_use_tree` (and indeed there may be things
592 // like `use foo::{a::{b, c}}` and so forth). They
593 // wind up being directly added to
594 // `self.items`. However, the structure of this
595 // function also requires us to return one item, and
596 // for that we return the `{}` import (called the
601 span: prefix.span.to(path.span),
604 // Add all the nested `PathListItem`s to the HIR.
605 for &(ref use_tree, id) in trees {
606 let new_hir_id = self.lower_node_id(id);
608 let mut prefix = prefix.clone();
610 // Give the segments new node-ids since they are being cloned.
611 for seg in &mut prefix.segments {
612 seg.id = self.sess.next_node_id();
615 // Each `use` import is an item and thus are owners of the
616 // names in the path. Up to this point the nested import is
617 // the current owner, since we want each desugared import to
618 // own its own names, we have to adjust the owner before
619 // lowering the rest of the import.
620 self.with_hir_id_owner(id, |this| {
621 let mut vis = this.rebuild_vis(&vis);
622 let mut ident = *ident;
624 let item = this.lower_use_tree(use_tree,
635 attrs: attrs.into_iter().cloned().collect(),
644 // Subtle and a bit hacky: we lower the privacy level
645 // of the list stem to "private" most of the time, but
646 // not for "restricted" paths. The key thing is that
647 // we don't want it to stay as `pub` (with no caveats)
648 // because that affects rustdoc and also the lints
649 // about `pub` items. But we can't *always* make it
650 // private -- particularly not for restricted paths --
651 // because it contains node-ids that would then be
652 // unused, failing the check that HirIds are "densely
655 hir::VisibilityKind::Public |
656 hir::VisibilityKind::Crate(_) |
657 hir::VisibilityKind::Inherited => {
658 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
660 hir::VisibilityKind::Restricted { .. } => {
661 // Do nothing here, as described in the comment on the match.
665 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
666 let res = self.lower_res(res);
667 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
668 hir::ItemKind::Use(path, hir::UseKind::ListStem)
673 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
674 /// many times in the HIR tree; for each occurrence, we need to assign distinct
675 /// `NodeId`s. (See, e.g., #56128.)
676 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
677 debug!("rebuild_use_path(path = {:?})", path);
678 let segments = path.segments.iter().map(|seg| hir::PathSegment {
680 hir_id: seg.hir_id.map(|_| self.next_id()),
683 infer_args: seg.infer_args,
692 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
693 let vis_kind = match vis.node {
694 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
695 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
696 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
697 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
698 hir::VisibilityKind::Restricted {
699 path: P(self.rebuild_use_path(path)),
700 hir_id: self.next_id(),
704 respan(vis.span, vis_kind)
707 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
708 let def_id = self.resolver.definitions().local_def_id(i.id);
710 hir_id: self.lower_node_id(i.id),
712 attrs: self.lower_attrs(&i.attrs),
714 ForeignItemKind::Fn(ref fdec, ref generics) => {
715 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
718 AnonymousLifetimeMode::PassThrough,
721 // Disallow `impl Trait` in foreign items.
722 this.lower_fn_decl(fdec, None, false, None),
723 this.lower_fn_params_to_names(fdec),
728 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
730 ForeignItemKind::Static(ref t, m) => {
731 hir::ForeignItemKind::Static(
732 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
734 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
735 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
737 vis: self.lower_visibility(&i.vis, None),
742 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
747 .map(|x| self.lower_foreign_item(x))
752 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
753 P(hir::GlobalAsm { asm: ga.asm })
756 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
758 attrs: self.lower_attrs(&v.attrs),
759 data: self.lower_variant_data(&v.data),
760 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
761 id: self.lower_node_id(v.id),
767 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
769 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
770 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
773 VariantData::Tuple(ref fields, id) => {
774 hir::VariantData::Tuple(
778 .map(|f| self.lower_struct_field(f))
780 self.lower_node_id(id),
783 VariantData::Unit(id) => {
784 hir::VariantData::Unit(self.lower_node_id(id))
789 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
790 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node {
791 let t = self.lower_path_ty(
795 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
796 ImplTraitContext::disallowed()
800 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
804 hir_id: self.lower_node_id(f.id),
805 ident: match f.ident {
806 Some(ident) => ident,
807 // FIXME(jseyfried): positional field hygiene.
808 None => Ident::new(sym::integer(index), f.span),
810 vis: self.lower_visibility(&f.vis, None),
812 attrs: self.lower_attrs(&f.attrs),
816 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
817 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
819 let (generics, node) = match i.node {
820 TraitItemKind::Const(ref ty, ref default) => (
821 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
822 hir::TraitItemKind::Const(
823 self.lower_ty(ty, ImplTraitContext::disallowed()),
826 .map(|x| self.lower_const_body(x)),
829 TraitItemKind::Method(ref sig, None) => {
830 let names = self.lower_fn_params_to_names(&sig.decl);
831 let (generics, sig) = self.lower_method_sig(
838 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
840 TraitItemKind::Method(ref sig, Some(ref body)) => {
841 let body_id = self.lower_fn_body_block(&sig.decl, body);
842 let (generics, sig) = self.lower_method_sig(
849 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
851 TraitItemKind::Type(ref bounds, ref default) => {
852 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
853 let node = hir::TraitItemKind::Type(
854 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
857 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
862 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
866 hir_id: self.lower_node_id(i.id),
868 attrs: self.lower_attrs(&i.attrs),
875 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
876 let (kind, has_default) = match i.node {
877 TraitItemKind::Const(_, ref default) => {
878 (hir::AssocItemKind::Const, default.is_some())
880 TraitItemKind::Type(_, ref default) => {
881 (hir::AssocItemKind::Type, default.is_some())
883 TraitItemKind::Method(ref sig, ref default) => (
884 hir::AssocItemKind::Method {
885 has_self: sig.decl.has_self(),
889 TraitItemKind::Macro(..) => unimplemented!(),
892 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
895 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
900 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
901 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
903 let (generics, node) = match i.node {
904 ImplItemKind::Const(ref ty, ref expr) => (
905 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
906 hir::ImplItemKind::Const(
907 self.lower_ty(ty, ImplTraitContext::disallowed()),
908 self.lower_const_body(expr),
911 ImplItemKind::Method(ref sig, ref body) => {
912 self.current_item = Some(i.span);
913 let body_id = self.lower_maybe_async_body(
914 &sig.decl, sig.header.asyncness.node, body
916 let impl_trait_return_allow = !self.is_in_trait_impl;
917 let (generics, sig) = self.lower_method_sig(
921 impl_trait_return_allow,
922 sig.header.asyncness.node.opt_return_id(),
925 (generics, hir::ImplItemKind::Method(sig, body_id))
927 ImplItemKind::TyAlias(ref ty) => (
928 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
929 hir::ImplItemKind::TyAlias(self.lower_ty(ty, ImplTraitContext::disallowed())),
931 ImplItemKind::OpaqueTy(ref bounds) => (
932 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
933 hir::ImplItemKind::OpaqueTy(
934 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
937 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
941 hir_id: self.lower_node_id(i.id),
943 attrs: self.lower_attrs(&i.attrs),
945 vis: self.lower_visibility(&i.vis, None),
946 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
951 // [1] since `default impl` is not yet implemented, this is always true in impls
954 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
956 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
959 vis: self.lower_visibility(&i.vis, Some(i.id)),
960 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
962 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
963 ImplItemKind::TyAlias(..) => hir::AssocItemKind::Type,
964 ImplItemKind::OpaqueTy(..) => hir::AssocItemKind::OpaqueTy,
965 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
966 has_self: sig.decl.has_self(),
968 ImplItemKind::Macro(..) => unimplemented!(),
972 // [1] since `default impl` is not yet implemented, this is always true in impls
975 /// If an `explicit_owner` is given, this method allocates the `HirId` in
976 /// the address space of that item instead of the item currently being
977 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
978 /// lower a `Visibility` value although we haven't lowered the owning
979 /// `ImplItem` in question yet.
983 explicit_owner: Option<NodeId>,
984 ) -> hir::Visibility {
985 let node = match v.node {
986 VisibilityKind::Public => hir::VisibilityKind::Public,
987 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
988 VisibilityKind::Restricted { ref path, id } => {
989 debug!("lower_visibility: restricted path id = {:?}", id);
990 let lowered_id = if let Some(owner) = explicit_owner {
991 self.lower_node_id_with_owner(id, owner)
993 self.lower_node_id(id)
995 let res = self.expect_full_res(id);
996 let res = self.lower_res(res);
997 hir::VisibilityKind::Restricted {
998 path: P(self.lower_path_extra(
1001 ParamMode::Explicit,
1007 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
1009 respan(v.span, node)
1012 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
1014 Defaultness::Default => hir::Defaultness::Default {
1015 has_value: has_value,
1017 Defaultness::Final => {
1019 hir::Defaultness::Final
1024 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
1026 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1027 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1031 fn record_body(&mut self, params: HirVec<hir::Param>, value: hir::Expr) -> hir::BodyId {
1032 let body = hir::Body {
1033 generator_kind: self.generator_kind,
1038 self.bodies.insert(id, body);
1044 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Param>, hir::Expr),
1046 let prev_gen_kind = self.generator_kind.take();
1047 let (parameters, result) = f(self);
1048 let body_id = self.record_body(parameters, result);
1049 self.generator_kind = prev_gen_kind;
1053 fn lower_param(&mut self, param: &Param) -> hir::Param {
1055 attrs: self.lower_attrs(¶m.attrs),
1056 hir_id: self.lower_node_id(param.id),
1057 pat: self.lower_pat(¶m.pat),
1062 pub(super) fn lower_fn_body(
1065 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1067 self.lower_body(|this| (
1068 decl.inputs.iter().map(|x| this.lower_param(x)).collect(),
1073 fn lower_fn_body_block(&mut self, decl: &FnDecl, body: &Block) -> hir::BodyId {
1074 self.lower_fn_body(decl, |this| {
1075 let body = this.lower_block(body, false);
1076 this.expr_block(body, ThinVec::new())
1080 pub(super) fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1081 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1084 fn lower_maybe_async_body(
1090 let closure_id = match asyncness {
1091 IsAsync::Async { closure_id, .. } => closure_id,
1092 IsAsync::NotAsync => return self.lower_fn_body_block(decl, body),
1095 self.lower_body(|this| {
1096 let mut parameters: Vec<hir::Param> = Vec::new();
1097 let mut statements: Vec<hir::Stmt> = Vec::new();
1099 // Async function parameters are lowered into the closure body so that they are
1100 // captured and so that the drop order matches the equivalent non-async functions.
1104 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1111 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1113 // let __arg2 = __arg2;
1114 // let <pattern> = __arg2;
1115 // let __arg1 = __arg1;
1116 // let <pattern> = __arg1;
1117 // let __arg0 = __arg0;
1118 // let <pattern> = __arg0;
1122 // If `<pattern>` is a simple ident, then it is lowered to a single
1123 // `let <pattern> = <pattern>;` statement as an optimization.
1124 for (index, parameter) in decl.inputs.iter().enumerate() {
1125 let parameter = this.lower_param(parameter);
1126 let span = parameter.pat.span;
1128 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1129 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1130 let (ident, is_simple_parameter) = match parameter.pat.node {
1131 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
1134 // Replace the ident for bindings that aren't simple.
1135 let name = format!("__arg{}", index);
1136 let ident = Ident::from_str(&name);
1142 let desugared_span =
1143 this.mark_span_with_reason(DesugaringKind::Async, span, None);
1145 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1148 // If this is the simple case, this parameter will end up being the same as the
1149 // original parameter, but with a different pattern id.
1150 let mut stmt_attrs = ThinVec::new();
1151 stmt_attrs.extend(parameter.attrs.iter().cloned());
1152 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1153 let new_parameter = hir::Param {
1154 attrs: parameter.attrs,
1155 hir_id: parameter.hir_id,
1156 pat: new_parameter_pat,
1157 span: parameter.span,
1161 if is_simple_parameter {
1162 // If this is the simple case, then we only insert one statement that is
1163 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1164 // `HirId`s are densely assigned.
1165 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1166 let stmt = this.stmt_let_pat(
1171 hir::LocalSource::AsyncFn
1173 statements.push(stmt);
1175 // If this is not the simple case, then we construct two statements:
1178 // let __argN = __argN;
1179 // let <pat> = __argN;
1182 // The first statement moves the parameter into the closure and thus ensures
1183 // that the drop order is correct.
1185 // The second statement creates the bindings that the user wrote.
1187 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1188 // because the user may have specified a `ref mut` binding in the next
1190 let (move_pat, move_id) = this.pat_ident_binding_mode(
1191 desugared_span, ident, hir::BindingAnnotation::Mutable);
1192 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1193 let move_stmt = this.stmt_let_pat(
1198 hir::LocalSource::AsyncFn
1201 // Construct the `let <pat> = __argN;` statement. We re-use the original
1202 // parameter's pattern so that `HirId`s are densely assigned.
1203 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1204 let pattern_stmt = this.stmt_let_pat(
1207 Some(P(pattern_expr)),
1209 hir::LocalSource::AsyncFn
1212 statements.push(move_stmt);
1213 statements.push(pattern_stmt);
1216 parameters.push(new_parameter);
1219 let async_expr = this.make_async_expr(
1220 CaptureBy::Value, closure_id, None, body.span,
1222 // Create a block from the user's function body:
1223 let user_body = this.lower_block(body, false);
1224 let user_body = this.expr_block(user_body, ThinVec::new());
1226 // Transform into `drop-temps { <user-body> }`, an expression:
1227 let desugared_span = this.mark_span_with_reason(
1228 DesugaringKind::Async,
1232 let user_body = this.expr_drop_temps(
1238 // Create a block like
1242 // let $param_pattern = $raw_param;
1244 // drop-temps { <user-body> }
1248 // This construction is carefully calibrated to
1249 // get the drop-order correct. In particular, the
1250 // drop-temps ensures that any temporaries in the
1251 // tail expression of `<user-body>` are dropped
1252 // *before* the parameters are dropped (see
1253 // rust-lang/rust#64512).
1254 let body = this.block_all(
1259 this.expr_block(P(body), ThinVec::new())
1261 (HirVec::from(parameters), this.expr(body.span, async_expr, ThinVec::new()))
1265 fn lower_method_sig(
1267 generics: &Generics,
1270 impl_trait_return_allow: bool,
1271 is_async: Option<NodeId>,
1272 ) -> (hir::Generics, hir::MethodSig) {
1273 let header = self.lower_fn_header(sig.header);
1274 let (generics, decl) = self.add_in_band_defs(
1277 AnonymousLifetimeMode::PassThrough,
1278 |this, idty| this.lower_fn_decl(
1280 Some((fn_def_id, idty)),
1281 impl_trait_return_allow,
1285 (generics, hir::MethodSig { header, decl })
1288 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
1290 IsAuto::Yes => hir::IsAuto::Yes,
1291 IsAuto::No => hir::IsAuto::No,
1295 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1297 unsafety: self.lower_unsafety(h.unsafety),
1298 asyncness: self.lower_asyncness(h.asyncness.node),
1299 constness: self.lower_constness(h.constness),
1304 pub(super) fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1306 Unsafety::Unsafe => hir::Unsafety::Unsafe,
1307 Unsafety::Normal => hir::Unsafety::Normal,
1311 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1313 Constness::Const => hir::Constness::Const,
1314 Constness::NotConst => hir::Constness::NotConst,
1318 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1320 IsAsync::Async { .. } => hir::IsAsync::Async,
1321 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1325 pub(super) fn lower_generics(
1327 generics: &Generics,
1328 itctx: ImplTraitContext<'_>)
1331 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1332 // FIXME: this could probably be done with less rightward drift. It also looks like two
1333 // control paths where `report_error` is called are the only paths that advance to after the
1334 // match statement, so the error reporting could probably just be moved there.
1335 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1336 for pred in &generics.where_clause.predicates {
1337 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1338 'next_bound: for bound in &bound_pred.bounds {
1339 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1340 let report_error = |this: &mut Self| {
1341 this.diagnostic().span_err(
1342 bound_pred.bounded_ty.span,
1343 "`?Trait` bounds are only permitted at the \
1344 point where a type parameter is declared",
1347 // Check if the where clause type is a plain type parameter.
1348 match bound_pred.bounded_ty.node {
1349 TyKind::Path(None, ref path)
1350 if path.segments.len() == 1
1351 && bound_pred.bound_generic_params.is_empty() =>
1353 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
1354 .get_partial_res(bound_pred.bounded_ty.id)
1355 .map(|d| d.base_res())
1357 if let Some(node_id) =
1358 self.resolver.definitions().as_local_node_id(def_id)
1360 for param in &generics.params {
1362 GenericParamKind::Type { .. } => {
1363 if node_id == param.id {
1364 add_bounds.entry(param.id)
1366 .push(bound.clone());
1367 continue 'next_bound;
1377 _ => report_error(self),
1385 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
1386 where_clause: self.lower_where_clause(&generics.where_clause),
1387 span: generics.span,
1391 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1392 self.with_anonymous_lifetime_mode(
1393 AnonymousLifetimeMode::ReportError,
1396 predicates: wc.predicates
1398 .map(|predicate| this.lower_where_predicate(predicate))
1406 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1408 WherePredicate::BoundPredicate(WhereBoundPredicate {
1409 ref bound_generic_params,
1414 self.with_in_scope_lifetime_defs(
1415 &bound_generic_params,
1417 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1418 bound_generic_params: this.lower_generic_params(
1419 bound_generic_params,
1420 &NodeMap::default(),
1421 ImplTraitContext::disallowed(),
1423 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1426 .filter_map(|bound| match *bound {
1427 // Ignore `?Trait` bounds.
1428 // They were copied into type parameters already.
1429 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1430 _ => Some(this.lower_param_bound(
1432 ImplTraitContext::disallowed(),
1441 WherePredicate::RegionPredicate(WhereRegionPredicate {
1445 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1447 lifetime: self.lower_lifetime(lifetime),
1448 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1450 WherePredicate::EqPredicate(WhereEqPredicate {
1456 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1457 hir_id: self.lower_node_id(id),
1458 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1459 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),