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 if let Some(hir_item) = lctx.lower_item(item) {
64 item_hir_id = Some(hir_item.hir_id);
65 lctx.insert_item(hir_item);
69 if let Some(hir_id) = item_hir_id {
70 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
71 let this = &mut ItemLowerer { lctx: this };
72 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
73 this.with_trait_impl_ref(opt_trait_ref, |this| {
74 visit::walk_item(this, item)
77 visit::walk_item(this, item);
83 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
84 self.lctx.with_hir_id_owner(item.id, |lctx| {
85 let hir_item = lctx.lower_trait_item(item);
86 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
87 lctx.trait_items.insert(id, hir_item);
88 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
91 visit::walk_trait_item(self, item);
94 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
95 self.lctx.with_hir_id_owner(item.id, |lctx| {
96 let hir_item = lctx.lower_impl_item(item);
97 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
98 lctx.impl_items.insert(id, hir_item);
99 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
101 visit::walk_impl_item(self, item);
105 impl LoweringContext<'_> {
106 // Same as the method above, but accepts `hir::GenericParam`s
107 // instead of `ast::GenericParam`s.
108 // This should only be used with generics that have already had their
109 // in-band lifetimes added. In practice, this means that this function is
110 // only used when lowering a child item of a trait or impl.
111 fn with_parent_item_lifetime_defs<T>(
113 parent_hir_id: hir::HirId,
114 f: impl FnOnce(&mut LoweringContext<'_>) -> T,
116 let old_len = self.in_scope_lifetimes.len();
118 let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
119 hir::ItemKind::Impl(_, _, _, ref generics, ..)
120 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
125 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
126 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
129 self.in_scope_lifetimes.extend(lt_def_names);
133 self.in_scope_lifetimes.truncate(old_len);
137 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
140 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
144 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
145 let node_ids = match i.node {
146 ItemKind::Use(ref use_tree) => {
147 let mut vec = smallvec![i.id];
148 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
151 ItemKind::MacroDef(..) => SmallVec::new(),
153 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
154 ItemKind::Static(ref ty, ..) => {
155 let mut ids = smallvec![i.id];
156 if self.sess.features_untracked().impl_trait_in_bindings {
157 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
158 visitor.visit_ty(ty);
162 ItemKind::Const(ref ty, ..) => {
163 let mut ids = smallvec![i.id];
164 if self.sess.features_untracked().impl_trait_in_bindings {
165 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
166 visitor.visit_ty(ty);
170 _ => smallvec![i.id],
173 node_ids.into_iter().map(|node_id| hir::ItemId {
174 id: self.allocate_hir_id_counter(node_id)
178 fn lower_item_id_use_tree(
182 vec: &mut SmallVec<[NodeId; 1]>
185 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
187 self.lower_item_id_use_tree(nested, id, vec);
189 UseTreeKind::Glob => {}
190 UseTreeKind::Simple(_, id1, id2) => {
191 for (_, &id) in self.expect_full_res_from_use(base_id)
193 .zip([id1, id2].iter())
201 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
202 let mut ident = i.ident;
203 let mut vis = self.lower_visibility(&i.vis, None);
204 let mut attrs = self.lower_attrs_extendable(&i.attrs);
205 if self.resolver.has_derives(i.id, SpecialDerives::PARTIAL_EQ | SpecialDerives::EQ) {
206 // Add `#[structural_match]` if the item derived both `PartialEq` and `Eq`.
207 let ident = Ident::new(sym::structural_match, i.span);
208 attrs.push(attr::mk_attr_outer(attr::mk_word_item(ident)));
210 let attrs = attrs.into();
212 if let ItemKind::MacroDef(ref def) = i.node {
213 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
214 let body = self.lower_token_stream(def.stream());
215 let hir_id = self.lower_node_id(i.id);
216 self.exported_macros.push(hir::MacroDef {
226 self.non_exported_macro_attrs.extend(attrs.into_iter());
231 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
234 hir_id: self.lower_node_id(i.id),
247 attrs: &hir::HirVec<Attribute>,
248 vis: &mut hir::Visibility,
252 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
253 ItemKind::Use(ref use_tree) => {
254 // Start with an empty prefix.
260 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
262 ItemKind::Static(ref t, m, ref e) => {
263 hir::ItemKind::Static(
266 if self.sess.features_untracked().impl_trait_in_bindings {
267 ImplTraitContext::OpaqueTy(None)
269 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
272 self.lower_mutability(m),
273 self.lower_const_body(e),
276 ItemKind::Const(ref t, ref e) => {
277 hir::ItemKind::Const(
280 if self.sess.features_untracked().impl_trait_in_bindings {
281 ImplTraitContext::OpaqueTy(None)
283 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
286 self.lower_const_body(e)
289 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
290 let fn_def_id = self.resolver.definitions().local_def_id(id);
291 self.with_new_scopes(|this| {
292 this.current_item = Some(ident.span);
294 // Note: we don't need to change the return type from `T` to
295 // `impl Future<Output = T>` here because lower_body
296 // only cares about the input argument patterns in the function
297 // declaration (decl), not the return types.
298 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
300 let (generics, fn_decl) = this.add_in_band_defs(
303 AnonymousLifetimeMode::PassThrough,
304 |this, idty| this.lower_fn_decl(
306 Some((fn_def_id, idty)),
308 header.asyncness.node.opt_return_id()
314 this.lower_fn_header(header),
320 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
321 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
322 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
323 ItemKind::TyAlias(ref t, ref generics) => hir::ItemKind::TyAlias(
324 self.lower_ty(t, ImplTraitContext::disallowed()),
325 self.lower_generics(generics, ImplTraitContext::disallowed()),
327 ItemKind::OpaqueTy(ref b, ref generics) => hir::ItemKind::OpaqueTy(
329 generics: self.lower_generics(generics,
330 ImplTraitContext::OpaqueTy(None)),
331 bounds: self.lower_param_bounds(b,
332 ImplTraitContext::OpaqueTy(None)),
334 origin: hir::OpaqueTyOrigin::TypeAlias,
337 ItemKind::Enum(ref enum_definition, ref generics) => {
340 variants: enum_definition
343 .map(|x| self.lower_variant(x))
346 self.lower_generics(generics, ImplTraitContext::disallowed()),
349 ItemKind::Struct(ref struct_def, ref generics) => {
350 let struct_def = self.lower_variant_data(struct_def);
351 hir::ItemKind::Struct(
353 self.lower_generics(generics, ImplTraitContext::disallowed()),
356 ItemKind::Union(ref vdata, ref generics) => {
357 let vdata = self.lower_variant_data(vdata);
358 hir::ItemKind::Union(
360 self.lower_generics(generics, ImplTraitContext::disallowed()),
372 let def_id = self.resolver.definitions().local_def_id(id);
374 // Lower the "impl header" first. This ordering is important
375 // for in-band lifetimes! Consider `'a` here:
377 // impl Foo<'a> for u32 {
378 // fn method(&'a self) { .. }
381 // Because we start by lowering the `Foo<'a> for u32`
382 // part, we will add `'a` to the list of generics on
383 // the impl. When we then encounter it later in the
384 // method, it will not be considered an in-band
385 // lifetime to be added, but rather a reference to a
387 let lowered_trait_impl_id = self.lower_node_id(id);
388 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
391 AnonymousLifetimeMode::CreateParameter,
393 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
394 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
397 if let Some(ref trait_ref) = trait_ref {
398 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
399 this.trait_impls.entry(def_id).or_default().push(
400 lowered_trait_impl_id);
404 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
406 (trait_ref, lowered_ty)
410 let new_impl_items = self.with_in_scope_lifetime_defs(
411 &ast_generics.params,
415 .map(|item| this.lower_impl_item_ref(item))
421 self.lower_unsafety(unsafety),
422 self.lower_impl_polarity(polarity),
423 self.lower_defaultness(defaultness, true /* [1] */),
430 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
431 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
434 .map(|item| self.lower_trait_item_ref(item))
436 hir::ItemKind::Trait(
437 self.lower_is_auto(is_auto),
438 self.lower_unsafety(unsafety),
439 self.lower_generics(generics, ImplTraitContext::disallowed()),
444 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
445 self.lower_generics(generics, ImplTraitContext::disallowed()),
446 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
448 ItemKind::MacroDef(..)
449 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
452 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
453 // not cause an assertion failure inside the `lower_defaultness` function.
461 vis: &mut hir::Visibility,
463 attrs: &hir::HirVec<Attribute>,
465 debug!("lower_use_tree(tree={:?})", tree);
466 debug!("lower_use_tree: vis = {:?}", vis);
468 let path = &tree.prefix;
469 let segments = prefix
472 .chain(path.segments.iter())
477 UseTreeKind::Simple(rename, id1, id2) => {
478 *ident = tree.ident();
480 // First, apply the prefix to the path.
481 let mut path = Path {
486 // Correctly resolve `self` imports.
487 if path.segments.len() > 1
488 && path.segments.last().unwrap().ident.name == kw::SelfLower
490 let _ = path.segments.pop();
491 if rename.is_none() {
492 *ident = path.segments.last().unwrap().ident;
496 let mut resolutions = self.expect_full_res_from_use(id);
497 // We want to return *something* from this function, so hold onto the first item
499 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
501 // Here, we are looping over namespaces, if they exist for the definition
502 // being imported. We only handle type and value namespaces because we
503 // won't be dealing with macros in the rest of the compiler.
504 // Essentially a single `use` which imports two names is desugared into
506 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
508 let mut path = path.clone();
509 for seg in &mut path.segments {
510 seg.id = self.sess.next_node_id();
512 let span = path.span;
514 self.with_hir_id_owner(new_node_id, |this| {
515 let new_id = this.lower_node_id(new_node_id);
516 let res = this.lower_res(res);
518 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
519 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
520 let vis = this.rebuild_vis(&vis);
526 attrs: attrs.into_iter().cloned().collect(),
536 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
537 hir::ItemKind::Use(path, hir::UseKind::Single)
539 UseTreeKind::Glob => {
540 let path = P(self.lower_path(
548 hir::ItemKind::Use(path, hir::UseKind::Glob)
550 UseTreeKind::Nested(ref trees) => {
551 // Nested imports are desugared into simple imports.
552 // So, if we start with
555 // pub(x) use foo::{a, b};
558 // we will create three items:
561 // pub(x) use foo::a;
562 // pub(x) use foo::b;
563 // pub(x) use foo::{}; // <-- this is called the `ListStem`
566 // The first two are produced by recursively invoking
567 // `lower_use_tree` (and indeed there may be things
568 // like `use foo::{a::{b, c}}` and so forth). They
569 // wind up being directly added to
570 // `self.items`. However, the structure of this
571 // function also requires us to return one item, and
572 // for that we return the `{}` import (called the
577 span: prefix.span.to(path.span),
580 // Add all the nested `PathListItem`s to the HIR.
581 for &(ref use_tree, id) in trees {
582 let new_hir_id = self.lower_node_id(id);
584 let mut prefix = prefix.clone();
586 // Give the segments new node-ids since they are being cloned.
587 for seg in &mut prefix.segments {
588 seg.id = self.sess.next_node_id();
591 // Each `use` import is an item and thus are owners of the
592 // names in the path. Up to this point the nested import is
593 // the current owner, since we want each desugared import to
594 // own its own names, we have to adjust the owner before
595 // lowering the rest of the import.
596 self.with_hir_id_owner(id, |this| {
597 let mut vis = this.rebuild_vis(&vis);
598 let mut ident = *ident;
600 let item = this.lower_use_tree(use_tree,
611 attrs: attrs.into_iter().cloned().collect(),
620 // Subtle and a bit hacky: we lower the privacy level
621 // of the list stem to "private" most of the time, but
622 // not for "restricted" paths. The key thing is that
623 // we don't want it to stay as `pub` (with no caveats)
624 // because that affects rustdoc and also the lints
625 // about `pub` items. But we can't *always* make it
626 // private -- particularly not for restricted paths --
627 // because it contains node-ids that would then be
628 // unused, failing the check that HirIds are "densely
631 hir::VisibilityKind::Public |
632 hir::VisibilityKind::Crate(_) |
633 hir::VisibilityKind::Inherited => {
634 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
636 hir::VisibilityKind::Restricted { .. } => {
637 // Do nothing here, as described in the comment on the match.
641 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
642 let res = self.lower_res(res);
643 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
644 hir::ItemKind::Use(path, hir::UseKind::ListStem)
649 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
650 /// many times in the HIR tree; for each occurrence, we need to assign distinct
651 /// `NodeId`s. (See, e.g., #56128.)
652 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
653 debug!("rebuild_use_path(path = {:?})", path);
654 let segments = path.segments.iter().map(|seg| hir::PathSegment {
656 hir_id: seg.hir_id.map(|_| self.next_id()),
659 infer_args: seg.infer_args,
668 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
669 let vis_kind = match vis.node {
670 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
671 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
672 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
673 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
674 hir::VisibilityKind::Restricted {
675 path: P(self.rebuild_use_path(path)),
676 hir_id: self.next_id(),
680 respan(vis.span, vis_kind)
683 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
684 let def_id = self.resolver.definitions().local_def_id(i.id);
686 hir_id: self.lower_node_id(i.id),
688 attrs: self.lower_attrs(&i.attrs),
690 ForeignItemKind::Fn(ref fdec, ref generics) => {
691 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
694 AnonymousLifetimeMode::PassThrough,
697 // Disallow impl Trait in foreign items
698 this.lower_fn_decl(fdec, None, false, None),
699 this.lower_fn_args_to_names(fdec),
704 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
706 ForeignItemKind::Static(ref t, m) => {
707 hir::ForeignItemKind::Static(
708 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
710 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
711 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
713 vis: self.lower_visibility(&i.vis, None),
718 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
723 .map(|x| self.lower_foreign_item(x))
728 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
735 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
737 node: hir::VariantKind {
739 id: self.lower_node_id(v.node.id),
740 attrs: self.lower_attrs(&v.node.attrs),
741 data: self.lower_variant_data(&v.node.data),
742 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
748 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
750 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
751 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
754 VariantData::Tuple(ref fields, id) => {
755 hir::VariantData::Tuple(
759 .map(|f| self.lower_struct_field(f))
761 self.lower_node_id(id),
764 VariantData::Unit(id) => {
765 hir::VariantData::Unit(self.lower_node_id(id))
770 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
771 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node {
772 let t = self.lower_path_ty(
776 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
777 ImplTraitContext::disallowed()
781 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
785 hir_id: self.lower_node_id(f.id),
786 ident: match f.ident {
787 Some(ident) => ident,
788 // FIXME(jseyfried): positional field hygiene.
789 None => Ident::new(sym::integer(index), f.span),
791 vis: self.lower_visibility(&f.vis, None),
793 attrs: self.lower_attrs(&f.attrs),
797 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
798 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
800 let (generics, node) = match i.node {
801 TraitItemKind::Const(ref ty, ref default) => (
802 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
803 hir::TraitItemKind::Const(
804 self.lower_ty(ty, ImplTraitContext::disallowed()),
807 .map(|x| self.lower_const_body(x)),
810 TraitItemKind::Method(ref sig, None) => {
811 let names = self.lower_fn_args_to_names(&sig.decl);
812 let (generics, sig) = self.lower_method_sig(
819 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
821 TraitItemKind::Method(ref sig, Some(ref body)) => {
822 let body_id = self.lower_fn_body_block(&sig.decl, body);
823 let (generics, sig) = self.lower_method_sig(
830 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
832 TraitItemKind::Type(ref bounds, ref default) => {
833 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
834 let node = hir::TraitItemKind::Type(
835 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
838 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
843 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
847 hir_id: self.lower_node_id(i.id),
849 attrs: self.lower_attrs(&i.attrs),
856 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
857 let (kind, has_default) = match i.node {
858 TraitItemKind::Const(_, ref default) => {
859 (hir::AssocItemKind::Const, default.is_some())
861 TraitItemKind::Type(_, ref default) => {
862 (hir::AssocItemKind::Type, default.is_some())
864 TraitItemKind::Method(ref sig, ref default) => (
865 hir::AssocItemKind::Method {
866 has_self: sig.decl.has_self(),
870 TraitItemKind::Macro(..) => unimplemented!(),
873 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
876 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
881 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
882 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
884 let (generics, node) = match i.node {
885 ImplItemKind::Const(ref ty, ref expr) => (
886 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
887 hir::ImplItemKind::Const(
888 self.lower_ty(ty, ImplTraitContext::disallowed()),
889 self.lower_const_body(expr),
892 ImplItemKind::Method(ref sig, ref body) => {
893 self.current_item = Some(i.span);
894 let body_id = self.lower_maybe_async_body(
895 &sig.decl, sig.header.asyncness.node, body
897 let impl_trait_return_allow = !self.is_in_trait_impl;
898 let (generics, sig) = self.lower_method_sig(
902 impl_trait_return_allow,
903 sig.header.asyncness.node.opt_return_id(),
906 (generics, hir::ImplItemKind::Method(sig, body_id))
908 ImplItemKind::TyAlias(ref ty) => (
909 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
910 hir::ImplItemKind::TyAlias(self.lower_ty(ty, ImplTraitContext::disallowed())),
912 ImplItemKind::OpaqueTy(ref bounds) => (
913 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
914 hir::ImplItemKind::OpaqueTy(
915 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
918 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
922 hir_id: self.lower_node_id(i.id),
924 attrs: self.lower_attrs(&i.attrs),
926 vis: self.lower_visibility(&i.vis, None),
927 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
932 // [1] since `default impl` is not yet implemented, this is always true in impls
935 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
937 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
940 vis: self.lower_visibility(&i.vis, Some(i.id)),
941 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
943 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
944 ImplItemKind::TyAlias(..) => hir::AssocItemKind::Type,
945 ImplItemKind::OpaqueTy(..) => hir::AssocItemKind::OpaqueTy,
946 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
947 has_self: sig.decl.has_self(),
949 ImplItemKind::Macro(..) => unimplemented!(),
953 // [1] since `default impl` is not yet implemented, this is always true in impls
956 /// If an `explicit_owner` is given, this method allocates the `HirId` in
957 /// the address space of that item instead of the item currently being
958 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
959 /// lower a `Visibility` value although we haven't lowered the owning
960 /// `ImplItem` in question yet.
964 explicit_owner: Option<NodeId>,
965 ) -> hir::Visibility {
966 let node = match v.node {
967 VisibilityKind::Public => hir::VisibilityKind::Public,
968 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
969 VisibilityKind::Restricted { ref path, id } => {
970 debug!("lower_visibility: restricted path id = {:?}", id);
971 let lowered_id = if let Some(owner) = explicit_owner {
972 self.lower_node_id_with_owner(id, owner)
974 self.lower_node_id(id)
976 let res = self.expect_full_res(id);
977 let res = self.lower_res(res);
978 hir::VisibilityKind::Restricted {
979 path: P(self.lower_path_extra(
988 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
993 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
995 Defaultness::Default => hir::Defaultness::Default {
996 has_value: has_value,
998 Defaultness::Final => {
1000 hir::Defaultness::Final
1005 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
1007 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1008 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1012 fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
1013 let body = hir::Body {
1014 generator_kind: self.generator_kind,
1019 self.bodies.insert(id, body);
1025 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1027 let prev_gen_kind = self.generator_kind.take();
1028 let (arguments, result) = f(self);
1029 let body_id = self.record_body(arguments, result);
1030 self.generator_kind = prev_gen_kind;
1034 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1036 attrs: self.lower_attrs(&arg.attrs),
1037 hir_id: self.lower_node_id(arg.id),
1038 pat: self.lower_pat(&arg.pat),
1043 pub(super) fn lower_fn_body(
1046 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1048 self.lower_body(|this| (
1049 decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1054 fn lower_fn_body_block(&mut self, decl: &FnDecl, body: &Block) -> hir::BodyId {
1055 self.lower_fn_body(decl, |this| {
1056 let body = this.lower_block(body, false);
1057 this.expr_block(body, ThinVec::new())
1061 pub(super) fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1062 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1065 fn lower_maybe_async_body(
1071 let closure_id = match asyncness {
1072 IsAsync::Async { closure_id, .. } => closure_id,
1073 IsAsync::NotAsync => return self.lower_fn_body_block(decl, body),
1076 self.lower_body(|this| {
1077 let mut arguments: Vec<hir::Arg> = Vec::new();
1078 let mut statements: Vec<hir::Stmt> = Vec::new();
1080 // Async function arguments are lowered into the closure body so that they are
1081 // captured and so that the drop order matches the equivalent non-async functions.
1085 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1092 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1094 // let __arg2 = __arg2;
1095 // let <pattern> = __arg2;
1096 // let __arg1 = __arg1;
1097 // let <pattern> = __arg1;
1098 // let __arg0 = __arg0;
1099 // let <pattern> = __arg0;
1103 // If `<pattern>` is a simple ident, then it is lowered to a single
1104 // `let <pattern> = <pattern>;` statement as an optimization.
1105 for (index, argument) in decl.inputs.iter().enumerate() {
1106 let argument = this.lower_arg(argument);
1107 let span = argument.pat.span;
1109 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1110 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
1111 let (ident, is_simple_argument) = match argument.pat.node {
1112 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
1115 // Replace the ident for bindings that aren't simple.
1116 let name = format!("__arg{}", index);
1117 let ident = Ident::from_str(&name);
1123 let desugared_span =
1124 this.mark_span_with_reason(DesugaringKind::Async, span, None);
1126 // Construct an argument representing `__argN: <ty>` to replace the argument of the
1129 // If this is the simple case, this argument will end up being the same as the
1130 // original argument, but with a different pattern id.
1131 let mut stmt_attrs = ThinVec::new();
1132 stmt_attrs.extend(argument.attrs.iter().cloned());
1133 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
1134 let new_argument = hir::Arg {
1135 attrs: argument.attrs,
1136 hir_id: argument.hir_id,
1137 pat: new_argument_pat,
1138 span: argument.span,
1142 if is_simple_argument {
1143 // If this is the simple case, then we only insert one statement that is
1144 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1145 // `HirId`s are densely assigned.
1146 let expr = this.expr_ident(desugared_span, ident, new_argument_id);
1147 let stmt = this.stmt_let_pat(
1152 hir::LocalSource::AsyncFn
1154 statements.push(stmt);
1156 // If this is not the simple case, then we construct two statements:
1159 // let __argN = __argN;
1160 // let <pat> = __argN;
1163 // The first statement moves the argument into the closure and thus ensures
1164 // that the drop order is correct.
1166 // The second statement creates the bindings that the user wrote.
1168 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1169 // because the user may have specified a `ref mut` binding in the next
1171 let (move_pat, move_id) = this.pat_ident_binding_mode(
1172 desugared_span, ident, hir::BindingAnnotation::Mutable);
1173 let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
1174 let move_stmt = this.stmt_let_pat(
1179 hir::LocalSource::AsyncFn
1182 // Construct the `let <pat> = __argN;` statement. We re-use the original
1183 // argument's pattern so that `HirId`s are densely assigned.
1184 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1185 let pattern_stmt = this.stmt_let_pat(
1188 Some(P(pattern_expr)),
1190 hir::LocalSource::AsyncFn
1193 statements.push(move_stmt);
1194 statements.push(pattern_stmt);
1197 arguments.push(new_argument);
1200 let async_expr = this.make_async_expr(
1201 CaptureBy::Value, closure_id, None, body.span,
1203 let body = this.lower_block_with_stmts(body, false, statements);
1204 this.expr_block(body, ThinVec::new())
1206 (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
1210 fn lower_method_sig(
1212 generics: &Generics,
1215 impl_trait_return_allow: bool,
1216 is_async: Option<NodeId>,
1217 ) -> (hir::Generics, hir::MethodSig) {
1218 let header = self.lower_fn_header(sig.header);
1219 let (generics, decl) = self.add_in_band_defs(
1222 AnonymousLifetimeMode::PassThrough,
1223 |this, idty| this.lower_fn_decl(
1225 Some((fn_def_id, idty)),
1226 impl_trait_return_allow,
1230 (generics, hir::MethodSig { header, decl })
1233 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
1235 IsAuto::Yes => hir::IsAuto::Yes,
1236 IsAuto::No => hir::IsAuto::No,
1240 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1242 unsafety: self.lower_unsafety(h.unsafety),
1243 asyncness: self.lower_asyncness(h.asyncness.node),
1244 constness: self.lower_constness(h.constness),
1249 pub(super) fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1251 Unsafety::Unsafe => hir::Unsafety::Unsafe,
1252 Unsafety::Normal => hir::Unsafety::Normal,
1256 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1258 Constness::Const => hir::Constness::Const,
1259 Constness::NotConst => hir::Constness::NotConst,
1263 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1265 IsAsync::Async { .. } => hir::IsAsync::Async,
1266 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1270 pub(super) fn lower_generics(
1272 generics: &Generics,
1273 itctx: ImplTraitContext<'_>)
1276 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1277 // FIXME: this could probably be done with less rightward drift. It also looks like two
1278 // control paths where `report_error` is called are the only paths that advance to after the
1279 // match statement, so the error reporting could probably just be moved there.
1280 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1281 for pred in &generics.where_clause.predicates {
1282 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1283 'next_bound: for bound in &bound_pred.bounds {
1284 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1285 let report_error = |this: &mut Self| {
1286 this.diagnostic().span_err(
1287 bound_pred.bounded_ty.span,
1288 "`?Trait` bounds are only permitted at the \
1289 point where a type parameter is declared",
1292 // Check if the where clause type is a plain type parameter.
1293 match bound_pred.bounded_ty.node {
1294 TyKind::Path(None, ref path)
1295 if path.segments.len() == 1
1296 && bound_pred.bound_generic_params.is_empty() =>
1298 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
1299 .get_partial_res(bound_pred.bounded_ty.id)
1300 .map(|d| d.base_res())
1302 if let Some(node_id) =
1303 self.resolver.definitions().as_local_node_id(def_id)
1305 for param in &generics.params {
1307 GenericParamKind::Type { .. } => {
1308 if node_id == param.id {
1309 add_bounds.entry(param.id)
1311 .push(bound.clone());
1312 continue 'next_bound;
1322 _ => report_error(self),
1330 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
1331 where_clause: self.lower_where_clause(&generics.where_clause),
1332 span: generics.span,
1336 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1337 self.with_anonymous_lifetime_mode(
1338 AnonymousLifetimeMode::ReportError,
1341 predicates: wc.predicates
1343 .map(|predicate| this.lower_where_predicate(predicate))
1351 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1353 WherePredicate::BoundPredicate(WhereBoundPredicate {
1354 ref bound_generic_params,
1359 self.with_in_scope_lifetime_defs(
1360 &bound_generic_params,
1362 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1363 bound_generic_params: this.lower_generic_params(
1364 bound_generic_params,
1365 &NodeMap::default(),
1366 ImplTraitContext::disallowed(),
1368 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1371 .filter_map(|bound| match *bound {
1372 // Ignore `?Trait` bounds.
1373 // They were copied into type parameters already.
1374 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1375 _ => Some(this.lower_param_bound(
1377 ImplTraitContext::disallowed(),
1386 WherePredicate::RegionPredicate(WhereRegionPredicate {
1390 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1392 lifetime: self.lower_lifetime(lifetime),
1393 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1395 WherePredicate::EqPredicate(WhereEqPredicate {
1401 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1402 hir_id: self.lower_node_id(id),
1403 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1404 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),