1 use super::AnonymousLifetimeMode;
2 use super::ImplTraitContext;
3 use super::ImplTraitPosition;
4 use super::ImplTraitTypeIdVisitor;
5 use super::LoweringContext;
8 use crate::arena::Arena;
10 use crate::hir::def::{DefKind, Res};
11 use crate::hir::def_id::DefId;
12 use crate::util::nodemap::NodeMap;
14 use rustc_target::spec::abi;
16 use smallvec::SmallVec;
17 use std::collections::BTreeSet;
20 use syntax::source_map::{respan, DesugaringKind};
21 use syntax::symbol::{kw, sym};
22 use syntax::visit::{self, Visitor};
25 use rustc_error_codes::*;
27 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
28 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
31 impl<'a, 'lowering, 'hir> ItemLowerer<'a, 'lowering, 'hir> {
32 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
36 let old = self.lctx.is_in_trait_impl;
37 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref { false } else { true };
39 self.lctx.is_in_trait_impl = old;
43 impl<'a, 'lowering, 'hir> Visitor<'a> for ItemLowerer<'a, 'lowering, 'hir> {
44 fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
45 let hir_id = self.lctx.lower_node_id(n);
47 self.lctx.modules.insert(
50 items: BTreeSet::new(),
51 trait_items: BTreeSet::new(),
52 impl_items: BTreeSet::new(),
56 let old = self.lctx.current_module;
57 self.lctx.current_module = hir_id;
58 visit::walk_mod(self, m);
59 self.lctx.current_module = old;
62 fn visit_item(&mut self, item: &'a Item) {
63 let mut item_hir_id = None;
64 self.lctx.with_hir_id_owner(item.id, |lctx| {
65 lctx.without_in_scope_lifetime_defs(|lctx| {
66 if let Some(hir_item) = lctx.lower_item(item) {
67 item_hir_id = Some(hir_item.hir_id);
68 lctx.insert_item(hir_item);
73 if let Some(hir_id) = item_hir_id {
74 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
75 let this = &mut ItemLowerer { lctx: this };
76 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.kind {
77 this.with_trait_impl_ref(opt_trait_ref, |this| visit::walk_item(this, item));
79 visit::walk_item(this, item);
85 fn visit_trait_item(&mut self, item: &'a AssocItem) {
86 self.lctx.with_hir_id_owner(item.id, |lctx| {
87 let hir_item = lctx.lower_trait_item(item);
88 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
89 lctx.trait_items.insert(id, hir_item);
90 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
93 visit::walk_trait_item(self, item);
96 fn visit_impl_item(&mut self, item: &'a AssocItem) {
97 self.lctx.with_hir_id_owner(item.id, |lctx| {
98 let hir_item = lctx.lower_impl_item(item);
99 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
100 lctx.impl_items.insert(id, hir_item);
101 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
103 visit::walk_impl_item(self, item);
107 impl<'hir> LoweringContext<'_, 'hir> {
108 // Same as the method above, but accepts `hir::GenericParam`s
109 // instead of `ast::GenericParam`s.
110 // This should only be used with generics that have already had their
111 // in-band lifetimes added. In practice, this means that this function is
112 // only used when lowering a child item of a trait or impl.
113 fn with_parent_item_lifetime_defs<T>(
115 parent_hir_id: hir::HirId,
116 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
118 let old_len = self.in_scope_lifetimes.len();
120 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
121 hir::ItemKind::Impl(_, _, _, ref generics, ..)
122 | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..],
125 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
126 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
129 self.in_scope_lifetimes.extend(lt_def_names);
133 self.in_scope_lifetimes.truncate(old_len);
137 // Clears (and restores) the `in_scope_lifetimes` field. Used when
138 // visiting nested items, which never inherit in-scope lifetimes
139 // from their surrounding environment.
140 fn without_in_scope_lifetime_defs<T>(
142 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
144 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
146 // this vector is only used when walking over impl headers,
147 // input types, and the like, and should not be non-empty in
149 assert!(self.lifetimes_to_define.is_empty());
153 assert!(self.in_scope_lifetimes.is_empty());
154 self.in_scope_lifetimes = old_in_scope_lifetimes;
159 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
164 .alloc_from_iter(m.items.iter().flat_map(|x| self.lower_item_id(x))),
168 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
169 let node_ids = match i.kind {
170 ItemKind::Use(ref use_tree) => {
171 let mut vec = smallvec![i.id];
172 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
175 ItemKind::MacroDef(..) => SmallVec::new(),
176 ItemKind::Fn(..) | ItemKind::Impl(.., None, _, _) => smallvec![i.id],
177 ItemKind::Static(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 ItemKind::Const(ref ty, ..) => {
186 let mut ids = smallvec![i.id];
187 if self.sess.features_untracked().impl_trait_in_bindings {
188 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
189 visitor.visit_ty(ty);
193 _ => smallvec![i.id],
198 .map(|node_id| hir::ItemId { id: self.allocate_hir_id_counter(node_id) })
202 fn lower_item_id_use_tree(
206 vec: &mut SmallVec<[NodeId; 1]>,
209 UseTreeKind::Nested(ref nested_vec) => {
210 for &(ref nested, id) in nested_vec {
212 self.lower_item_id_use_tree(nested, id, vec);
215 UseTreeKind::Glob => {}
216 UseTreeKind::Simple(_, id1, id2) => {
218 self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter())
226 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
227 let mut ident = i.ident;
228 let mut vis = self.lower_visibility(&i.vis, None);
229 let attrs = self.lower_attrs_arena(&i.attrs);
231 if let ItemKind::MacroDef(ref def) = i.kind {
232 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
233 let body = self.lower_token_stream(def.body.inner_tokens());
234 let hir_id = self.lower_node_id(i.id);
235 self.exported_macros.push(hir::MacroDef {
245 self.non_exported_macro_attrs.extend(attrs.iter().cloned());
250 let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind);
252 Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span })
260 attrs: &'hir [Attribute],
261 vis: &mut hir::Visibility<'hir>,
263 ) -> hir::ItemKind<'hir> {
265 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
266 ItemKind::Use(ref use_tree) => {
267 // Start with an empty prefix.
268 let prefix = Path { segments: vec![], span: use_tree.span };
270 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
272 ItemKind::Static(ref t, m, ref e) => {
273 let ty = self.lower_ty(
275 if self.sess.features_untracked().impl_trait_in_bindings {
276 ImplTraitContext::OpaqueTy(None)
278 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
281 hir::ItemKind::Static(ty, m, self.lower_const_body(span, Some(e)))
283 ItemKind::Const(ref t, ref e) => {
284 let ty = self.lower_ty(
286 if self.sess.features_untracked().impl_trait_in_bindings {
287 ImplTraitContext::OpaqueTy(None)
289 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
292 hir::ItemKind::Const(ty, self.lower_const_body(span, Some(e)))
294 ItemKind::Fn(FnSig { ref decl, header }, ref generics, ref body) => {
295 let fn_def_id = self.resolver.definitions().local_def_id(id);
296 self.with_new_scopes(|this| {
297 this.current_item = Some(ident.span);
299 // Note: we don't need to change the return type from `T` to
300 // `impl Future<Output = T>` here because lower_body
301 // only cares about the input argument patterns in the function
302 // declaration (decl), not the return types.
304 this.lower_maybe_async_body(span, &decl, header.asyncness.node, Some(body));
306 let (generics, decl) = this.add_in_band_defs(
309 AnonymousLifetimeMode::PassThrough,
313 Some((fn_def_id, idty)),
315 header.asyncness.node.opt_return_id(),
319 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
320 hir::ItemKind::Fn(sig, generics, body_id)
323 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
324 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
325 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
326 ItemKind::TyAlias(ref ty, ref generics) => match ty.kind.opaque_top_hack() {
328 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
329 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
330 hir::ItemKind::TyAlias(ty, generics)
333 let ty = hir::OpaqueTy {
334 generics: self.lower_generics(generics, ImplTraitContext::OpaqueTy(None)),
335 bounds: self.lower_param_bounds(bounds, ImplTraitContext::OpaqueTy(None)),
337 origin: hir::OpaqueTyOrigin::TypeAlias,
339 hir::ItemKind::OpaqueTy(ty)
342 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
344 variants: self.arena.alloc_from_iter(
345 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
348 self.lower_generics(generics, ImplTraitContext::disallowed()),
350 ItemKind::Struct(ref struct_def, ref generics) => {
351 let struct_def = self.lower_variant_data(struct_def);
352 hir::ItemKind::Struct(
354 self.lower_generics(generics, ImplTraitContext::disallowed()),
357 ItemKind::Union(ref vdata, ref generics) => {
358 let vdata = self.lower_variant_data(vdata);
359 hir::ItemKind::Union(
361 self.lower_generics(generics, ImplTraitContext::disallowed()),
373 let def_id = self.resolver.definitions().local_def_id(id);
375 // Lower the "impl header" first. This ordering is important
376 // for in-band lifetimes! Consider `'a` here:
378 // impl Foo<'a> for u32 {
379 // fn method(&'a self) { .. }
382 // Because we start by lowering the `Foo<'a> for u32`
383 // part, we will add `'a` to the list of generics on
384 // the impl. When we then encounter it later in the
385 // method, it will not be considered an in-band
386 // lifetime to be added, but rather a reference to a
388 let lowered_trait_impl_id = self.lower_node_id(id);
389 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
392 AnonymousLifetimeMode::CreateParameter,
394 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
395 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
398 if let Some(ref trait_ref) = trait_ref {
399 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
403 .push(lowered_trait_impl_id);
407 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
409 (trait_ref, lowered_ty)
414 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
415 this.arena.alloc_from_iter(
416 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
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 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
435 hir::ItemKind::Trait(
438 self.lower_generics(generics, ImplTraitContext::disallowed()),
443 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
444 self.lower_generics(generics, ImplTraitContext::disallowed()),
445 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
447 ItemKind::MacroDef(..) | ItemKind::Mac(..) => {
448 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<'hir>,
463 attrs: &'hir [Attribute],
464 ) -> hir::ItemKind<'hir> {
465 debug!("lower_use_tree(tree={:?})", tree);
466 debug!("lower_use_tree: vis = {:?}", vis);
468 let path = &tree.prefix;
469 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
472 UseTreeKind::Simple(rename, id1, id2) => {
473 *ident = tree.ident();
475 // First, apply the prefix to the path.
476 let mut path = Path { segments, span: path.span };
478 // Correctly resolve `self` imports.
479 if path.segments.len() > 1
480 && path.segments.last().unwrap().ident.name == kw::SelfLower
482 let _ = path.segments.pop();
483 if rename.is_none() {
484 *ident = path.segments.last().unwrap().ident;
488 let mut resolutions = self.expect_full_res_from_use(id);
489 // We want to return *something* from this function, so hold onto the first item
491 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
493 // Here, we are looping over namespaces, if they exist for the definition
494 // being imported. We only handle type and value namespaces because we
495 // won't be dealing with macros in the rest of the compiler.
496 // Essentially a single `use` which imports two names is desugared into
498 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
500 let mut path = path.clone();
501 for seg in &mut path.segments {
502 seg.id = self.resolver.next_node_id();
504 let span = path.span;
506 self.with_hir_id_owner(new_node_id, |this| {
507 let new_id = this.lower_node_id(new_node_id);
508 let res = this.lower_res(res);
509 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
510 let kind = hir::ItemKind::Use(this.arena.alloc(path), hir::UseKind::Single);
511 let vis = this.rebuild_vis(&vis);
513 this.insert_item(hir::Item {
524 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
525 let path = self.arena.alloc(path);
526 hir::ItemKind::Use(path, hir::UseKind::Single)
528 UseTreeKind::Glob => {
529 let path = self.arena.alloc(self.lower_path(
531 &Path { segments, span: path.span },
534 hir::ItemKind::Use(path, hir::UseKind::Glob)
536 UseTreeKind::Nested(ref trees) => {
537 // Nested imports are desugared into simple imports.
538 // So, if we start with
541 // pub(x) use foo::{a, b};
544 // we will create three items:
547 // pub(x) use foo::a;
548 // pub(x) use foo::b;
549 // pub(x) use foo::{}; // <-- this is called the `ListStem`
552 // The first two are produced by recursively invoking
553 // `lower_use_tree` (and indeed there may be things
554 // like `use foo::{a::{b, c}}` and so forth). They
555 // wind up being directly added to
556 // `self.items`. However, the structure of this
557 // function also requires us to return one item, and
558 // for that we return the `{}` import (called the
561 let prefix = Path { segments, span: prefix.span.to(path.span) };
563 // Add all the nested `PathListItem`s to the HIR.
564 for &(ref use_tree, id) in trees {
565 let new_hir_id = self.lower_node_id(id);
567 let mut prefix = prefix.clone();
569 // Give the segments new node-ids since they are being cloned.
570 for seg in &mut prefix.segments {
571 seg.id = self.resolver.next_node_id();
574 // Each `use` import is an item and thus are owners of the
575 // names in the path. Up to this point the nested import is
576 // the current owner, since we want each desugared import to
577 // own its own names, we have to adjust the owner before
578 // lowering the rest of the import.
579 self.with_hir_id_owner(id, |this| {
580 let mut vis = this.rebuild_vis(&vis);
581 let mut ident = *ident;
584 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
586 this.insert_item(hir::Item {
597 // Subtle and a bit hacky: we lower the privacy level
598 // of the list stem to "private" most of the time, but
599 // not for "restricted" paths. The key thing is that
600 // we don't want it to stay as `pub` (with no caveats)
601 // because that affects rustdoc and also the lints
602 // about `pub` items. But we can't *always* make it
603 // private -- particularly not for restricted paths --
604 // because it contains node-ids that would then be
605 // unused, failing the check that HirIds are "densely
608 hir::VisibilityKind::Public
609 | hir::VisibilityKind::Crate(_)
610 | hir::VisibilityKind::Inherited => {
611 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
613 hir::VisibilityKind::Restricted { .. } => {
614 // Do nothing here, as described in the comment on the match.
618 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
619 let res = self.lower_res(res);
620 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
621 let path = self.arena.alloc(path);
622 hir::ItemKind::Use(path, hir::UseKind::ListStem)
627 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
628 /// many times in the HIR tree; for each occurrence, we need to assign distinct
629 /// `NodeId`s. (See, e.g., #56128.)
630 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> hir::Path<'hir> {
631 debug!("rebuild_use_path(path = {:?})", path);
633 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
635 hir_id: seg.hir_id.map(|_| self.next_id()),
638 infer_args: seg.infer_args,
640 hir::Path { span: path.span, res: path.res, segments }
643 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
644 let vis_kind = match vis.node {
645 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
646 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
647 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
648 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
649 hir::VisibilityKind::Restricted {
650 path: self.arena.alloc(self.rebuild_use_path(path)),
651 hir_id: self.next_id(),
655 respan(vis.span, vis_kind)
658 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
659 let def_id = self.resolver.definitions().local_def_id(i.id);
661 hir_id: self.lower_node_id(i.id),
663 attrs: self.lower_attrs_arena(&i.attrs),
665 ForeignItemKind::Fn(ref fdec, ref generics) => {
666 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
669 AnonymousLifetimeMode::PassThrough,
672 // Disallow `impl Trait` in foreign items.
673 this.lower_fn_decl(fdec, None, false, None),
674 this.lower_fn_params_to_names(fdec),
678 let fn_args = self.arena.alloc_from_iter(fn_args.into_iter());
680 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
682 ForeignItemKind::Static(ref t, m) => {
683 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
684 hir::ForeignItemKind::Static(ty, m)
686 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
687 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
689 vis: self.lower_visibility(&i.vis, None),
694 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'hir> {
696 abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
697 items: self.arena.alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item(x))),
701 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
702 self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
705 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
707 attrs: self.lower_attrs_arena(&v.attrs),
708 data: self.lower_variant_data(&v.data),
709 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
710 id: self.lower_node_id(v.id),
716 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> {
718 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
720 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
723 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
725 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
726 self.lower_node_id(id),
728 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
732 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'hir> {
733 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
734 let t = self.lower_path_ty(
738 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
739 ImplTraitContext::disallowed(),
743 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
747 hir_id: self.lower_node_id(f.id),
748 ident: match f.ident {
749 Some(ident) => ident,
750 // FIXME(jseyfried): positional field hygiene.
751 None => Ident::new(sym::integer(index), f.span),
753 vis: self.lower_visibility(&f.vis, None),
755 attrs: self.lower_attrs_arena(&f.attrs),
759 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
760 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
762 let (generics, kind) = match i.kind {
763 AssocItemKind::Const(ref ty, ref default) => {
764 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
765 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
768 hir::TraitItemKind::Const(
770 default.as_ref().map(|x| self.lower_const_body(i.span, Some(x))),
774 AssocItemKind::Fn(ref sig, None) => {
775 let names = self.lower_fn_params_to_names(&sig.decl);
776 let names: &[Ident] = self.arena.alloc_from_iter(names.into_iter());
777 let (generics, sig) =
778 self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
779 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
781 AssocItemKind::Fn(ref sig, Some(ref body)) => {
782 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
783 let (generics, sig) =
784 self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
785 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
787 AssocItemKind::TyAlias(ref bounds, ref default) => {
788 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
789 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
790 let kind = hir::TraitItemKind::Type(
791 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
797 AssocItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
801 hir_id: self.lower_node_id(i.id),
803 attrs: self.lower_attrs_arena(&i.attrs),
810 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
811 let (kind, has_default) = match i.kind {
812 AssocItemKind::Const(_, ref default) => (hir::AssocItemKind::Const, default.is_some()),
813 AssocItemKind::TyAlias(_, ref default) => (hir::AssocItemKind::Type, default.is_some()),
814 AssocItemKind::Fn(ref sig, ref default) => {
815 (hir::AssocItemKind::Method { has_self: sig.decl.has_self() }, default.is_some())
817 AssocItemKind::Macro(..) => unimplemented!(),
820 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
823 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
828 /// Construct `ExprKind::Err` for the given `span`.
829 fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
830 self.expr(span, hir::ExprKind::Err, AttrVec::new())
833 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
834 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
836 let (generics, kind) = match i.kind {
837 AssocItemKind::Const(ref ty, ref expr) => {
838 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
839 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
842 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
845 AssocItemKind::Fn(ref sig, ref body) => {
846 self.current_item = Some(i.span);
847 let body_id = self.lower_maybe_async_body(
850 sig.header.asyncness.node,
853 let impl_trait_return_allow = !self.is_in_trait_impl;
854 let (generics, sig) = self.lower_method_sig(
858 impl_trait_return_allow,
859 sig.header.asyncness.node.opt_return_id(),
862 (generics, hir::ImplItemKind::Method(sig, body_id))
864 AssocItemKind::TyAlias(_, ref ty) => {
865 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
866 let kind = match ty {
868 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
869 hir::ImplItemKind::TyAlias(ty)
871 Some(ty) => match ty.kind.opaque_top_hack() {
873 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
874 hir::ImplItemKind::TyAlias(ty)
877 let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
878 hir::ImplItemKind::OpaqueTy(bs)
884 AssocItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
888 hir_id: self.lower_node_id(i.id),
890 attrs: self.lower_attrs_arena(&i.attrs),
892 vis: self.lower_visibility(&i.vis, None),
893 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
898 // [1] since `default impl` is not yet implemented, this is always true in impls
901 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
903 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
906 vis: self.lower_visibility(&i.vis, Some(i.id)),
907 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
908 kind: match &i.kind {
909 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
910 AssocItemKind::TyAlias(_, ty) => {
911 match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
912 None => hir::AssocItemKind::Type,
913 Some(_) => hir::AssocItemKind::OpaqueTy,
916 AssocItemKind::Fn(sig, _) => {
917 hir::AssocItemKind::Method { has_self: sig.decl.has_self() }
919 AssocItemKind::Macro(..) => unimplemented!(),
923 // [1] since `default impl` is not yet implemented, this is always true in impls
926 /// If an `explicit_owner` is given, this method allocates the `HirId` in
927 /// the address space of that item instead of the item currently being
928 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
929 /// lower a `Visibility` value although we haven't lowered the owning
930 /// `ImplItem` in question yet.
934 explicit_owner: Option<NodeId>,
935 ) -> hir::Visibility<'hir> {
936 let node = match v.node {
937 VisibilityKind::Public => hir::VisibilityKind::Public,
938 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
939 VisibilityKind::Restricted { ref path, id } => {
940 debug!("lower_visibility: restricted path id = {:?}", id);
941 let lowered_id = if let Some(owner) = explicit_owner {
942 self.lower_node_id_with_owner(id, owner)
944 self.lower_node_id(id)
946 let res = self.expect_full_res(id);
947 let res = self.lower_res(res);
948 hir::VisibilityKind::Restricted {
949 path: self.arena.alloc(self.lower_path_extra(
958 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
963 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
965 Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
966 Defaultness::Final => {
968 hir::Defaultness::Final
975 params: &'hir [hir::Param<'hir>],
976 value: hir::Expr<'hir>,
978 let body = hir::Body { generator_kind: self.generator_kind, params, value };
980 self.bodies.insert(id, body);
986 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
988 let prev_gen_kind = self.generator_kind.take();
989 let (parameters, result) = f(self);
990 let body_id = self.record_body(parameters, result);
991 self.generator_kind = prev_gen_kind;
995 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
997 attrs: self.lower_attrs_arena(¶m.attrs),
998 hir_id: self.lower_node_id(param.id),
999 pat: self.lower_pat(¶m.pat),
1004 pub(super) fn lower_fn_body(
1007 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1009 self.lower_body(|this| {
1011 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1017 fn lower_fn_body_block(
1021 body: Option<&Block>,
1023 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1026 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1028 Some(block) => self.lower_block_expr(block),
1029 None => self.expr_err(span),
1033 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1034 self.lower_body(|this| {
1038 Some(expr) => this.lower_expr_mut(expr),
1039 None => this.expr_err(span),
1045 fn lower_maybe_async_body(
1050 body: Option<&Block>,
1052 let closure_id = match asyncness {
1053 IsAsync::Async { closure_id, .. } => closure_id,
1054 IsAsync::NotAsync => return self.lower_fn_body_block(span, decl, body),
1057 self.lower_body(|this| {
1058 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1059 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1061 // Async function parameters are lowered into the closure body so that they are
1062 // captured and so that the drop order matches the equivalent non-async functions.
1066 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1072 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1074 // let __arg2 = __arg2;
1075 // let <pattern> = __arg2;
1076 // let __arg1 = __arg1;
1077 // let <pattern> = __arg1;
1078 // let __arg0 = __arg0;
1079 // let <pattern> = __arg0;
1080 // drop-temps { <body> } // see comments later in fn for details
1084 // If `<pattern>` is a simple ident, then it is lowered to a single
1085 // `let <pattern> = <pattern>;` statement as an optimization.
1087 // Note that the body is embedded in `drop-temps`; an
1088 // equivalent desugaring would be `return { <body>
1089 // };`. The key point is that we wish to drop all the
1090 // let-bound variables and temporaries created in the body
1091 // (and its tail expression!) before we drop the
1092 // parameters (c.f. rust-lang/rust#64512).
1093 for (index, parameter) in decl.inputs.iter().enumerate() {
1094 let parameter = this.lower_param(parameter);
1095 let span = parameter.pat.span;
1097 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1098 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1099 let (ident, is_simple_parameter) = match parameter.pat.kind {
1100 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) => {
1104 // Replace the ident for bindings that aren't simple.
1105 let name = format!("__arg{}", index);
1106 let ident = Ident::from_str(&name);
1112 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1114 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1117 // If this is the simple case, this parameter will end up being the same as the
1118 // original parameter, but with a different pattern id.
1119 let mut stmt_attrs = AttrVec::new();
1120 stmt_attrs.extend(parameter.attrs.iter().cloned());
1121 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1122 let new_parameter = hir::Param {
1123 attrs: parameter.attrs,
1124 hir_id: parameter.hir_id,
1125 pat: new_parameter_pat,
1126 span: parameter.span,
1129 if is_simple_parameter {
1130 // If this is the simple case, then we only insert one statement that is
1131 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1132 // `HirId`s are densely assigned.
1133 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1134 let stmt = this.stmt_let_pat(
1137 Some(this.arena.alloc(expr)),
1139 hir::LocalSource::AsyncFn,
1141 statements.push(stmt);
1143 // If this is not the simple case, then we construct two statements:
1146 // let __argN = __argN;
1147 // let <pat> = __argN;
1150 // The first statement moves the parameter into the closure and thus ensures
1151 // that the drop order is correct.
1153 // The second statement creates the bindings that the user wrote.
1155 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1156 // because the user may have specified a `ref mut` binding in the next
1158 let (move_pat, move_id) = this.pat_ident_binding_mode(
1161 hir::BindingAnnotation::Mutable,
1163 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1164 let move_stmt = this.stmt_let_pat(
1167 Some(this.arena.alloc(move_expr)),
1169 hir::LocalSource::AsyncFn,
1172 // Construct the `let <pat> = __argN;` statement. We re-use the original
1173 // parameter's pattern so that `HirId`s are densely assigned.
1174 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1175 let pattern_stmt = this.stmt_let_pat(
1178 Some(this.arena.alloc(pattern_expr)),
1180 hir::LocalSource::AsyncFn,
1183 statements.push(move_stmt);
1184 statements.push(pattern_stmt);
1187 parameters.push(new_parameter);
1190 let body_span = body.map_or(span, |b| b.span);
1191 let async_expr = this.make_async_expr(
1196 hir::AsyncGeneratorKind::Fn,
1198 // Create a block from the user's function body:
1199 let user_body = this.lower_block_expr_opt(body_span, body);
1201 // Transform into `drop-temps { <user-body> }`, an expression:
1202 let desugared_span =
1203 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1204 let user_body = this.expr_drop_temps(
1206 this.arena.alloc(user_body),
1210 // As noted above, create the final block like
1214 // let $param_pattern = $raw_param;
1216 // drop-temps { <user-body> }
1219 let body = this.block_all(
1221 this.arena.alloc_from_iter(statements),
1225 this.expr_block(body, AttrVec::new())
1230 this.arena.alloc_from_iter(parameters),
1231 this.expr(body_span, async_expr, AttrVec::new()),
1236 fn lower_method_sig(
1238 generics: &Generics,
1241 impl_trait_return_allow: bool,
1242 is_async: Option<NodeId>,
1243 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1244 let header = self.lower_fn_header(sig.header);
1245 let (generics, decl) = self.add_in_band_defs(
1248 AnonymousLifetimeMode::PassThrough,
1252 Some((fn_def_id, idty)),
1253 impl_trait_return_allow,
1258 (generics, hir::FnSig { header, decl })
1261 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1263 unsafety: h.unsafety,
1264 asyncness: self.lower_asyncness(h.asyncness.node),
1265 constness: h.constness.node,
1266 abi: self.lower_extern(h.ext),
1270 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1271 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1272 self.error_on_invalid_abi(abi);
1277 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1279 Extern::None => abi::Abi::Rust,
1280 Extern::Implicit => abi::Abi::C,
1281 Extern::Explicit(abi) => self.lower_abi(abi),
1285 fn error_on_invalid_abi(&self, abi: StrLit) {
1286 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1287 .span_label(abi.span, "invalid ABI")
1288 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1292 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1294 IsAsync::Async { .. } => hir::IsAsync::Async,
1295 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1299 pub(super) fn lower_generics_mut(
1301 generics: &Generics,
1302 itctx: ImplTraitContext<'_, 'hir>,
1303 ) -> GenericsCtor<'hir> {
1304 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1305 // FIXME: this could probably be done with less rightward drift. It also looks like two
1306 // control paths where `report_error` is called are the only paths that advance to after the
1307 // match statement, so the error reporting could probably just be moved there.
1308 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1309 for pred in &generics.where_clause.predicates {
1310 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1311 'next_bound: for bound in &bound_pred.bounds {
1312 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1313 let report_error = |this: &mut Self| {
1314 this.diagnostic().span_err(
1315 bound_pred.bounded_ty.span,
1316 "`?Trait` bounds are only permitted at the \
1317 point where a type parameter is declared",
1320 // Check if the where clause type is a plain type parameter.
1321 match bound_pred.bounded_ty.kind {
1322 TyKind::Path(None, ref path)
1323 if path.segments.len() == 1
1324 && bound_pred.bound_generic_params.is_empty() =>
1326 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1328 .get_partial_res(bound_pred.bounded_ty.id)
1329 .map(|d| d.base_res())
1331 if let Some(node_id) =
1332 self.resolver.definitions().as_local_node_id(def_id)
1334 for param in &generics.params {
1336 GenericParamKind::Type { .. } => {
1337 if node_id == param.id {
1341 .push(bound.clone());
1342 continue 'next_bound;
1352 _ => report_error(self),
1360 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx),
1361 where_clause: self.lower_where_clause(&generics.where_clause),
1362 span: generics.span,
1366 pub(super) fn lower_generics(
1368 generics: &Generics,
1369 itctx: ImplTraitContext<'_, 'hir>,
1370 ) -> hir::Generics<'hir> {
1371 let generics_ctor = self.lower_generics_mut(generics, itctx);
1372 generics_ctor.into_generics(self.arena)
1375 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1376 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1378 predicates: this.arena.alloc_from_iter(
1379 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1386 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1388 WherePredicate::BoundPredicate(WhereBoundPredicate {
1389 ref bound_generic_params,
1394 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1395 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1396 bound_generic_params: this.lower_generic_params(
1397 bound_generic_params,
1398 &NodeMap::default(),
1399 ImplTraitContext::disallowed(),
1401 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1402 bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1404 // Ignore `?Trait` bounds.
1405 // They were copied into type parameters already.
1406 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1408 this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1416 WherePredicate::RegionPredicate(WhereRegionPredicate {
1420 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1422 lifetime: self.lower_lifetime(lifetime),
1423 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1425 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1426 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1427 hir_id: self.lower_node_id(id),
1428 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1429 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1437 /// Helper struct for delayed construction of Generics.
1438 pub(super) struct GenericsCtor<'hir> {
1439 pub(super) params: Vec<hir::GenericParam<'hir>>,
1440 where_clause: hir::WhereClause<'hir>,
1444 impl GenericsCtor<'hir> {
1445 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1447 params: arena.alloc_from_iter(self.params),
1448 where_clause: self.where_clause,