1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition, ImplTraitTypeIdVisitor};
4 use rustc::arena::Arena;
8 use rustc_ast::node_id::NodeMap;
10 use rustc_ast::visit::{self, AssocCtxt, Visitor};
11 use rustc_errors::struct_span_err;
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_span::source_map::{respan, DesugaringKind};
16 use rustc_span::symbol::{kw, sym};
18 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
22 use std::collections::BTreeSet;
24 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
25 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
28 impl ItemLowerer<'_, '_, '_> {
29 fn with_trait_impl_ref(&mut self, impl_ref: &Option<TraitRef>, f: impl FnOnce(&mut Self)) {
30 let old = self.lctx.is_in_trait_impl;
31 self.lctx.is_in_trait_impl = if let &None = impl_ref { false } else { true };
33 self.lctx.is_in_trait_impl = old;
37 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
38 fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
39 let hir_id = self.lctx.lower_node_id(n);
41 self.lctx.modules.insert(
44 items: BTreeSet::new(),
45 trait_items: BTreeSet::new(),
46 impl_items: BTreeSet::new(),
50 let old = self.lctx.current_module;
51 self.lctx.current_module = hir_id;
52 visit::walk_mod(self, m);
53 self.lctx.current_module = old;
56 fn visit_item(&mut self, item: &'a Item) {
57 let mut item_hir_id = None;
58 self.lctx.with_hir_id_owner(item.id, |lctx| {
59 lctx.without_in_scope_lifetime_defs(|lctx| {
60 if let Some(hir_item) = lctx.lower_item(item) {
61 item_hir_id = Some(hir_item.hir_id);
62 lctx.insert_item(hir_item);
67 if let Some(hir_id) = item_hir_id {
68 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
69 let this = &mut ItemLowerer { lctx: this };
70 if let ItemKind::Impl { ref of_trait, .. } = item.kind {
71 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
73 visit::walk_item(this, item);
79 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
80 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
82 let hir_item = lctx.lower_trait_item(item);
83 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
84 lctx.trait_items.insert(id, hir_item);
85 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
88 let hir_item = lctx.lower_impl_item(item);
89 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
90 lctx.impl_items.insert(id, hir_item);
91 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
95 visit::walk_assoc_item(self, item, ctxt);
99 impl<'hir> LoweringContext<'_, 'hir> {
100 // Same as the method above, but accepts `hir::GenericParam`s
101 // instead of `ast::GenericParam`s.
102 // This should only be used with generics that have already had their
103 // in-band lifetimes added. In practice, this means that this function is
104 // only used when lowering a child item of a trait or impl.
105 fn with_parent_item_lifetime_defs<T>(
107 parent_hir_id: hir::HirId,
108 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
110 let old_len = self.in_scope_lifetimes.len();
112 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
113 hir::ItemKind::Impl { ref generics, .. }
114 | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..],
117 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
118 hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()),
121 self.in_scope_lifetimes.extend(lt_def_names);
125 self.in_scope_lifetimes.truncate(old_len);
129 // Clears (and restores) the `in_scope_lifetimes` field. Used when
130 // visiting nested items, which never inherit in-scope lifetimes
131 // from their surrounding environment.
132 fn without_in_scope_lifetime_defs<T>(
134 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
136 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
138 // this vector is only used when walking over impl headers,
139 // input types, and the like, and should not be non-empty in
141 assert!(self.lifetimes_to_define.is_empty());
145 assert!(self.in_scope_lifetimes.is_empty());
146 self.in_scope_lifetimes = old_in_scope_lifetimes;
151 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
156 .alloc_from_iter(m.items.iter().flat_map(|x| self.lower_item_id(x))),
160 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
161 let node_ids = match i.kind {
162 ItemKind::Use(ref use_tree) => {
163 let mut vec = smallvec![i.id];
164 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
167 ItemKind::MacroDef(..) => SmallVec::new(),
168 ItemKind::Fn(..) | ItemKind::Impl { of_trait: None, .. } => smallvec![i.id],
169 ItemKind::Static(ref ty, ..) => {
170 let mut ids = smallvec![i.id];
171 if self.sess.features_untracked().impl_trait_in_bindings {
172 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
173 visitor.visit_ty(ty);
177 ItemKind::Const(_, ref ty, ..) => {
178 let mut ids = smallvec![i.id];
179 if self.sess.features_untracked().impl_trait_in_bindings {
180 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
181 visitor.visit_ty(ty);
185 _ => smallvec![i.id],
190 .map(|node_id| hir::ItemId { id: self.allocate_hir_id_counter(node_id) })
194 fn lower_item_id_use_tree(
198 vec: &mut SmallVec<[NodeId; 1]>,
201 UseTreeKind::Nested(ref nested_vec) => {
202 for &(ref nested, id) in nested_vec {
204 self.lower_item_id_use_tree(nested, id, vec);
207 UseTreeKind::Glob => {}
208 UseTreeKind::Simple(_, id1, id2) => {
210 self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter())
218 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
219 let mut ident = i.ident;
220 let mut vis = self.lower_visibility(&i.vis, None);
221 let attrs = self.lower_attrs(&i.attrs);
223 if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind {
224 if !macro_rules || attr::contains_name(&i.attrs, sym::macro_export) {
225 let hir_id = self.lower_node_id(i.id);
226 let body = P(self.lower_mac_args(body));
227 self.exported_macros.push(hir::MacroDef {
233 ast: MacroDef { body, macro_rules },
236 self.non_exported_macro_attrs.extend(attrs.iter().cloned());
241 let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind);
243 Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span })
251 attrs: &'hir [Attribute],
252 vis: &mut hir::Visibility<'hir>,
254 ) -> hir::ItemKind<'hir> {
256 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
257 ItemKind::Use(ref use_tree) => {
258 // Start with an empty prefix.
259 let prefix = Path { segments: vec![], span: use_tree.span };
261 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
263 ItemKind::Static(ref t, m, ref e) => {
264 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
265 hir::ItemKind::Static(ty, m, body_id)
267 ItemKind::Const(_, ref t, ref e) => {
268 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
269 hir::ItemKind::Const(ty, body_id)
271 ItemKind::Fn(_, FnSig { ref decl, header }, ref generics, ref body) => {
272 let fn_def_id = self.resolver.definitions().local_def_id(id).expect_local();
273 self.with_new_scopes(|this| {
274 this.current_item = Some(ident.span);
276 // Note: we don't need to change the return type from `T` to
277 // `impl Future<Output = T>` here because lower_body
278 // only cares about the input argument patterns in the function
279 // declaration (decl), not the return types.
280 let asyncness = header.asyncness;
282 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
284 let (generics, decl) = this.add_in_band_defs(
287 AnonymousLifetimeMode::PassThrough,
289 let ret_id = asyncness.opt_return_id();
292 Some((fn_def_id.to_def_id(), idty)),
298 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
299 hir::ItemKind::Fn(sig, generics, body_id)
302 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
303 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
304 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
305 ItemKind::TyAlias(_, ref gen, _, Some(ref ty)) => match ty.kind.opaque_top_hack() {
307 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
308 let generics = self.lower_generics(gen, ImplTraitContext::disallowed());
309 hir::ItemKind::TyAlias(ty, generics)
312 let ctx = || ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc);
313 let ty = hir::OpaqueTy {
314 generics: self.lower_generics(gen, ctx()),
315 bounds: self.lower_param_bounds(bounds, ctx()),
317 origin: hir::OpaqueTyOrigin::TypeAlias,
319 hir::ItemKind::OpaqueTy(ty)
322 ItemKind::TyAlias(_, ref generics, _, None) => {
323 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
324 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
325 hir::ItemKind::TyAlias(ty, generics)
327 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
329 variants: self.arena.alloc_from_iter(
330 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
333 self.lower_generics(generics, ImplTraitContext::disallowed()),
335 ItemKind::Struct(ref struct_def, ref generics) => {
336 let struct_def = self.lower_variant_data(struct_def);
337 hir::ItemKind::Struct(
339 self.lower_generics(generics, ImplTraitContext::disallowed()),
342 ItemKind::Union(ref vdata, ref generics) => {
343 let vdata = self.lower_variant_data(vdata);
344 hir::ItemKind::Union(
346 self.lower_generics(generics, ImplTraitContext::disallowed()),
354 generics: ref ast_generics,
355 of_trait: ref trait_ref,
357 items: ref impl_items,
359 let def_id = self.resolver.definitions().local_def_id(id).expect_local();
361 // Lower the "impl header" first. This ordering is important
362 // for in-band lifetimes! Consider `'a` here:
364 // impl Foo<'a> for u32 {
365 // fn method(&'a self) { .. }
368 // Because we start by lowering the `Foo<'a> for u32`
369 // part, we will add `'a` to the list of generics on
370 // the impl. When we then encounter it later in the
371 // method, it will not be considered an in-band
372 // lifetime to be added, but rather a reference to a
374 let lowered_trait_impl_id = self.lower_node_id(id);
375 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
378 AnonymousLifetimeMode::CreateParameter,
380 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
381 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
384 if let Some(ref trait_ref) = trait_ref {
385 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
389 .push(lowered_trait_impl_id);
393 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
395 (trait_ref, lowered_ty)
400 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
401 this.arena.alloc_from_iter(
402 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
406 hir::ItemKind::Impl {
407 unsafety: self.lower_unsafety(unsafety),
409 defaultness: self.lower_defaultness(defaultness, true /* [1] */),
410 constness: self.lower_constness(constness),
414 items: new_impl_items,
417 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
418 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
421 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
422 hir::ItemKind::Trait(
424 self.lower_unsafety(unsafety),
425 self.lower_generics(generics, ImplTraitContext::disallowed()),
430 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
431 self.lower_generics(generics, ImplTraitContext::disallowed()),
432 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
434 ItemKind::MacroDef(..) | ItemKind::MacCall(..) => {
435 bug!("`TyMac` should have been expanded by now")
439 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
440 // not cause an assertion failure inside the `lower_defaultness` function.
448 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
449 let itctx = if self.sess.features_untracked().impl_trait_in_bindings {
450 ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc)
452 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
454 let ty = self.lower_ty(ty, itctx);
455 (ty, self.lower_const_body(span, body))
463 vis: &mut hir::Visibility<'hir>,
465 attrs: &'hir [Attribute],
466 ) -> hir::ItemKind<'hir> {
467 debug!("lower_use_tree(tree={:?})", tree);
468 debug!("lower_use_tree: vis = {:?}", vis);
470 let path = &tree.prefix;
471 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
474 UseTreeKind::Simple(rename, id1, id2) => {
475 *ident = tree.ident();
477 // First, apply the prefix to the path.
478 let mut path = Path { segments, span: path.span };
480 // Correctly resolve `self` imports.
481 if path.segments.len() > 1
482 && path.segments.last().unwrap().ident.name == kw::SelfLower
484 let _ = path.segments.pop();
485 if rename.is_none() {
486 *ident = path.segments.last().unwrap().ident;
490 let mut resolutions = self.expect_full_res_from_use(id);
491 // We want to return *something* from this function, so hold onto the first item
493 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
495 // Here, we are looping over namespaces, if they exist for the definition
496 // being imported. We only handle type and value namespaces because we
497 // won't be dealing with macros in the rest of the compiler.
498 // Essentially a single `use` which imports two names is desugared into
500 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
502 let mut path = path.clone();
503 for seg in &mut path.segments {
504 seg.id = self.resolver.next_node_id();
506 let span = path.span;
508 self.with_hir_id_owner(new_node_id, |this| {
509 let new_id = this.lower_node_id(new_node_id);
510 let res = this.lower_res(res);
511 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
512 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
513 let vis = this.rebuild_vis(&vis);
515 this.insert_item(hir::Item {
526 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
527 hir::ItemKind::Use(path, hir::UseKind::Single)
529 UseTreeKind::Glob => {
531 self.lower_path(id, &Path { segments, span: path.span }, ParamMode::Explicit);
532 hir::ItemKind::Use(path, hir::UseKind::Glob)
534 UseTreeKind::Nested(ref trees) => {
535 // Nested imports are desugared into simple imports.
536 // So, if we start with
539 // pub(x) use foo::{a, b};
542 // we will create three items:
545 // pub(x) use foo::a;
546 // pub(x) use foo::b;
547 // pub(x) use foo::{}; // <-- this is called the `ListStem`
550 // The first two are produced by recursively invoking
551 // `lower_use_tree` (and indeed there may be things
552 // like `use foo::{a::{b, c}}` and so forth). They
553 // wind up being directly added to
554 // `self.items`. However, the structure of this
555 // function also requires us to return one item, and
556 // for that we return the `{}` import (called the
559 let prefix = Path { segments, span: prefix.span.to(path.span) };
561 // Add all the nested `PathListItem`s to the HIR.
562 for &(ref use_tree, id) in trees {
563 let new_hir_id = self.lower_node_id(id);
565 let mut prefix = prefix.clone();
567 // Give the segments new node-ids since they are being cloned.
568 for seg in &mut prefix.segments {
569 seg.id = self.resolver.next_node_id();
572 // Each `use` import is an item and thus are owners of the
573 // names in the path. Up to this point the nested import is
574 // the current owner, since we want each desugared import to
575 // own its own names, we have to adjust the owner before
576 // lowering the rest of the import.
577 self.with_hir_id_owner(id, |this| {
578 let mut vis = this.rebuild_vis(&vis);
579 let mut ident = *ident;
582 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
584 this.insert_item(hir::Item {
595 // Subtle and a bit hacky: we lower the privacy level
596 // of the list stem to "private" most of the time, but
597 // not for "restricted" paths. The key thing is that
598 // we don't want it to stay as `pub` (with no caveats)
599 // because that affects rustdoc and also the lints
600 // about `pub` items. But we can't *always* make it
601 // private -- particularly not for restricted paths --
602 // because it contains node-ids that would then be
603 // unused, failing the check that HirIds are "densely
606 hir::VisibilityKind::Public
607 | hir::VisibilityKind::Crate(_)
608 | hir::VisibilityKind::Inherited => {
609 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
611 hir::VisibilityKind::Restricted { .. } => {
612 // Do nothing here, as described in the comment on the match.
616 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
617 let res = self.lower_res(res);
618 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
619 hir::ItemKind::Use(path, hir::UseKind::ListStem)
624 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
625 /// many times in the HIR tree; for each occurrence, we need to assign distinct
626 /// `NodeId`s. (See, e.g., #56128.)
627 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
628 debug!("rebuild_use_path(path = {:?})", path);
630 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
632 hir_id: seg.hir_id.map(|_| self.next_id()),
635 infer_args: seg.infer_args,
637 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
640 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
641 let vis_kind = match vis.node {
642 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
643 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
644 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
645 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
646 hir::VisibilityKind::Restricted {
647 path: self.rebuild_use_path(path),
648 hir_id: self.next_id(),
652 respan(vis.span, vis_kind)
655 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
656 let def_id = self.resolver.definitions().local_def_id(i.id).expect_local();
658 hir_id: self.lower_node_id(i.id),
660 attrs: self.lower_attrs(&i.attrs),
662 ForeignItemKind::Fn(_, ref sig, ref generics, _) => {
663 let fdec = &sig.decl;
664 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
667 AnonymousLifetimeMode::PassThrough,
670 // Disallow `impl Trait` in foreign items.
671 this.lower_fn_decl(fdec, None, false, None),
672 this.lower_fn_params_to_names(fdec),
677 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
679 ForeignItemKind::Static(ref t, m, _) => {
680 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
681 hir::ForeignItemKind::Static(ty, m)
683 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
684 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
686 vis: self.lower_visibility(&i.vis, None),
691 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'hir> {
693 abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
694 items: self.arena.alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item(x))),
698 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
699 self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
702 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
704 attrs: self.lower_attrs(&v.attrs),
705 data: self.lower_variant_data(&v.data),
706 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
707 id: self.lower_node_id(v.id),
713 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> {
715 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
717 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
720 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
722 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
723 self.lower_node_id(id),
725 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
729 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'hir> {
730 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
731 let t = self.lower_path_ty(
735 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
736 ImplTraitContext::disallowed(),
740 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
744 hir_id: self.lower_node_id(f.id),
745 ident: match f.ident {
746 Some(ident) => ident,
747 // FIXME(jseyfried): positional field hygiene.
748 None => Ident::new(sym::integer(index), f.span),
750 vis: self.lower_visibility(&f.vis, None),
752 attrs: self.lower_attrs(&f.attrs),
756 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
757 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id).expect_local();
759 let (generics, kind) = match i.kind {
760 AssocItemKind::Const(_, ref ty, ref default) => {
761 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
762 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
763 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
765 AssocItemKind::Fn(_, ref sig, ref generics, None) => {
766 let names = self.lower_fn_params_to_names(&sig.decl);
767 let (generics, sig) =
768 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
769 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
771 AssocItemKind::Fn(_, ref sig, ref generics, Some(ref body)) => {
772 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
773 let (generics, sig) =
774 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
775 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
777 AssocItemKind::TyAlias(_, ref generics, ref bounds, ref default) => {
778 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
779 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
780 let kind = hir::TraitItemKind::Type(
781 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
787 AssocItemKind::MacCall(..) => bug!("macro item shouldn't exist at this point"),
791 hir_id: self.lower_node_id(i.id),
793 attrs: self.lower_attrs(&i.attrs),
800 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
801 let (kind, has_default) = match &i.kind {
802 AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
803 AssocItemKind::TyAlias(_, _, _, default) => {
804 (hir::AssocItemKind::Type, default.is_some())
806 AssocItemKind::Fn(_, sig, _, default) => {
807 (hir::AssocItemKind::Method { has_self: sig.decl.has_self() }, default.is_some())
809 AssocItemKind::MacCall(..) => unimplemented!(),
811 let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id) };
812 let defaultness = hir::Defaultness::Default { has_value: has_default };
813 hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind }
816 /// Construct `ExprKind::Err` for the given `span`.
817 fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
818 self.expr(span, hir::ExprKind::Err, AttrVec::new())
821 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
822 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id).expect_local();
824 let (generics, kind) = match &i.kind {
825 AssocItemKind::Const(_, ty, expr) => {
826 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
828 hir::Generics::empty(),
829 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
832 AssocItemKind::Fn(_, sig, generics, body) => {
833 self.current_item = Some(i.span);
834 let asyncness = sig.header.asyncness;
836 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
837 let impl_trait_return_allow = !self.is_in_trait_impl;
838 let (generics, sig) = self.lower_method_sig(
842 impl_trait_return_allow,
843 asyncness.opt_return_id(),
846 (generics, hir::ImplItemKind::Fn(sig, body_id))
848 AssocItemKind::TyAlias(_, generics, _, ty) => {
849 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
850 let kind = match ty {
852 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
853 hir::ImplItemKind::TyAlias(ty)
855 Some(ty) => match ty.kind.opaque_top_hack() {
857 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
858 hir::ImplItemKind::TyAlias(ty)
861 let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
862 hir::ImplItemKind::OpaqueTy(bs)
868 AssocItemKind::MacCall(..) => bug!("`TyMac` should have been expanded by now"),
872 hir_id: self.lower_node_id(i.id),
874 attrs: self.lower_attrs(&i.attrs),
876 vis: self.lower_visibility(&i.vis, None),
877 defaultness: self.lower_defaultness(i.kind.defaultness(), true /* [1] */),
882 // [1] since `default impl` is not yet implemented, this is always true in impls
885 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
887 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
890 vis: self.lower_visibility(&i.vis, Some(i.id)),
891 defaultness: self.lower_defaultness(i.kind.defaultness(), true /* [1] */),
892 kind: match &i.kind {
893 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
894 AssocItemKind::TyAlias(.., ty) => {
895 match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
896 None => hir::AssocItemKind::Type,
897 Some(_) => hir::AssocItemKind::OpaqueTy,
900 AssocItemKind::Fn(_, sig, ..) => {
901 hir::AssocItemKind::Method { has_self: sig.decl.has_self() }
903 AssocItemKind::MacCall(..) => unimplemented!(),
907 // [1] since `default impl` is not yet implemented, this is always true in impls
910 /// If an `explicit_owner` is given, this method allocates the `HirId` in
911 /// the address space of that item instead of the item currently being
912 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
913 /// lower a `Visibility` value although we haven't lowered the owning
914 /// `ImplItem` in question yet.
918 explicit_owner: Option<NodeId>,
919 ) -> hir::Visibility<'hir> {
920 let node = match v.node {
921 VisibilityKind::Public => hir::VisibilityKind::Public,
922 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
923 VisibilityKind::Restricted { ref path, id } => {
924 debug!("lower_visibility: restricted path id = {:?}", id);
925 let lowered_id = if let Some(owner) = explicit_owner {
926 self.lower_node_id_with_owner(id, owner)
928 self.lower_node_id(id)
930 let res = self.expect_full_res(id);
931 let res = self.lower_res(res);
932 hir::VisibilityKind::Restricted {
933 path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
937 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
942 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
944 Defaultness::Default(_) => hir::Defaultness::Default { has_value },
945 Defaultness::Final => {
947 hir::Defaultness::Final
954 params: &'hir [hir::Param<'hir>],
955 value: hir::Expr<'hir>,
957 let body = hir::Body { generator_kind: self.generator_kind, params, value };
959 self.bodies.insert(id, body);
965 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
967 let prev_gen_kind = self.generator_kind.take();
968 let (parameters, result) = f(self);
969 let body_id = self.record_body(parameters, result);
970 self.generator_kind = prev_gen_kind;
974 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
976 attrs: self.lower_attrs(¶m.attrs),
977 hir_id: self.lower_node_id(param.id),
978 pat: self.lower_pat(¶m.pat),
983 pub(super) fn lower_fn_body(
986 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
988 self.lower_body(|this| {
990 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
996 fn lower_fn_body_block(
1000 body: Option<&Block>,
1002 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1005 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1007 Some(block) => self.lower_block_expr(block),
1008 None => self.expr_err(span),
1012 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1013 self.lower_body(|this| {
1017 Some(expr) => this.lower_expr_mut(expr),
1018 None => this.expr_err(span),
1024 fn lower_maybe_async_body(
1029 body: Option<&Block>,
1031 let closure_id = match asyncness {
1032 Async::Yes { closure_id, .. } => closure_id,
1033 Async::No => return self.lower_fn_body_block(span, decl, body),
1036 self.lower_body(|this| {
1037 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1038 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1040 // Async function parameters are lowered into the closure body so that they are
1041 // captured and so that the drop order matches the equivalent non-async functions.
1045 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1051 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1053 // let __arg2 = __arg2;
1054 // let <pattern> = __arg2;
1055 // let __arg1 = __arg1;
1056 // let <pattern> = __arg1;
1057 // let __arg0 = __arg0;
1058 // let <pattern> = __arg0;
1059 // drop-temps { <body> } // see comments later in fn for details
1063 // If `<pattern>` is a simple ident, then it is lowered to a single
1064 // `let <pattern> = <pattern>;` statement as an optimization.
1066 // Note that the body is embedded in `drop-temps`; an
1067 // equivalent desugaring would be `return { <body>
1068 // };`. The key point is that we wish to drop all the
1069 // let-bound variables and temporaries created in the body
1070 // (and its tail expression!) before we drop the
1071 // parameters (c.f. rust-lang/rust#64512).
1072 for (index, parameter) in decl.inputs.iter().enumerate() {
1073 let parameter = this.lower_param(parameter);
1074 let span = parameter.pat.span;
1076 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1077 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1078 let (ident, is_simple_parameter) = match parameter.pat.kind {
1079 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) => {
1083 // Replace the ident for bindings that aren't simple.
1084 let name = format!("__arg{}", index);
1085 let ident = Ident::from_str(&name);
1091 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1093 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1096 // If this is the simple case, this parameter will end up being the same as the
1097 // original parameter, but with a different pattern id.
1098 let mut stmt_attrs = AttrVec::new();
1099 stmt_attrs.extend(parameter.attrs.iter().cloned());
1100 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1101 let new_parameter = hir::Param {
1102 attrs: parameter.attrs,
1103 hir_id: parameter.hir_id,
1104 pat: new_parameter_pat,
1105 span: parameter.span,
1108 if is_simple_parameter {
1109 // If this is the simple case, then we only insert one statement that is
1110 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1111 // `HirId`s are densely assigned.
1112 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1113 let stmt = this.stmt_let_pat(
1118 hir::LocalSource::AsyncFn,
1120 statements.push(stmt);
1122 // If this is not the simple case, then we construct two statements:
1125 // let __argN = __argN;
1126 // let <pat> = __argN;
1129 // The first statement moves the parameter into the closure and thus ensures
1130 // that the drop order is correct.
1132 // The second statement creates the bindings that the user wrote.
1134 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1135 // because the user may have specified a `ref mut` binding in the next
1137 let (move_pat, move_id) = this.pat_ident_binding_mode(
1140 hir::BindingAnnotation::Mutable,
1142 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1143 let move_stmt = this.stmt_let_pat(
1148 hir::LocalSource::AsyncFn,
1151 // Construct the `let <pat> = __argN;` statement. We re-use the original
1152 // parameter's pattern so that `HirId`s are densely assigned.
1153 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1154 let pattern_stmt = this.stmt_let_pat(
1159 hir::LocalSource::AsyncFn,
1162 statements.push(move_stmt);
1163 statements.push(pattern_stmt);
1166 parameters.push(new_parameter);
1169 let body_span = body.map_or(span, |b| b.span);
1170 let async_expr = this.make_async_expr(
1175 hir::AsyncGeneratorKind::Fn,
1177 // Create a block from the user's function body:
1178 let user_body = this.lower_block_expr_opt(body_span, body);
1180 // Transform into `drop-temps { <user-body> }`, an expression:
1181 let desugared_span =
1182 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1183 let user_body = this.expr_drop_temps(
1185 this.arena.alloc(user_body),
1189 // As noted above, create the final block like
1193 // let $param_pattern = $raw_param;
1195 // drop-temps { <user-body> }
1198 let body = this.block_all(
1200 this.arena.alloc_from_iter(statements),
1204 this.expr_block(body, AttrVec::new())
1209 this.arena.alloc_from_iter(parameters),
1210 this.expr(body_span, async_expr, AttrVec::new()),
1215 fn lower_method_sig(
1217 generics: &Generics,
1219 fn_def_id: LocalDefId,
1220 impl_trait_return_allow: bool,
1221 is_async: Option<NodeId>,
1222 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1223 let header = self.lower_fn_header(sig.header);
1224 let (generics, decl) = self.add_in_band_defs(
1227 AnonymousLifetimeMode::PassThrough,
1231 Some((fn_def_id.to_def_id(), idty)),
1232 impl_trait_return_allow,
1237 (generics, hir::FnSig { header, decl })
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),
1244 constness: self.lower_constness(h.constness),
1245 abi: self.lower_extern(h.ext),
1249 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1250 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1251 self.error_on_invalid_abi(abi);
1256 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1258 Extern::None => abi::Abi::Rust,
1259 Extern::Implicit => abi::Abi::C,
1260 Extern::Explicit(abi) => self.lower_abi(abi),
1264 fn error_on_invalid_abi(&self, abi: StrLit) {
1265 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1266 .span_label(abi.span, "invalid ABI")
1267 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1271 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1273 Async::Yes { .. } => hir::IsAsync::Async,
1274 Async::No => hir::IsAsync::NotAsync,
1278 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1280 Const::Yes(_) => hir::Constness::Const,
1281 Const::No => hir::Constness::NotConst,
1285 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1287 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1288 Unsafe::No => hir::Unsafety::Normal,
1292 pub(super) fn lower_generics_mut(
1294 generics: &Generics,
1295 itctx: ImplTraitContext<'_, 'hir>,
1296 ) -> GenericsCtor<'hir> {
1297 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1298 // FIXME: this could probably be done with less rightward drift. It also looks like two
1299 // control paths where `report_error` is called are the only paths that advance to after the
1300 // match statement, so the error reporting could probably just be moved there.
1301 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1302 for pred in &generics.where_clause.predicates {
1303 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1304 'next_bound: for bound in &bound_pred.bounds {
1305 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1306 let report_error = |this: &mut Self| {
1307 this.diagnostic().span_err(
1308 bound_pred.bounded_ty.span,
1309 "`?Trait` bounds are only permitted at the \
1310 point where a type parameter is declared",
1313 // Check if the where clause type is a plain type parameter.
1314 match bound_pred.bounded_ty.kind {
1315 TyKind::Path(None, ref path)
1316 if path.segments.len() == 1
1317 && bound_pred.bound_generic_params.is_empty() =>
1319 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1321 .get_partial_res(bound_pred.bounded_ty.id)
1322 .map(|d| d.base_res())
1324 if let Some(node_id) =
1325 self.resolver.definitions().as_local_node_id(def_id)
1327 for param in &generics.params {
1329 GenericParamKind::Type { .. } => {
1330 if node_id == param.id {
1334 .push(bound.clone());
1335 continue 'next_bound;
1345 _ => report_error(self),
1353 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1354 where_clause: self.lower_where_clause(&generics.where_clause),
1355 span: generics.span,
1359 pub(super) fn lower_generics(
1361 generics: &Generics,
1362 itctx: ImplTraitContext<'_, 'hir>,
1363 ) -> hir::Generics<'hir> {
1364 let generics_ctor = self.lower_generics_mut(generics, itctx);
1365 generics_ctor.into_generics(self.arena)
1368 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1369 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1371 predicates: this.arena.alloc_from_iter(
1372 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1379 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1381 WherePredicate::BoundPredicate(WhereBoundPredicate {
1382 ref bound_generic_params,
1387 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1388 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1389 bound_generic_params: this.lower_generic_params(
1390 bound_generic_params,
1391 &NodeMap::default(),
1392 ImplTraitContext::disallowed(),
1394 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1395 bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1397 // Ignore `?Trait` bounds.
1398 // They were copied into type parameters already.
1399 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1401 this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1409 WherePredicate::RegionPredicate(WhereRegionPredicate {
1413 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1415 lifetime: self.lower_lifetime(lifetime),
1416 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1418 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1419 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1420 hir_id: self.lower_node_id(id),
1421 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1422 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1430 /// Helper struct for delayed construction of Generics.
1431 pub(super) struct GenericsCtor<'hir> {
1432 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1433 where_clause: hir::WhereClause<'hir>,
1437 impl<'hir> GenericsCtor<'hir> {
1438 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1440 params: arena.alloc_from_iter(self.params),
1441 where_clause: self.where_clause,