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;
15 use rustc_target::spec::abi;
17 use std::collections::BTreeSet;
18 use smallvec::SmallVec;
21 use syntax::visit::{self, Visitor};
22 use syntax::source_map::{respan, DesugaringKind};
23 use syntax::symbol::{kw, sym};
26 use rustc_error_codes::*;
28 pub(super) struct ItemLowerer<'tcx, 'interner> {
29 pub(super) lctx: &'tcx mut LoweringContext<'interner>,
32 impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> {
33 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
37 let old = self.lctx.is_in_trait_impl;
38 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
44 self.lctx.is_in_trait_impl = old;
48 impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> {
49 fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
50 let hir_id = self.lctx.lower_node_id(n);
52 self.lctx.modules.insert(hir_id, hir::ModuleItems {
53 items: BTreeSet::new(),
54 trait_items: BTreeSet::new(),
55 impl_items: BTreeSet::new(),
58 let old = self.lctx.current_module;
59 self.lctx.current_module = hir_id;
60 visit::walk_mod(self, m);
61 self.lctx.current_module = old;
64 fn visit_item(&mut self, item: &'tcx Item) {
65 let mut item_hir_id = None;
66 self.lctx.with_hir_id_owner(item.id, |lctx| {
67 lctx.without_in_scope_lifetime_defs(|lctx| {
68 if let Some(hir_item) = lctx.lower_item(item) {
69 item_hir_id = Some(hir_item.hir_id);
70 lctx.insert_item(hir_item);
75 if let Some(hir_id) = item_hir_id {
76 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
77 let this = &mut ItemLowerer { lctx: this };
78 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.kind {
79 this.with_trait_impl_ref(opt_trait_ref, |this| {
80 visit::walk_item(this, item)
83 visit::walk_item(this, item);
89 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
90 self.lctx.with_hir_id_owner(item.id, |lctx| {
91 let hir_item = lctx.lower_trait_item(item);
92 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
93 lctx.trait_items.insert(id, hir_item);
94 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
97 visit::walk_trait_item(self, item);
100 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
101 self.lctx.with_hir_id_owner(item.id, |lctx| {
102 let hir_item = lctx.lower_impl_item(item);
103 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
104 lctx.impl_items.insert(id, hir_item);
105 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
107 visit::walk_impl_item(self, item);
111 impl LoweringContext<'_> {
112 // Same as the method above, but accepts `hir::GenericParam`s
113 // instead of `ast::GenericParam`s.
114 // This should only be used with generics that have already had their
115 // in-band lifetimes added. In practice, this means that this function is
116 // only used when lowering a child item of a trait or impl.
117 fn with_parent_item_lifetime_defs<T>(
119 parent_hir_id: hir::HirId,
120 f: impl FnOnce(&mut LoweringContext<'_>) -> T,
122 let old_len = self.in_scope_lifetimes.len();
124 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
125 hir::ItemKind::Impl(_, _, _, ref generics, ..)
126 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
131 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
132 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
135 self.in_scope_lifetimes.extend(lt_def_names);
139 self.in_scope_lifetimes.truncate(old_len);
143 // Clears (and restores) the `in_scope_lifetimes` field. Used when
144 // visiting nested items, which never inherit in-scope lifetimes
145 // from their surrounding environment.
146 fn without_in_scope_lifetime_defs<T>(
148 f: impl FnOnce(&mut LoweringContext<'_>) -> T,
150 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
152 // this vector is only used when walking over impl headers,
153 // input types, and the like, and should not be non-empty in
155 assert!(self.lifetimes_to_define.is_empty());
159 assert!(self.in_scope_lifetimes.is_empty());
160 self.in_scope_lifetimes = old_in_scope_lifetimes;
165 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
168 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
172 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
173 let node_ids = match i.kind {
174 ItemKind::Use(ref use_tree) => {
175 let mut vec = smallvec![i.id];
176 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
179 ItemKind::MacroDef(..) => SmallVec::new(),
181 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
182 ItemKind::Static(ref ty, ..) => {
183 let mut ids = smallvec![i.id];
184 if self.sess.features_untracked().impl_trait_in_bindings {
185 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
186 visitor.visit_ty(ty);
190 ItemKind::Const(ref ty, ..) => {
191 let mut ids = smallvec![i.id];
192 if self.sess.features_untracked().impl_trait_in_bindings {
193 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
194 visitor.visit_ty(ty);
198 _ => smallvec![i.id],
201 node_ids.into_iter().map(|node_id| hir::ItemId {
202 id: self.allocate_hir_id_counter(node_id)
206 fn lower_item_id_use_tree(
210 vec: &mut SmallVec<[NodeId; 1]>
213 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
215 self.lower_item_id_use_tree(nested, id, vec);
217 UseTreeKind::Glob => {}
218 UseTreeKind::Simple(_, id1, id2) => {
219 for (_, &id) in self.expect_full_res_from_use(base_id)
221 .zip([id1, id2].iter())
229 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
230 let mut ident = i.ident;
231 let mut vis = self.lower_visibility(&i.vis, None);
232 let attrs = self.lower_attrs(&i.attrs);
234 if let ItemKind::MacroDef(ref def) = i.kind {
235 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
236 let body = self.lower_token_stream(def.stream());
237 let hir_id = self.lower_node_id(i.id);
238 self.exported_macros.push(hir::MacroDef {
248 self.non_exported_macro_attrs.extend(attrs.into_iter());
253 let kind = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.kind);
256 hir_id: self.lower_node_id(i.id),
269 attrs: &hir::HirVec<Attribute>,
270 vis: &mut hir::Visibility,
274 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
275 ItemKind::Use(ref use_tree) => {
276 // Start with an empty prefix.
282 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
284 ItemKind::Static(ref t, m, ref e) => {
285 hir::ItemKind::Static(
288 if self.sess.features_untracked().impl_trait_in_bindings {
289 ImplTraitContext::OpaqueTy(None)
291 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
295 self.lower_const_body(e),
298 ItemKind::Const(ref t, ref e) => {
299 hir::ItemKind::Const(
302 if self.sess.features_untracked().impl_trait_in_bindings {
303 ImplTraitContext::OpaqueTy(None)
305 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
308 self.lower_const_body(e)
311 ItemKind::Fn(FnSig { ref decl, header }, ref generics, ref body) => {
312 let fn_def_id = self.resolver.definitions().local_def_id(id);
313 self.with_new_scopes(|this| {
314 this.current_item = Some(ident.span);
316 // Note: we don't need to change the return type from `T` to
317 // `impl Future<Output = T>` here because lower_body
318 // only cares about the input argument patterns in the function
319 // declaration (decl), not the return types.
320 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
322 let (generics, decl) = this.add_in_band_defs(
325 AnonymousLifetimeMode::PassThrough,
326 |this, idty| this.lower_fn_decl(
328 Some((fn_def_id, idty)),
330 header.asyncness.node.opt_return_id()
333 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
334 hir::ItemKind::Fn(sig, generics, body_id)
337 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
338 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
339 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
340 ItemKind::TyAlias(ref ty, ref generics) => match ty.kind.opaque_top_hack() {
342 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
343 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
344 hir::ItemKind::TyAlias(ty, generics)
347 let ty = hir::OpaqueTy {
348 generics: self.lower_generics(generics, ImplTraitContext::OpaqueTy(None)),
349 bounds: self.lower_param_bounds(bounds, ImplTraitContext::OpaqueTy(None)),
351 origin: hir::OpaqueTyOrigin::TypeAlias,
353 hir::ItemKind::OpaqueTy(ty)
356 ItemKind::Enum(ref enum_definition, ref generics) => {
359 variants: enum_definition
362 .map(|x| self.lower_variant(x))
365 self.lower_generics(generics, ImplTraitContext::disallowed()),
368 ItemKind::Struct(ref struct_def, ref generics) => {
369 let struct_def = self.lower_variant_data(struct_def);
370 hir::ItemKind::Struct(
372 self.lower_generics(generics, ImplTraitContext::disallowed()),
375 ItemKind::Union(ref vdata, ref generics) => {
376 let vdata = self.lower_variant_data(vdata);
377 hir::ItemKind::Union(
379 self.lower_generics(generics, ImplTraitContext::disallowed()),
391 let def_id = self.resolver.definitions().local_def_id(id);
393 // Lower the "impl header" first. This ordering is important
394 // for in-band lifetimes! Consider `'a` here:
396 // impl Foo<'a> for u32 {
397 // fn method(&'a self) { .. }
400 // Because we start by lowering the `Foo<'a> for u32`
401 // part, we will add `'a` to the list of generics on
402 // the impl. When we then encounter it later in the
403 // method, it will not be considered an in-band
404 // lifetime to be added, but rather a reference to a
406 let lowered_trait_impl_id = self.lower_node_id(id);
407 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
410 AnonymousLifetimeMode::CreateParameter,
412 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
413 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
416 if let Some(ref trait_ref) = trait_ref {
417 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
418 this.trait_impls.entry(def_id).or_default().push(
419 lowered_trait_impl_id);
423 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
425 (trait_ref, lowered_ty)
429 let new_impl_items = self.with_in_scope_lifetime_defs(
430 &ast_generics.params,
434 .map(|item| this.lower_impl_item_ref(item))
442 self.lower_defaultness(defaultness, true /* [1] */),
449 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
450 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
453 .map(|item| self.lower_trait_item_ref(item))
455 hir::ItemKind::Trait(
458 self.lower_generics(generics, ImplTraitContext::disallowed()),
463 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
464 self.lower_generics(generics, ImplTraitContext::disallowed()),
465 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
467 ItemKind::MacroDef(..)
468 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
471 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
472 // not cause an assertion failure inside the `lower_defaultness` function.
480 vis: &mut hir::Visibility,
482 attrs: &hir::HirVec<Attribute>,
484 debug!("lower_use_tree(tree={:?})", tree);
485 debug!("lower_use_tree: vis = {:?}", vis);
487 let path = &tree.prefix;
488 let segments = prefix
491 .chain(path.segments.iter())
496 UseTreeKind::Simple(rename, id1, id2) => {
497 *ident = tree.ident();
499 // First, apply the prefix to the path.
500 let mut path = Path {
505 // Correctly resolve `self` imports.
506 if path.segments.len() > 1
507 && path.segments.last().unwrap().ident.name == kw::SelfLower
509 let _ = path.segments.pop();
510 if rename.is_none() {
511 *ident = path.segments.last().unwrap().ident;
515 let mut resolutions = self.expect_full_res_from_use(id);
516 // We want to return *something* from this function, so hold onto the first item
518 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
520 // Here, we are looping over namespaces, if they exist for the definition
521 // being imported. We only handle type and value namespaces because we
522 // won't be dealing with macros in the rest of the compiler.
523 // Essentially a single `use` which imports two names is desugared into
525 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
527 let mut path = path.clone();
528 for seg in &mut path.segments {
529 seg.id = self.resolver.next_node_id();
531 let span = path.span;
533 self.with_hir_id_owner(new_node_id, |this| {
534 let new_id = this.lower_node_id(new_node_id);
535 let res = this.lower_res(res);
537 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
538 let kind = hir::ItemKind::Use(P(path), hir::UseKind::Single);
539 let vis = this.rebuild_vis(&vis);
545 attrs: attrs.into_iter().cloned().collect(),
554 let path = P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
555 hir::ItemKind::Use(path, hir::UseKind::Single)
557 UseTreeKind::Glob => {
558 let path = P(self.lower_path(
566 hir::ItemKind::Use(path, hir::UseKind::Glob)
568 UseTreeKind::Nested(ref trees) => {
569 // Nested imports are desugared into simple imports.
570 // So, if we start with
573 // pub(x) use foo::{a, b};
576 // we will create three items:
579 // pub(x) use foo::a;
580 // pub(x) use foo::b;
581 // pub(x) use foo::{}; // <-- this is called the `ListStem`
584 // The first two are produced by recursively invoking
585 // `lower_use_tree` (and indeed there may be things
586 // like `use foo::{a::{b, c}}` and so forth). They
587 // wind up being directly added to
588 // `self.items`. However, the structure of this
589 // function also requires us to return one item, and
590 // for that we return the `{}` import (called the
595 span: prefix.span.to(path.span),
598 // Add all the nested `PathListItem`s to the HIR.
599 for &(ref use_tree, id) in trees {
600 let new_hir_id = self.lower_node_id(id);
602 let mut prefix = prefix.clone();
604 // Give the segments new node-ids since they are being cloned.
605 for seg in &mut prefix.segments {
606 seg.id = self.resolver.next_node_id();
609 // Each `use` import is an item and thus are owners of the
610 // names in the path. Up to this point the nested import is
611 // the current owner, since we want each desugared import to
612 // own its own names, we have to adjust the owner before
613 // lowering the rest of the import.
614 self.with_hir_id_owner(id, |this| {
615 let mut vis = this.rebuild_vis(&vis);
616 let mut ident = *ident;
618 let kind = this.lower_use_tree(use_tree,
629 attrs: attrs.into_iter().cloned().collect(),
638 // Subtle and a bit hacky: we lower the privacy level
639 // of the list stem to "private" most of the time, but
640 // not for "restricted" paths. The key thing is that
641 // we don't want it to stay as `pub` (with no caveats)
642 // because that affects rustdoc and also the lints
643 // about `pub` items. But we can't *always* make it
644 // private -- particularly not for restricted paths --
645 // because it contains node-ids that would then be
646 // unused, failing the check that HirIds are "densely
649 hir::VisibilityKind::Public |
650 hir::VisibilityKind::Crate(_) |
651 hir::VisibilityKind::Inherited => {
652 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
654 hir::VisibilityKind::Restricted { .. } => {
655 // Do nothing here, as described in the comment on the match.
659 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
660 let res = self.lower_res(res);
661 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
662 hir::ItemKind::Use(path, hir::UseKind::ListStem)
667 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
668 /// many times in the HIR tree; for each occurrence, we need to assign distinct
669 /// `NodeId`s. (See, e.g., #56128.)
670 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
671 debug!("rebuild_use_path(path = {:?})", path);
672 let segments = path.segments.iter().map(|seg| hir::PathSegment {
674 hir_id: seg.hir_id.map(|_| self.next_id()),
677 infer_args: seg.infer_args,
686 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
687 let vis_kind = match vis.node {
688 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
689 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
690 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
691 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
692 hir::VisibilityKind::Restricted {
693 path: P(self.rebuild_use_path(path)),
694 hir_id: self.next_id(),
698 respan(vis.span, vis_kind)
701 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
702 let def_id = self.resolver.definitions().local_def_id(i.id);
704 hir_id: self.lower_node_id(i.id),
706 attrs: self.lower_attrs(&i.attrs),
708 ForeignItemKind::Fn(ref fdec, ref generics) => {
709 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
712 AnonymousLifetimeMode::PassThrough,
715 // Disallow `impl Trait` in foreign items.
716 this.lower_fn_decl(fdec, None, false, None),
717 this.lower_fn_params_to_names(fdec),
722 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
724 ForeignItemKind::Static(ref t, m) => {
725 hir::ForeignItemKind::Static(
726 self.lower_ty(t, ImplTraitContext::disallowed()), m)
728 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
729 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
731 vis: self.lower_visibility(&i.vis, None),
736 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
738 abi: self.lower_abi(fm.abi),
741 .map(|x| self.lower_foreign_item(x))
746 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
747 P(hir::GlobalAsm { asm: ga.asm })
750 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
752 attrs: self.lower_attrs(&v.attrs),
753 data: self.lower_variant_data(&v.data),
754 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
755 id: self.lower_node_id(v.id),
761 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
763 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
764 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
767 VariantData::Tuple(ref fields, id) => {
768 hir::VariantData::Tuple(
772 .map(|f| self.lower_struct_field(f))
774 self.lower_node_id(id),
777 VariantData::Unit(id) => {
778 hir::VariantData::Unit(self.lower_node_id(id))
783 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
784 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
785 let t = self.lower_path_ty(
789 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
790 ImplTraitContext::disallowed()
794 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
798 hir_id: self.lower_node_id(f.id),
799 ident: match f.ident {
800 Some(ident) => ident,
801 // FIXME(jseyfried): positional field hygiene.
802 None => Ident::new(sym::integer(index), f.span),
804 vis: self.lower_visibility(&f.vis, None),
806 attrs: self.lower_attrs(&f.attrs),
810 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
811 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
813 let (generics, kind) = match i.kind {
814 TraitItemKind::Const(ref ty, ref default) => (
815 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
816 hir::TraitItemKind::Const(
817 self.lower_ty(ty, ImplTraitContext::disallowed()),
820 .map(|x| self.lower_const_body(x)),
823 TraitItemKind::Method(ref sig, None) => {
824 let names = self.lower_fn_params_to_names(&sig.decl);
825 let (generics, sig) = self.lower_method_sig(
832 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
834 TraitItemKind::Method(ref sig, Some(ref body)) => {
835 let body_id = self.lower_fn_body_block(&sig.decl, body);
836 let (generics, sig) = self.lower_method_sig(
843 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
845 TraitItemKind::Type(ref bounds, ref default) => {
846 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
847 let kind = hir::TraitItemKind::Type(
848 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
851 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
856 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
860 hir_id: self.lower_node_id(i.id),
862 attrs: self.lower_attrs(&i.attrs),
869 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
870 let (kind, has_default) = match i.kind {
871 TraitItemKind::Const(_, ref default) => {
872 (hir::AssocItemKind::Const, default.is_some())
874 TraitItemKind::Type(_, ref default) => {
875 (hir::AssocItemKind::Type, default.is_some())
877 TraitItemKind::Method(ref sig, ref default) => (
878 hir::AssocItemKind::Method {
879 has_self: sig.decl.has_self(),
883 TraitItemKind::Macro(..) => unimplemented!(),
886 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
889 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
894 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
895 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
897 let (generics, kind) = match i.kind {
898 ImplItemKind::Const(ref ty, ref expr) => (
899 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
900 hir::ImplItemKind::Const(
901 self.lower_ty(ty, ImplTraitContext::disallowed()),
902 self.lower_const_body(expr),
905 ImplItemKind::Method(ref sig, ref body) => {
906 self.current_item = Some(i.span);
907 let body_id = self.lower_maybe_async_body(
908 &sig.decl, sig.header.asyncness.node, body
910 let impl_trait_return_allow = !self.is_in_trait_impl;
911 let (generics, sig) = self.lower_method_sig(
915 impl_trait_return_allow,
916 sig.header.asyncness.node.opt_return_id(),
919 (generics, hir::ImplItemKind::Method(sig, body_id))
921 ImplItemKind::TyAlias(ref ty) => {
922 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
923 let kind = match ty.kind.opaque_top_hack() {
925 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
926 hir::ImplItemKind::TyAlias(ty)
929 let bounds = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
930 hir::ImplItemKind::OpaqueTy(bounds)
935 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
939 hir_id: self.lower_node_id(i.id),
941 attrs: self.lower_attrs(&i.attrs),
943 vis: self.lower_visibility(&i.vis, None),
944 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
949 // [1] since `default impl` is not yet implemented, this is always true in impls
952 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
954 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
957 vis: self.lower_visibility(&i.vis, Some(i.id)),
958 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
959 kind: match &i.kind {
960 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
961 ImplItemKind::TyAlias(ty) => match ty.kind.opaque_top_hack() {
962 None => hir::AssocItemKind::Type,
963 Some(_) => hir::AssocItemKind::OpaqueTy,
965 ImplItemKind::Method(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 record_body(&mut self, params: HirVec<hir::Param>, value: hir::Expr) -> hir::BodyId {
1025 let body = hir::Body {
1026 generator_kind: self.generator_kind,
1031 self.bodies.insert(id, body);
1037 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Param>, hir::Expr),
1039 let prev_gen_kind = self.generator_kind.take();
1040 let (parameters, result) = f(self);
1041 let body_id = self.record_body(parameters, result);
1042 self.generator_kind = prev_gen_kind;
1046 fn lower_param(&mut self, param: &Param) -> hir::Param {
1048 attrs: self.lower_attrs(¶m.attrs),
1049 hir_id: self.lower_node_id(param.id),
1050 pat: self.lower_pat(¶m.pat),
1055 pub(super) fn lower_fn_body(
1058 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1060 self.lower_body(|this| (
1061 decl.inputs.iter().map(|x| this.lower_param(x)).collect(),
1066 fn lower_fn_body_block(&mut self, decl: &FnDecl, body: &Block) -> hir::BodyId {
1067 self.lower_fn_body(decl, |this| this.lower_block_expr(body))
1070 pub(super) fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1071 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1074 fn lower_maybe_async_body(
1080 let closure_id = match asyncness {
1081 IsAsync::Async { closure_id, .. } => closure_id,
1082 IsAsync::NotAsync => return self.lower_fn_body_block(decl, body),
1085 self.lower_body(|this| {
1086 let mut parameters: Vec<hir::Param> = Vec::new();
1087 let mut statements: Vec<hir::Stmt> = Vec::new();
1089 // Async function parameters are lowered into the closure body so that they are
1090 // captured and so that the drop order matches the equivalent non-async functions.
1094 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1100 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1102 // let __arg2 = __arg2;
1103 // let <pattern> = __arg2;
1104 // let __arg1 = __arg1;
1105 // let <pattern> = __arg1;
1106 // let __arg0 = __arg0;
1107 // let <pattern> = __arg0;
1108 // drop-temps { <body> } // see comments later in fn for details
1112 // If `<pattern>` is a simple ident, then it is lowered to a single
1113 // `let <pattern> = <pattern>;` statement as an optimization.
1115 // Note that the body is embedded in `drop-temps`; an
1116 // equivalent desugaring would be `return { <body>
1117 // };`. The key point is that we wish to drop all the
1118 // let-bound variables and temporaries created in the body
1119 // (and its tail expression!) before we drop the
1120 // parameters (c.f. rust-lang/rust#64512).
1121 for (index, parameter) in decl.inputs.iter().enumerate() {
1122 let parameter = this.lower_param(parameter);
1123 let span = parameter.pat.span;
1125 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1126 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1127 let (ident, is_simple_parameter) = match parameter.pat.kind {
1128 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
1131 // Replace the ident for bindings that aren't simple.
1132 let name = format!("__arg{}", index);
1133 let ident = Ident::from_str(&name);
1139 let desugared_span =
1140 this.mark_span_with_reason(DesugaringKind::Async, span, None);
1142 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1145 // If this is the simple case, this parameter will end up being the same as the
1146 // original parameter, but with a different pattern id.
1147 let mut stmt_attrs = ThinVec::new();
1148 stmt_attrs.extend(parameter.attrs.iter().cloned());
1149 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1150 let new_parameter = hir::Param {
1151 attrs: parameter.attrs,
1152 hir_id: parameter.hir_id,
1153 pat: new_parameter_pat,
1154 span: parameter.span,
1158 if is_simple_parameter {
1159 // If this is the simple case, then we only insert one statement that is
1160 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1161 // `HirId`s are densely assigned.
1162 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1163 let stmt = this.stmt_let_pat(
1168 hir::LocalSource::AsyncFn
1170 statements.push(stmt);
1172 // If this is not the simple case, then we construct two statements:
1175 // let __argN = __argN;
1176 // let <pat> = __argN;
1179 // The first statement moves the parameter into the closure and thus ensures
1180 // that the drop order is correct.
1182 // The second statement creates the bindings that the user wrote.
1184 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1185 // because the user may have specified a `ref mut` binding in the next
1187 let (move_pat, move_id) = this.pat_ident_binding_mode(
1188 desugared_span, ident, hir::BindingAnnotation::Mutable);
1189 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1190 let move_stmt = this.stmt_let_pat(
1195 hir::LocalSource::AsyncFn
1198 // Construct the `let <pat> = __argN;` statement. We re-use the original
1199 // parameter's pattern so that `HirId`s are densely assigned.
1200 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1201 let pattern_stmt = this.stmt_let_pat(
1204 Some(P(pattern_expr)),
1206 hir::LocalSource::AsyncFn
1209 statements.push(move_stmt);
1210 statements.push(pattern_stmt);
1213 parameters.push(new_parameter);
1216 let async_expr = this.make_async_expr(
1221 hir::AsyncGeneratorKind::Fn,
1223 // Create a block from the user's function body:
1224 let user_body = this.lower_block_expr(body);
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 // As noted above, create the final block like
1242 // let $param_pattern = $raw_param;
1244 // drop-temps { <user-body> }
1247 let body = this.block_all(
1252 this.expr_block(P(body), ThinVec::new())
1254 (HirVec::from(parameters), this.expr(body.span, async_expr, ThinVec::new()))
1258 fn lower_method_sig(
1260 generics: &Generics,
1263 impl_trait_return_allow: bool,
1264 is_async: Option<NodeId>,
1265 ) -> (hir::Generics, hir::FnSig) {
1266 let header = self.lower_fn_header(sig.header);
1267 let (generics, decl) = self.add_in_band_defs(
1270 AnonymousLifetimeMode::PassThrough,
1271 |this, idty| this.lower_fn_decl(
1273 Some((fn_def_id, idty)),
1274 impl_trait_return_allow,
1278 (generics, hir::FnSig { header, decl })
1281 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1283 unsafety: h.unsafety,
1284 asyncness: self.lower_asyncness(h.asyncness.node),
1285 constness: h.constness.node,
1286 abi: self.lower_abi(h.abi),
1290 pub(super) fn lower_abi(&mut self, abi: Abi) -> abi::Abi {
1291 abi::lookup(&abi.symbol.as_str()).unwrap_or_else(|| {
1292 self.error_on_invalid_abi(abi);
1297 fn error_on_invalid_abi(&self, abi: Abi) {
1302 "invalid ABI: found `{}`",
1305 .span_label(abi.span, "invalid ABI")
1306 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1310 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1312 IsAsync::Async { .. } => hir::IsAsync::Async,
1313 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1317 pub(super) fn lower_generics(
1319 generics: &Generics,
1320 itctx: ImplTraitContext<'_>)
1323 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1324 // FIXME: this could probably be done with less rightward drift. It also looks like two
1325 // control paths where `report_error` is called are the only paths that advance to after the
1326 // match statement, so the error reporting could probably just be moved there.
1327 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1328 for pred in &generics.where_clause.predicates {
1329 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1330 'next_bound: for bound in &bound_pred.bounds {
1331 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1332 let report_error = |this: &mut Self| {
1333 this.diagnostic().span_err(
1334 bound_pred.bounded_ty.span,
1335 "`?Trait` bounds are only permitted at the \
1336 point where a type parameter is declared",
1339 // Check if the where clause type is a plain type parameter.
1340 match bound_pred.bounded_ty.kind {
1341 TyKind::Path(None, ref path)
1342 if path.segments.len() == 1
1343 && bound_pred.bound_generic_params.is_empty() =>
1345 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
1346 .get_partial_res(bound_pred.bounded_ty.id)
1347 .map(|d| d.base_res())
1349 if let Some(node_id) =
1350 self.resolver.definitions().as_local_node_id(def_id)
1352 for param in &generics.params {
1354 GenericParamKind::Type { .. } => {
1355 if node_id == param.id {
1356 add_bounds.entry(param.id)
1358 .push(bound.clone());
1359 continue 'next_bound;
1369 _ => report_error(self),
1377 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
1378 where_clause: self.lower_where_clause(&generics.where_clause),
1379 span: generics.span,
1383 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1384 self.with_anonymous_lifetime_mode(
1385 AnonymousLifetimeMode::ReportError,
1388 predicates: wc.predicates
1390 .map(|predicate| this.lower_where_predicate(predicate))
1398 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1400 WherePredicate::BoundPredicate(WhereBoundPredicate {
1401 ref bound_generic_params,
1406 self.with_in_scope_lifetime_defs(
1407 &bound_generic_params,
1409 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1410 bound_generic_params: this.lower_generic_params(
1411 bound_generic_params,
1412 &NodeMap::default(),
1413 ImplTraitContext::disallowed(),
1415 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1418 .filter_map(|bound| match *bound {
1419 // Ignore `?Trait` bounds.
1420 // They were copied into type parameters already.
1421 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1422 _ => Some(this.lower_param_bound(
1424 ImplTraitContext::disallowed(),
1433 WherePredicate::RegionPredicate(WhereRegionPredicate {
1437 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1439 lifetime: self.lower_lifetime(lifetime),
1440 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1442 WherePredicate::EqPredicate(WhereEqPredicate {
1448 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1449 hir_id: self.lower_node_id(id),
1450 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1451 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),