1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition, ImplTraitTypeIdVisitor};
4 use rustc::arena::Arena;
6 use rustc_errors::struct_span_err;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_span::source_map::{respan, DesugaringKind};
11 use rustc_span::symbol::{kw, sym};
13 use rustc_target::spec::abi;
16 use syntax::node_id::NodeMap;
17 use syntax::visit::{self, AssocCtxt, Visitor};
20 use smallvec::{smallvec, SmallVec};
21 use std::collections::BTreeSet;
23 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
24 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
27 impl ItemLowerer<'_, '_, '_> {
28 fn with_trait_impl_ref(&mut self, impl_ref: &Option<TraitRef>, f: impl FnOnce(&mut Self)) {
29 let old = self.lctx.is_in_trait_impl;
30 self.lctx.is_in_trait_impl = if let &None = impl_ref { false } else { true };
32 self.lctx.is_in_trait_impl = old;
36 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
37 fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
38 let hir_id = self.lctx.lower_node_id(n);
40 self.lctx.modules.insert(
43 items: BTreeSet::new(),
44 trait_items: BTreeSet::new(),
45 impl_items: BTreeSet::new(),
49 let old = self.lctx.current_module;
50 self.lctx.current_module = hir_id;
51 visit::walk_mod(self, m);
52 self.lctx.current_module = old;
55 fn visit_item(&mut self, item: &'a Item) {
56 let mut item_hir_id = None;
57 self.lctx.with_hir_id_owner(item.id, |lctx| {
58 lctx.without_in_scope_lifetime_defs(|lctx| {
59 if let Some(hir_item) = lctx.lower_item(item) {
60 item_hir_id = Some(hir_item.hir_id);
61 lctx.insert_item(hir_item);
66 if let Some(hir_id) = item_hir_id {
67 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
68 let this = &mut ItemLowerer { lctx: this };
69 if let ItemKind::Impl { ref of_trait, .. } = item.kind {
70 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
72 visit::walk_item(this, item);
78 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
79 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
81 let hir_item = lctx.lower_trait_item(item);
82 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
83 lctx.trait_items.insert(id, hir_item);
84 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
87 let hir_item = lctx.lower_impl_item(item);
88 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
89 lctx.impl_items.insert(id, hir_item);
90 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
94 visit::walk_assoc_item(self, item, ctxt);
98 impl<'hir> LoweringContext<'_, 'hir> {
99 // Same as the method above, but accepts `hir::GenericParam`s
100 // instead of `ast::GenericParam`s.
101 // This should only be used with generics that have already had their
102 // in-band lifetimes added. In practice, this means that this function is
103 // only used when lowering a child item of a trait or impl.
104 fn with_parent_item_lifetime_defs<T>(
106 parent_hir_id: hir::HirId,
107 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
109 let old_len = self.in_scope_lifetimes.len();
111 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
112 hir::ItemKind::Impl { ref generics, .. }
113 | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..],
116 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
117 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
120 self.in_scope_lifetimes.extend(lt_def_names);
124 self.in_scope_lifetimes.truncate(old_len);
128 // Clears (and restores) the `in_scope_lifetimes` field. Used when
129 // visiting nested items, which never inherit in-scope lifetimes
130 // from their surrounding environment.
131 fn without_in_scope_lifetime_defs<T>(
133 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
135 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
137 // this vector is only used when walking over impl headers,
138 // input types, and the like, and should not be non-empty in
140 assert!(self.lifetimes_to_define.is_empty());
144 assert!(self.in_scope_lifetimes.is_empty());
145 self.in_scope_lifetimes = old_in_scope_lifetimes;
150 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
155 .alloc_from_iter(m.items.iter().flat_map(|x| self.lower_item_id(x))),
159 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
160 let node_ids = match i.kind {
161 ItemKind::Use(ref use_tree) => {
162 let mut vec = smallvec![i.id];
163 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
166 ItemKind::MacroDef(..) => SmallVec::new(),
167 ItemKind::Fn(..) | ItemKind::Impl { of_trait: None, .. } => smallvec![i.id],
168 ItemKind::Static(ref ty, ..) => {
169 let mut ids = smallvec![i.id];
170 if self.sess.features_untracked().impl_trait_in_bindings {
171 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
172 visitor.visit_ty(ty);
176 ItemKind::Const(_, ref ty, ..) => {
177 let mut ids = smallvec![i.id];
178 if self.sess.features_untracked().impl_trait_in_bindings {
179 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
180 visitor.visit_ty(ty);
184 _ => smallvec![i.id],
189 .map(|node_id| hir::ItemId { id: self.allocate_hir_id_counter(node_id) })
193 fn lower_item_id_use_tree(
197 vec: &mut SmallVec<[NodeId; 1]>,
200 UseTreeKind::Nested(ref nested_vec) => {
201 for &(ref nested, id) in nested_vec {
203 self.lower_item_id_use_tree(nested, id, vec);
206 UseTreeKind::Glob => {}
207 UseTreeKind::Simple(_, id1, id2) => {
209 self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter())
217 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
218 let mut ident = i.ident;
219 let mut vis = self.lower_visibility(&i.vis, None);
220 let attrs = self.lower_attrs(&i.attrs);
222 if let ItemKind::MacroDef(ref def) = i.kind {
223 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
224 let body = self.lower_token_stream(def.body.inner_tokens());
225 let hir_id = self.lower_node_id(i.id);
226 self.exported_macros.push(hir::MacroDef {
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);
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();
290 this.lower_fn_decl(&decl, Some((fn_def_id, idty)), true, ret_id)
293 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
294 hir::ItemKind::Fn(sig, generics, body_id)
297 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
298 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
299 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
300 ItemKind::TyAlias(_, ref gen, _, Some(ref ty)) => match ty.kind.opaque_top_hack() {
302 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
303 let generics = self.lower_generics(gen, ImplTraitContext::disallowed());
304 hir::ItemKind::TyAlias(ty, generics)
307 let ctx = || ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc);
308 let ty = hir::OpaqueTy {
309 generics: self.lower_generics(gen, ctx()),
310 bounds: self.lower_param_bounds(bounds, ctx()),
312 origin: hir::OpaqueTyOrigin::TypeAlias,
314 hir::ItemKind::OpaqueTy(ty)
317 ItemKind::TyAlias(_, ref generics, _, None) => {
318 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
319 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
320 hir::ItemKind::TyAlias(ty, generics)
322 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
324 variants: self.arena.alloc_from_iter(
325 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
328 self.lower_generics(generics, ImplTraitContext::disallowed()),
330 ItemKind::Struct(ref struct_def, ref generics) => {
331 let struct_def = self.lower_variant_data(struct_def);
332 hir::ItemKind::Struct(
334 self.lower_generics(generics, ImplTraitContext::disallowed()),
337 ItemKind::Union(ref vdata, ref generics) => {
338 let vdata = self.lower_variant_data(vdata);
339 hir::ItemKind::Union(
341 self.lower_generics(generics, ImplTraitContext::disallowed()),
349 generics: ref ast_generics,
350 of_trait: ref trait_ref,
352 items: ref impl_items,
354 let def_id = self.resolver.definitions().local_def_id(id);
356 // Lower the "impl header" first. This ordering is important
357 // for in-band lifetimes! Consider `'a` here:
359 // impl Foo<'a> for u32 {
360 // fn method(&'a self) { .. }
363 // Because we start by lowering the `Foo<'a> for u32`
364 // part, we will add `'a` to the list of generics on
365 // the impl. When we then encounter it later in the
366 // method, it will not be considered an in-band
367 // lifetime to be added, but rather a reference to a
369 let lowered_trait_impl_id = self.lower_node_id(id);
370 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
373 AnonymousLifetimeMode::CreateParameter,
375 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
376 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
379 if let Some(ref trait_ref) = trait_ref {
380 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
384 .push(lowered_trait_impl_id);
388 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
390 (trait_ref, lowered_ty)
395 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
396 this.arena.alloc_from_iter(
397 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
401 hir::ItemKind::Impl {
402 unsafety: self.lower_unsafety(unsafety),
404 defaultness: self.lower_defaultness(defaultness, true /* [1] */),
405 constness: self.lower_constness(constness),
409 items: new_impl_items,
412 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
413 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
416 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
417 hir::ItemKind::Trait(
419 self.lower_unsafety(unsafety),
420 self.lower_generics(generics, ImplTraitContext::disallowed()),
425 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
426 self.lower_generics(generics, ImplTraitContext::disallowed()),
427 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
429 ItemKind::MacroDef(..) | ItemKind::Mac(..) => {
430 bug!("`TyMac` should have been expanded by now")
434 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
435 // not cause an assertion failure inside the `lower_defaultness` function.
443 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
444 let itctx = if self.sess.features_untracked().impl_trait_in_bindings {
445 ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc)
447 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
449 let ty = self.lower_ty(ty, itctx);
450 (ty, self.lower_const_body(span, body))
458 vis: &mut hir::Visibility<'hir>,
460 attrs: &'hir [Attribute],
461 ) -> hir::ItemKind<'hir> {
462 debug!("lower_use_tree(tree={:?})", tree);
463 debug!("lower_use_tree: vis = {:?}", vis);
465 let path = &tree.prefix;
466 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
469 UseTreeKind::Simple(rename, id1, id2) => {
470 *ident = tree.ident();
472 // First, apply the prefix to the path.
473 let mut path = Path { segments, span: path.span };
475 // Correctly resolve `self` imports.
476 if path.segments.len() > 1
477 && path.segments.last().unwrap().ident.name == kw::SelfLower
479 let _ = path.segments.pop();
480 if rename.is_none() {
481 *ident = path.segments.last().unwrap().ident;
485 let mut resolutions = self.expect_full_res_from_use(id);
486 // We want to return *something* from this function, so hold onto the first item
488 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
490 // Here, we are looping over namespaces, if they exist for the definition
491 // being imported. We only handle type and value namespaces because we
492 // won't be dealing with macros in the rest of the compiler.
493 // Essentially a single `use` which imports two names is desugared into
495 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
497 let mut path = path.clone();
498 for seg in &mut path.segments {
499 seg.id = self.resolver.next_node_id();
501 let span = path.span;
503 self.with_hir_id_owner(new_node_id, |this| {
504 let new_id = this.lower_node_id(new_node_id);
505 let res = this.lower_res(res);
506 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
507 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
508 let vis = this.rebuild_vis(&vis);
510 this.insert_item(hir::Item {
521 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
522 hir::ItemKind::Use(path, hir::UseKind::Single)
524 UseTreeKind::Glob => {
526 self.lower_path(id, &Path { segments, span: path.span }, ParamMode::Explicit);
527 hir::ItemKind::Use(path, hir::UseKind::Glob)
529 UseTreeKind::Nested(ref trees) => {
530 // Nested imports are desugared into simple imports.
531 // So, if we start with
534 // pub(x) use foo::{a, b};
537 // we will create three items:
540 // pub(x) use foo::a;
541 // pub(x) use foo::b;
542 // pub(x) use foo::{}; // <-- this is called the `ListStem`
545 // The first two are produced by recursively invoking
546 // `lower_use_tree` (and indeed there may be things
547 // like `use foo::{a::{b, c}}` and so forth). They
548 // wind up being directly added to
549 // `self.items`. However, the structure of this
550 // function also requires us to return one item, and
551 // for that we return the `{}` import (called the
554 let prefix = Path { segments, span: prefix.span.to(path.span) };
556 // Add all the nested `PathListItem`s to the HIR.
557 for &(ref use_tree, id) in trees {
558 let new_hir_id = self.lower_node_id(id);
560 let mut prefix = prefix.clone();
562 // Give the segments new node-ids since they are being cloned.
563 for seg in &mut prefix.segments {
564 seg.id = self.resolver.next_node_id();
567 // Each `use` import is an item and thus are owners of the
568 // names in the path. Up to this point the nested import is
569 // the current owner, since we want each desugared import to
570 // own its own names, we have to adjust the owner before
571 // lowering the rest of the import.
572 self.with_hir_id_owner(id, |this| {
573 let mut vis = this.rebuild_vis(&vis);
574 let mut ident = *ident;
577 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
579 this.insert_item(hir::Item {
590 // Subtle and a bit hacky: we lower the privacy level
591 // of the list stem to "private" most of the time, but
592 // not for "restricted" paths. The key thing is that
593 // we don't want it to stay as `pub` (with no caveats)
594 // because that affects rustdoc and also the lints
595 // about `pub` items. But we can't *always* make it
596 // private -- particularly not for restricted paths --
597 // because it contains node-ids that would then be
598 // unused, failing the check that HirIds are "densely
601 hir::VisibilityKind::Public
602 | hir::VisibilityKind::Crate(_)
603 | hir::VisibilityKind::Inherited => {
604 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
606 hir::VisibilityKind::Restricted { .. } => {
607 // Do nothing here, as described in the comment on the match.
611 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
612 let res = self.lower_res(res);
613 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
614 hir::ItemKind::Use(path, hir::UseKind::ListStem)
619 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
620 /// many times in the HIR tree; for each occurrence, we need to assign distinct
621 /// `NodeId`s. (See, e.g., #56128.)
622 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
623 debug!("rebuild_use_path(path = {:?})", path);
625 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
627 hir_id: seg.hir_id.map(|_| self.next_id()),
630 infer_args: seg.infer_args,
632 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
635 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
636 let vis_kind = match vis.node {
637 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
638 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
639 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
640 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
641 hir::VisibilityKind::Restricted {
642 path: self.rebuild_use_path(path),
643 hir_id: self.next_id(),
647 respan(vis.span, vis_kind)
650 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
651 let def_id = self.resolver.definitions().local_def_id(i.id);
653 hir_id: self.lower_node_id(i.id),
655 attrs: self.lower_attrs(&i.attrs),
657 ForeignItemKind::Fn(_, ref sig, ref generics, _) => {
658 let fdec = &sig.decl;
659 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
662 AnonymousLifetimeMode::PassThrough,
665 // Disallow `impl Trait` in foreign items.
666 this.lower_fn_decl(fdec, None, false, None),
667 this.lower_fn_params_to_names(fdec),
672 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
674 ForeignItemKind::Static(ref t, m, _) => {
675 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
676 hir::ForeignItemKind::Static(ty, m)
678 ForeignItemKind::Const(_, ref t, _) => {
679 // For recovery purposes.
680 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
681 hir::ForeignItemKind::Static(ty, Mutability::Not)
683 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
684 ForeignItemKind::Macro(_) => 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);
759 let (generics, kind) = match i.kind {
760 AssocItemKind::Static(ref ty, _, ref default) // Let's pretend this is a `const`.
761 | AssocItemKind::Const(_, ref ty, ref default) => {
762 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
763 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
764 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
766 AssocItemKind::Fn(_, ref sig, ref generics, None) => {
767 let names = self.lower_fn_params_to_names(&sig.decl);
768 let (generics, sig) =
769 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
770 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
772 AssocItemKind::Fn(_, ref sig, ref generics, Some(ref body)) => {
773 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
774 let (generics, sig) =
775 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
776 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
778 AssocItemKind::TyAlias(_, ref generics, ref bounds, ref default) => {
779 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
780 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
781 let kind = hir::TraitItemKind::Type(
782 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
788 AssocItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
792 hir_id: self.lower_node_id(i.id),
794 attrs: self.lower_attrs(&i.attrs),
801 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
802 let (kind, has_default) = match &i.kind {
803 AssocItemKind::Static(_, _, default) // Let's pretend this is a `const` for recovery.
804 | AssocItemKind::Const(_, _, default) => {
805 (hir::AssocItemKind::Const, default.is_some())
807 AssocItemKind::TyAlias(_, _, _, default) => (hir::AssocItemKind::Type, default.is_some()),
808 AssocItemKind::Fn(_, sig, _, default) => {
809 (hir::AssocItemKind::Method { has_self: sig.decl.has_self() }, default.is_some())
811 AssocItemKind::Macro(..) => unimplemented!(),
813 let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id) };
814 let defaultness = hir::Defaultness::Default { has_value: has_default };
815 hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind }
818 /// Construct `ExprKind::Err` for the given `span`.
819 fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
820 self.expr(span, hir::ExprKind::Err, AttrVec::new())
823 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
824 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
826 let (generics, kind) = match &i.kind {
827 AssocItemKind::Static(ty, _, expr) | AssocItemKind::Const(_, ty, expr) => {
828 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
830 hir::Generics::empty(),
831 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
834 AssocItemKind::Fn(_, sig, generics, body) => {
835 self.current_item = Some(i.span);
836 let asyncness = sig.header.asyncness;
838 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
839 let impl_trait_return_allow = !self.is_in_trait_impl;
840 let (generics, sig) = self.lower_method_sig(
844 impl_trait_return_allow,
845 asyncness.opt_return_id(),
848 (generics, hir::ImplItemKind::Method(sig, body_id))
850 AssocItemKind::TyAlias(_, generics, _, ty) => {
851 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
852 let kind = match ty {
854 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
855 hir::ImplItemKind::TyAlias(ty)
857 Some(ty) => match ty.kind.opaque_top_hack() {
859 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
860 hir::ImplItemKind::TyAlias(ty)
863 let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
864 hir::ImplItemKind::OpaqueTy(bs)
870 AssocItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
874 hir_id: self.lower_node_id(i.id),
876 attrs: self.lower_attrs(&i.attrs),
878 vis: self.lower_visibility(&i.vis, None),
879 defaultness: self.lower_defaultness(i.kind.defaultness(), true /* [1] */),
884 // [1] since `default impl` is not yet implemented, this is always true in impls
887 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
889 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
892 vis: self.lower_visibility(&i.vis, Some(i.id)),
893 defaultness: self.lower_defaultness(i.kind.defaultness(), true /* [1] */),
894 kind: match &i.kind {
895 AssocItemKind::Static(..) // Let's pretend this is a `const` for recovery.
896 | AssocItemKind::Const(..) => hir::AssocItemKind::Const,
897 AssocItemKind::TyAlias(.., ty) => {
898 match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
899 None => hir::AssocItemKind::Type,
900 Some(_) => hir::AssocItemKind::OpaqueTy,
903 AssocItemKind::Fn(_, sig, ..) => {
904 hir::AssocItemKind::Method { has_self: sig.decl.has_self() }
906 AssocItemKind::Macro(..) => unimplemented!(),
910 // [1] since `default impl` is not yet implemented, this is always true in impls
913 /// If an `explicit_owner` is given, this method allocates the `HirId` in
914 /// the address space of that item instead of the item currently being
915 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
916 /// lower a `Visibility` value although we haven't lowered the owning
917 /// `ImplItem` in question yet.
921 explicit_owner: Option<NodeId>,
922 ) -> hir::Visibility<'hir> {
923 let node = match v.node {
924 VisibilityKind::Public => hir::VisibilityKind::Public,
925 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
926 VisibilityKind::Restricted { ref path, id } => {
927 debug!("lower_visibility: restricted path id = {:?}", id);
928 let lowered_id = if let Some(owner) = explicit_owner {
929 self.lower_node_id_with_owner(id, owner)
931 self.lower_node_id(id)
933 let res = self.expect_full_res(id);
934 let res = self.lower_res(res);
935 hir::VisibilityKind::Restricted {
936 path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
940 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
945 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
947 Defaultness::Default(_) => hir::Defaultness::Default { has_value },
948 Defaultness::Final => {
950 hir::Defaultness::Final
957 params: &'hir [hir::Param<'hir>],
958 value: hir::Expr<'hir>,
960 let body = hir::Body { generator_kind: self.generator_kind, params, value };
962 self.bodies.insert(id, body);
968 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
970 let prev_gen_kind = self.generator_kind.take();
971 let (parameters, result) = f(self);
972 let body_id = self.record_body(parameters, result);
973 self.generator_kind = prev_gen_kind;
977 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
979 attrs: self.lower_attrs(¶m.attrs),
980 hir_id: self.lower_node_id(param.id),
981 pat: self.lower_pat(¶m.pat),
986 pub(super) fn lower_fn_body(
989 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
991 self.lower_body(|this| {
993 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
999 fn lower_fn_body_block(
1003 body: Option<&Block>,
1005 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1008 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1010 Some(block) => self.lower_block_expr(block),
1011 None => self.expr_err(span),
1015 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1016 self.lower_body(|this| {
1020 Some(expr) => this.lower_expr_mut(expr),
1021 None => this.expr_err(span),
1027 fn lower_maybe_async_body(
1032 body: Option<&Block>,
1034 let closure_id = match asyncness {
1035 Async::Yes { closure_id, .. } => closure_id,
1036 Async::No => return self.lower_fn_body_block(span, decl, body),
1039 self.lower_body(|this| {
1040 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1041 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1043 // Async function parameters are lowered into the closure body so that they are
1044 // captured and so that the drop order matches the equivalent non-async functions.
1048 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1054 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1056 // let __arg2 = __arg2;
1057 // let <pattern> = __arg2;
1058 // let __arg1 = __arg1;
1059 // let <pattern> = __arg1;
1060 // let __arg0 = __arg0;
1061 // let <pattern> = __arg0;
1062 // drop-temps { <body> } // see comments later in fn for details
1066 // If `<pattern>` is a simple ident, then it is lowered to a single
1067 // `let <pattern> = <pattern>;` statement as an optimization.
1069 // Note that the body is embedded in `drop-temps`; an
1070 // equivalent desugaring would be `return { <body>
1071 // };`. The key point is that we wish to drop all the
1072 // let-bound variables and temporaries created in the body
1073 // (and its tail expression!) before we drop the
1074 // parameters (c.f. rust-lang/rust#64512).
1075 for (index, parameter) in decl.inputs.iter().enumerate() {
1076 let parameter = this.lower_param(parameter);
1077 let span = parameter.pat.span;
1079 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1080 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1081 let (ident, is_simple_parameter) = match parameter.pat.kind {
1082 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) => {
1086 // Replace the ident for bindings that aren't simple.
1087 let name = format!("__arg{}", index);
1088 let ident = Ident::from_str(&name);
1094 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1096 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1099 // If this is the simple case, this parameter will end up being the same as the
1100 // original parameter, but with a different pattern id.
1101 let mut stmt_attrs = AttrVec::new();
1102 stmt_attrs.extend(parameter.attrs.iter().cloned());
1103 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1104 let new_parameter = hir::Param {
1105 attrs: parameter.attrs,
1106 hir_id: parameter.hir_id,
1107 pat: new_parameter_pat,
1108 span: parameter.span,
1111 if is_simple_parameter {
1112 // If this is the simple case, then we only insert one statement that is
1113 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1114 // `HirId`s are densely assigned.
1115 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1116 let stmt = this.stmt_let_pat(
1121 hir::LocalSource::AsyncFn,
1123 statements.push(stmt);
1125 // If this is not the simple case, then we construct two statements:
1128 // let __argN = __argN;
1129 // let <pat> = __argN;
1132 // The first statement moves the parameter into the closure and thus ensures
1133 // that the drop order is correct.
1135 // The second statement creates the bindings that the user wrote.
1137 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1138 // because the user may have specified a `ref mut` binding in the next
1140 let (move_pat, move_id) = this.pat_ident_binding_mode(
1143 hir::BindingAnnotation::Mutable,
1145 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1146 let move_stmt = this.stmt_let_pat(
1151 hir::LocalSource::AsyncFn,
1154 // Construct the `let <pat> = __argN;` statement. We re-use the original
1155 // parameter's pattern so that `HirId`s are densely assigned.
1156 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1157 let pattern_stmt = this.stmt_let_pat(
1162 hir::LocalSource::AsyncFn,
1165 statements.push(move_stmt);
1166 statements.push(pattern_stmt);
1169 parameters.push(new_parameter);
1172 let body_span = body.map_or(span, |b| b.span);
1173 let async_expr = this.make_async_expr(
1178 hir::AsyncGeneratorKind::Fn,
1180 // Create a block from the user's function body:
1181 let user_body = this.lower_block_expr_opt(body_span, body);
1183 // Transform into `drop-temps { <user-body> }`, an expression:
1184 let desugared_span =
1185 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1186 let user_body = this.expr_drop_temps(
1188 this.arena.alloc(user_body),
1192 // As noted above, create the final block like
1196 // let $param_pattern = $raw_param;
1198 // drop-temps { <user-body> }
1201 let body = this.block_all(
1203 this.arena.alloc_from_iter(statements),
1207 this.expr_block(body, AttrVec::new())
1212 this.arena.alloc_from_iter(parameters),
1213 this.expr(body_span, async_expr, AttrVec::new()),
1218 fn lower_method_sig(
1220 generics: &Generics,
1223 impl_trait_return_allow: bool,
1224 is_async: Option<NodeId>,
1225 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1226 let header = self.lower_fn_header(sig.header);
1227 let (generics, decl) = self.add_in_band_defs(
1230 AnonymousLifetimeMode::PassThrough,
1234 Some((fn_def_id, idty)),
1235 impl_trait_return_allow,
1240 (generics, hir::FnSig { header, decl })
1243 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1245 unsafety: self.lower_unsafety(h.unsafety),
1246 asyncness: self.lower_asyncness(h.asyncness),
1247 constness: self.lower_constness(h.constness),
1248 abi: self.lower_extern(h.ext),
1252 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1253 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1254 self.error_on_invalid_abi(abi);
1259 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1261 Extern::None => abi::Abi::Rust,
1262 Extern::Implicit => abi::Abi::C,
1263 Extern::Explicit(abi) => self.lower_abi(abi),
1267 fn error_on_invalid_abi(&self, abi: StrLit) {
1268 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1269 .span_label(abi.span, "invalid ABI")
1270 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1274 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1276 Async::Yes { .. } => hir::IsAsync::Async,
1277 Async::No => hir::IsAsync::NotAsync,
1281 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1283 Const::Yes(_) => hir::Constness::Const,
1284 Const::No => hir::Constness::NotConst,
1288 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1290 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1291 Unsafe::No => hir::Unsafety::Normal,
1295 pub(super) fn lower_generics_mut(
1297 generics: &Generics,
1298 itctx: ImplTraitContext<'_, 'hir>,
1299 ) -> GenericsCtor<'hir> {
1300 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1301 // FIXME: this could probably be done with less rightward drift. It also looks like two
1302 // control paths where `report_error` is called are the only paths that advance to after the
1303 // match statement, so the error reporting could probably just be moved there.
1304 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1305 for pred in &generics.where_clause.predicates {
1306 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1307 'next_bound: for bound in &bound_pred.bounds {
1308 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1309 let report_error = |this: &mut Self| {
1310 this.diagnostic().span_err(
1311 bound_pred.bounded_ty.span,
1312 "`?Trait` bounds are only permitted at the \
1313 point where a type parameter is declared",
1316 // Check if the where clause type is a plain type parameter.
1317 match bound_pred.bounded_ty.kind {
1318 TyKind::Path(None, ref path)
1319 if path.segments.len() == 1
1320 && bound_pred.bound_generic_params.is_empty() =>
1322 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1324 .get_partial_res(bound_pred.bounded_ty.id)
1325 .map(|d| d.base_res())
1327 if let Some(node_id) =
1328 self.resolver.definitions().as_local_node_id(def_id)
1330 for param in &generics.params {
1332 GenericParamKind::Type { .. } => {
1333 if node_id == param.id {
1337 .push(bound.clone());
1338 continue 'next_bound;
1348 _ => report_error(self),
1356 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1357 where_clause: self.lower_where_clause(&generics.where_clause),
1358 span: generics.span,
1362 pub(super) fn lower_generics(
1364 generics: &Generics,
1365 itctx: ImplTraitContext<'_, 'hir>,
1366 ) -> hir::Generics<'hir> {
1367 let generics_ctor = self.lower_generics_mut(generics, itctx);
1368 generics_ctor.into_generics(self.arena)
1371 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1372 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1374 predicates: this.arena.alloc_from_iter(
1375 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1382 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1384 WherePredicate::BoundPredicate(WhereBoundPredicate {
1385 ref bound_generic_params,
1390 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1391 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1392 bound_generic_params: this.lower_generic_params(
1393 bound_generic_params,
1394 &NodeMap::default(),
1395 ImplTraitContext::disallowed(),
1397 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1398 bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1400 // Ignore `?Trait` bounds.
1401 // They were copied into type parameters already.
1402 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1404 this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1412 WherePredicate::RegionPredicate(WhereRegionPredicate {
1416 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1418 lifetime: self.lower_lifetime(lifetime),
1419 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1421 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1422 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1423 hir_id: self.lower_node_id(id),
1424 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1425 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1433 /// Helper struct for delayed construction of Generics.
1434 pub(super) struct GenericsCtor<'hir> {
1435 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1436 where_clause: hir::WhereClause<'hir>,
1440 impl<'hir> GenericsCtor<'hir> {
1441 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1443 params: arena.alloc_from_iter(self.params),
1444 where_clause: self.where_clause,