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 { constness, ref of_trait, .. } = item.kind {
70 if let Const::Yes(span) = constness {
73 .struct_span_err(item.span, "const trait impls are not yet implemented")
74 .span_label(span, "const because of this")
78 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
80 visit::walk_item(this, item);
86 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
87 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
89 let hir_item = lctx.lower_trait_item(item);
90 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
91 lctx.trait_items.insert(id, hir_item);
92 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
95 let hir_item = lctx.lower_impl_item(item);
96 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
97 lctx.impl_items.insert(id, hir_item);
98 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
102 visit::walk_assoc_item(self, item, ctxt);
106 impl<'hir> LoweringContext<'_, 'hir> {
107 // Same as the method above, but accepts `hir::GenericParam`s
108 // instead of `ast::GenericParam`s.
109 // This should only be used with generics that have already had their
110 // in-band lifetimes added. In practice, this means that this function is
111 // only used when lowering a child item of a trait or impl.
112 fn with_parent_item_lifetime_defs<T>(
114 parent_hir_id: hir::HirId,
115 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
117 let old_len = self.in_scope_lifetimes.len();
119 let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind {
120 hir::ItemKind::Impl { ref generics, .. }
121 | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..],
124 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
125 hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
128 self.in_scope_lifetimes.extend(lt_def_names);
132 self.in_scope_lifetimes.truncate(old_len);
136 // Clears (and restores) the `in_scope_lifetimes` field. Used when
137 // visiting nested items, which never inherit in-scope lifetimes
138 // from their surrounding environment.
139 fn without_in_scope_lifetime_defs<T>(
141 f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T,
143 let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]);
145 // this vector is only used when walking over impl headers,
146 // input types, and the like, and should not be non-empty in
148 assert!(self.lifetimes_to_define.is_empty());
152 assert!(self.in_scope_lifetimes.is_empty());
153 self.in_scope_lifetimes = old_in_scope_lifetimes;
158 pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'hir> {
163 .alloc_from_iter(m.items.iter().flat_map(|x| self.lower_item_id(x))),
167 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
168 let node_ids = match i.kind {
169 ItemKind::Use(ref use_tree) => {
170 let mut vec = smallvec![i.id];
171 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
174 ItemKind::MacroDef(..) => SmallVec::new(),
175 ItemKind::Fn(..) | ItemKind::Impl { of_trait: None, .. } => smallvec![i.id],
176 ItemKind::Static(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 ItemKind::Const(ref ty, ..) => {
185 let mut ids = smallvec![i.id];
186 if self.sess.features_untracked().impl_trait_in_bindings {
187 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
188 visitor.visit_ty(ty);
192 _ => smallvec![i.id],
197 .map(|node_id| hir::ItemId { id: self.allocate_hir_id_counter(node_id) })
201 fn lower_item_id_use_tree(
205 vec: &mut SmallVec<[NodeId; 1]>,
208 UseTreeKind::Nested(ref nested_vec) => {
209 for &(ref nested, id) in nested_vec {
211 self.lower_item_id_use_tree(nested, id, vec);
214 UseTreeKind::Glob => {}
215 UseTreeKind::Simple(_, id1, id2) => {
217 self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter())
225 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
226 let mut ident = i.ident;
227 let mut vis = self.lower_visibility(&i.vis, None);
228 let attrs = self.lower_attrs(&i.attrs);
230 if let ItemKind::MacroDef(ref def) = i.kind {
231 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
232 let body = self.lower_token_stream(def.body.inner_tokens());
233 let hir_id = self.lower_node_id(i.id);
234 self.exported_macros.push(hir::MacroDef {
244 self.non_exported_macro_attrs.extend(attrs.iter().cloned());
249 let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind);
251 Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span })
259 attrs: &'hir [Attribute],
260 vis: &mut hir::Visibility<'hir>,
262 ) -> hir::ItemKind<'hir> {
264 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
265 ItemKind::Use(ref use_tree) => {
266 // Start with an empty prefix.
267 let prefix = Path { segments: vec![], span: use_tree.span };
269 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
271 ItemKind::Static(ref t, m, ref e) => {
272 let ty = self.lower_ty(
274 if self.sess.features_untracked().impl_trait_in_bindings {
275 ImplTraitContext::OpaqueTy(None)
277 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
280 hir::ItemKind::Static(ty, m, self.lower_const_body(span, Some(e)))
282 ItemKind::Const(ref t, ref e) => {
283 let ty = self.lower_ty(
285 if self.sess.features_untracked().impl_trait_in_bindings {
286 ImplTraitContext::OpaqueTy(None)
288 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
291 hir::ItemKind::Const(ty, self.lower_const_body(span, Some(e)))
293 ItemKind::Fn(FnSig { ref decl, header }, ref generics, ref body) => {
294 let fn_def_id = self.resolver.definitions().local_def_id(id);
295 self.with_new_scopes(|this| {
296 this.current_item = Some(ident.span);
298 // Note: we don't need to change the return type from `T` to
299 // `impl Future<Output = T>` here because lower_body
300 // only cares about the input argument patterns in the function
301 // declaration (decl), not the return types.
302 let asyncness = header.asyncness.node;
304 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
306 let (generics, decl) = this.add_in_band_defs(
309 AnonymousLifetimeMode::PassThrough,
311 let ret_id = asyncness.opt_return_id();
312 this.lower_fn_decl(&decl, Some((fn_def_id, idty)), true, ret_id)
315 let sig = hir::FnSig { decl, header: this.lower_fn_header(header) };
316 hir::ItemKind::Fn(sig, generics, body_id)
319 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
320 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
321 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
322 ItemKind::TyAlias(ref ty, ref generics) => match ty.kind.opaque_top_hack() {
324 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
325 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
326 hir::ItemKind::TyAlias(ty, generics)
329 let ty = hir::OpaqueTy {
330 generics: self.lower_generics(generics, ImplTraitContext::OpaqueTy(None)),
331 bounds: self.lower_param_bounds(bounds, ImplTraitContext::OpaqueTy(None)),
333 origin: hir::OpaqueTyOrigin::TypeAlias,
335 hir::ItemKind::OpaqueTy(ty)
338 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
340 variants: self.arena.alloc_from_iter(
341 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
344 self.lower_generics(generics, ImplTraitContext::disallowed()),
346 ItemKind::Struct(ref struct_def, ref generics) => {
347 let struct_def = self.lower_variant_data(struct_def);
348 hir::ItemKind::Struct(
350 self.lower_generics(generics, ImplTraitContext::disallowed()),
353 ItemKind::Union(ref vdata, ref generics) => {
354 let vdata = self.lower_variant_data(vdata);
355 hir::ItemKind::Union(
357 self.lower_generics(generics, ImplTraitContext::disallowed()),
365 generics: ref ast_generics,
366 of_trait: ref trait_ref,
368 items: ref impl_items,
370 let def_id = self.resolver.definitions().local_def_id(id);
372 // Lower the "impl header" first. This ordering is important
373 // for in-band lifetimes! Consider `'a` here:
375 // impl Foo<'a> for u32 {
376 // fn method(&'a self) { .. }
379 // Because we start by lowering the `Foo<'a> for u32`
380 // part, we will add `'a` to the list of generics on
381 // the impl. When we then encounter it later in the
382 // method, it will not be considered an in-band
383 // lifetime to be added, but rather a reference to a
385 let lowered_trait_impl_id = self.lower_node_id(id);
386 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
389 AnonymousLifetimeMode::CreateParameter,
391 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
392 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
395 if let Some(ref trait_ref) = trait_ref {
396 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
400 .push(lowered_trait_impl_id);
404 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
406 (trait_ref, lowered_ty)
411 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
412 this.arena.alloc_from_iter(
413 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
417 hir::ItemKind::Impl {
418 unsafety: self.lower_unsafety(unsafety),
420 defaultness: self.lower_defaultness(defaultness, true /* [1] */),
421 constness: self.lower_constness(constness),
425 items: new_impl_items,
428 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
429 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
432 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
433 hir::ItemKind::Trait(
435 self.lower_unsafety(unsafety),
436 self.lower_generics(generics, ImplTraitContext::disallowed()),
441 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
442 self.lower_generics(generics, ImplTraitContext::disallowed()),
443 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
445 ItemKind::MacroDef(..) | ItemKind::Mac(..) => {
446 bug!("`TyMac` should have been expanded by now")
450 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
451 // not cause an assertion failure inside the `lower_defaultness` function.
459 vis: &mut hir::Visibility<'hir>,
461 attrs: &'hir [Attribute],
462 ) -> hir::ItemKind<'hir> {
463 debug!("lower_use_tree(tree={:?})", tree);
464 debug!("lower_use_tree: vis = {:?}", vis);
466 let path = &tree.prefix;
467 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
470 UseTreeKind::Simple(rename, id1, id2) => {
471 *ident = tree.ident();
473 // First, apply the prefix to the path.
474 let mut path = Path { segments, span: path.span };
476 // Correctly resolve `self` imports.
477 if path.segments.len() > 1
478 && path.segments.last().unwrap().ident.name == kw::SelfLower
480 let _ = path.segments.pop();
481 if rename.is_none() {
482 *ident = path.segments.last().unwrap().ident;
486 let mut resolutions = self.expect_full_res_from_use(id);
487 // We want to return *something* from this function, so hold onto the first item
489 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
491 // Here, we are looping over namespaces, if they exist for the definition
492 // being imported. We only handle type and value namespaces because we
493 // won't be dealing with macros in the rest of the compiler.
494 // Essentially a single `use` which imports two names is desugared into
496 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
498 let mut path = path.clone();
499 for seg in &mut path.segments {
500 seg.id = self.resolver.next_node_id();
502 let span = path.span;
504 self.with_hir_id_owner(new_node_id, |this| {
505 let new_id = this.lower_node_id(new_node_id);
506 let res = this.lower_res(res);
507 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
508 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
509 let vis = this.rebuild_vis(&vis);
511 this.insert_item(hir::Item {
522 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
523 hir::ItemKind::Use(path, hir::UseKind::Single)
525 UseTreeKind::Glob => {
527 self.lower_path(id, &Path { segments, span: path.span }, ParamMode::Explicit);
528 hir::ItemKind::Use(path, hir::UseKind::Glob)
530 UseTreeKind::Nested(ref trees) => {
531 // Nested imports are desugared into simple imports.
532 // So, if we start with
535 // pub(x) use foo::{a, b};
538 // we will create three items:
541 // pub(x) use foo::a;
542 // pub(x) use foo::b;
543 // pub(x) use foo::{}; // <-- this is called the `ListStem`
546 // The first two are produced by recursively invoking
547 // `lower_use_tree` (and indeed there may be things
548 // like `use foo::{a::{b, c}}` and so forth). They
549 // wind up being directly added to
550 // `self.items`. However, the structure of this
551 // function also requires us to return one item, and
552 // for that we return the `{}` import (called the
555 let prefix = Path { segments, span: prefix.span.to(path.span) };
557 // Add all the nested `PathListItem`s to the HIR.
558 for &(ref use_tree, id) in trees {
559 let new_hir_id = self.lower_node_id(id);
561 let mut prefix = prefix.clone();
563 // Give the segments new node-ids since they are being cloned.
564 for seg in &mut prefix.segments {
565 seg.id = self.resolver.next_node_id();
568 // Each `use` import is an item and thus are owners of the
569 // names in the path. Up to this point the nested import is
570 // the current owner, since we want each desugared import to
571 // own its own names, we have to adjust the owner before
572 // lowering the rest of the import.
573 self.with_hir_id_owner(id, |this| {
574 let mut vis = this.rebuild_vis(&vis);
575 let mut ident = *ident;
578 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
580 this.insert_item(hir::Item {
591 // Subtle and a bit hacky: we lower the privacy level
592 // of the list stem to "private" most of the time, but
593 // not for "restricted" paths. The key thing is that
594 // we don't want it to stay as `pub` (with no caveats)
595 // because that affects rustdoc and also the lints
596 // about `pub` items. But we can't *always* make it
597 // private -- particularly not for restricted paths --
598 // because it contains node-ids that would then be
599 // unused, failing the check that HirIds are "densely
602 hir::VisibilityKind::Public
603 | hir::VisibilityKind::Crate(_)
604 | hir::VisibilityKind::Inherited => {
605 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
607 hir::VisibilityKind::Restricted { .. } => {
608 // Do nothing here, as described in the comment on the match.
612 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
613 let res = self.lower_res(res);
614 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
615 hir::ItemKind::Use(path, hir::UseKind::ListStem)
620 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
621 /// many times in the HIR tree; for each occurrence, we need to assign distinct
622 /// `NodeId`s. (See, e.g., #56128.)
623 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
624 debug!("rebuild_use_path(path = {:?})", path);
626 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
628 hir_id: seg.hir_id.map(|_| self.next_id()),
631 infer_args: seg.infer_args,
633 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
636 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
637 let vis_kind = match vis.node {
638 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
639 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
640 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
641 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
642 hir::VisibilityKind::Restricted {
643 path: self.rebuild_use_path(path),
644 hir_id: self.next_id(),
648 respan(vis.span, vis_kind)
651 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
652 let def_id = self.resolver.definitions().local_def_id(i.id);
654 hir_id: self.lower_node_id(i.id),
656 attrs: self.lower_attrs(&i.attrs),
658 ForeignItemKind::Fn(ref sig, ref generics, _) => {
659 let fdec = &sig.decl;
660 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
663 AnonymousLifetimeMode::PassThrough,
666 // Disallow `impl Trait` in foreign items.
667 this.lower_fn_decl(fdec, None, false, None),
668 this.lower_fn_params_to_names(fdec),
673 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
675 ForeignItemKind::Static(ref t, m) => {
676 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
677 hir::ForeignItemKind::Static(ty, m)
679 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
680 ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"),
682 vis: self.lower_visibility(&i.vis, None),
687 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'hir> {
689 abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
690 items: self.arena.alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item(x))),
694 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm {
695 self.arena.alloc(hir::GlobalAsm { asm: ga.asm })
698 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
700 attrs: self.lower_attrs(&v.attrs),
701 data: self.lower_variant_data(&v.data),
702 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
703 id: self.lower_node_id(v.id),
709 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> {
711 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
713 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
716 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
718 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))),
719 self.lower_node_id(id),
721 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
725 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'hir> {
726 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
727 let t = self.lower_path_ty(
731 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
732 ImplTraitContext::disallowed(),
736 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
740 hir_id: self.lower_node_id(f.id),
741 ident: match f.ident {
742 Some(ident) => ident,
743 // FIXME(jseyfried): positional field hygiene.
744 None => Ident::new(sym::integer(index), f.span),
746 vis: self.lower_visibility(&f.vis, None),
748 attrs: self.lower_attrs(&f.attrs),
752 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
753 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
755 let (generics, kind) = match i.kind {
756 AssocItemKind::Const(ref ty, ref default) => {
757 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
758 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
761 hir::TraitItemKind::Const(
763 default.as_ref().map(|x| self.lower_const_body(i.span, Some(x))),
767 AssocItemKind::Fn(ref sig, None) => {
768 let names = self.lower_fn_params_to_names(&sig.decl);
769 let (generics, sig) =
770 self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
771 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
773 AssocItemKind::Fn(ref sig, Some(ref body)) => {
774 let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body));
775 let (generics, sig) =
776 self.lower_method_sig(&i.generics, sig, trait_item_def_id, false, None);
777 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
779 AssocItemKind::TyAlias(ref bounds, ref default) => {
780 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
781 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
782 let kind = hir::TraitItemKind::Type(
783 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
789 AssocItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
793 hir_id: self.lower_node_id(i.id),
795 attrs: self.lower_attrs(&i.attrs),
802 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
803 let (kind, has_default) = match i.kind {
804 AssocItemKind::Const(_, ref default) => (hir::AssocItemKind::Const, default.is_some()),
805 AssocItemKind::TyAlias(_, ref default) => (hir::AssocItemKind::Type, default.is_some()),
806 AssocItemKind::Fn(ref sig, ref default) => {
807 (hir::AssocItemKind::Method { has_self: sig.decl.has_self() }, default.is_some())
809 AssocItemKind::Macro(..) => unimplemented!(),
812 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
815 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
820 /// Construct `ExprKind::Err` for the given `span`.
821 fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
822 self.expr(span, hir::ExprKind::Err, AttrVec::new())
825 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
826 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
828 let (generics, kind) = match i.kind {
829 AssocItemKind::Const(ref ty, ref expr) => {
830 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
831 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
834 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
837 AssocItemKind::Fn(ref sig, ref body) => {
838 self.current_item = Some(i.span);
839 let body_id = self.lower_maybe_async_body(
842 sig.header.asyncness.node,
845 let impl_trait_return_allow = !self.is_in_trait_impl;
846 let (generics, sig) = self.lower_method_sig(
850 impl_trait_return_allow,
851 sig.header.asyncness.node.opt_return_id(),
854 (generics, hir::ImplItemKind::Method(sig, body_id))
856 AssocItemKind::TyAlias(_, ref ty) => {
857 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
858 let kind = match ty {
860 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
861 hir::ImplItemKind::TyAlias(ty)
863 Some(ty) => match ty.kind.opaque_top_hack() {
865 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
866 hir::ImplItemKind::TyAlias(ty)
869 let bs = self.lower_param_bounds(bs, ImplTraitContext::disallowed());
870 hir::ImplItemKind::OpaqueTy(bs)
876 AssocItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
880 hir_id: self.lower_node_id(i.id),
882 attrs: self.lower_attrs(&i.attrs),
884 vis: self.lower_visibility(&i.vis, None),
885 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
890 // [1] since `default impl` is not yet implemented, this is always true in impls
893 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
895 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
898 vis: self.lower_visibility(&i.vis, Some(i.id)),
899 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
900 kind: match &i.kind {
901 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
902 AssocItemKind::TyAlias(_, ty) => {
903 match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
904 None => hir::AssocItemKind::Type,
905 Some(_) => hir::AssocItemKind::OpaqueTy,
908 AssocItemKind::Fn(sig, _) => {
909 hir::AssocItemKind::Method { has_self: sig.decl.has_self() }
911 AssocItemKind::Macro(..) => unimplemented!(),
915 // [1] since `default impl` is not yet implemented, this is always true in impls
918 /// If an `explicit_owner` is given, this method allocates the `HirId` in
919 /// the address space of that item instead of the item currently being
920 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
921 /// lower a `Visibility` value although we haven't lowered the owning
922 /// `ImplItem` in question yet.
926 explicit_owner: Option<NodeId>,
927 ) -> hir::Visibility<'hir> {
928 let node = match v.node {
929 VisibilityKind::Public => hir::VisibilityKind::Public,
930 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
931 VisibilityKind::Restricted { ref path, id } => {
932 debug!("lower_visibility: restricted path id = {:?}", id);
933 let lowered_id = if let Some(owner) = explicit_owner {
934 self.lower_node_id_with_owner(id, owner)
936 self.lower_node_id(id)
938 let res = self.expect_full_res(id);
939 let res = self.lower_res(res);
940 hir::VisibilityKind::Restricted {
941 path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
945 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
950 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
952 Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
953 Defaultness::Final => {
955 hir::Defaultness::Final
962 params: &'hir [hir::Param<'hir>],
963 value: hir::Expr<'hir>,
965 let body = hir::Body { generator_kind: self.generator_kind, params, value };
967 self.bodies.insert(id, body);
973 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
975 let prev_gen_kind = self.generator_kind.take();
976 let (parameters, result) = f(self);
977 let body_id = self.record_body(parameters, result);
978 self.generator_kind = prev_gen_kind;
982 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
984 attrs: self.lower_attrs(¶m.attrs),
985 hir_id: self.lower_node_id(param.id),
986 pat: self.lower_pat(¶m.pat),
991 pub(super) fn lower_fn_body(
994 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
996 self.lower_body(|this| {
998 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1004 fn lower_fn_body_block(
1008 body: Option<&Block>,
1010 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1013 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1015 Some(block) => self.lower_block_expr(block),
1016 None => self.expr_err(span),
1020 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1021 self.lower_body(|this| {
1025 Some(expr) => this.lower_expr_mut(expr),
1026 None => this.expr_err(span),
1032 fn lower_maybe_async_body(
1037 body: Option<&Block>,
1039 let closure_id = match asyncness {
1040 IsAsync::Async { closure_id, .. } => closure_id,
1041 IsAsync::NotAsync => return self.lower_fn_body_block(span, decl, body),
1044 self.lower_body(|this| {
1045 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1046 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1048 // Async function parameters are lowered into the closure body so that they are
1049 // captured and so that the drop order matches the equivalent non-async functions.
1053 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1059 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1061 // let __arg2 = __arg2;
1062 // let <pattern> = __arg2;
1063 // let __arg1 = __arg1;
1064 // let <pattern> = __arg1;
1065 // let __arg0 = __arg0;
1066 // let <pattern> = __arg0;
1067 // drop-temps { <body> } // see comments later in fn for details
1071 // If `<pattern>` is a simple ident, then it is lowered to a single
1072 // `let <pattern> = <pattern>;` statement as an optimization.
1074 // Note that the body is embedded in `drop-temps`; an
1075 // equivalent desugaring would be `return { <body>
1076 // };`. The key point is that we wish to drop all the
1077 // let-bound variables and temporaries created in the body
1078 // (and its tail expression!) before we drop the
1079 // parameters (c.f. rust-lang/rust#64512).
1080 for (index, parameter) in decl.inputs.iter().enumerate() {
1081 let parameter = this.lower_param(parameter);
1082 let span = parameter.pat.span;
1084 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1085 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1086 let (ident, is_simple_parameter) = match parameter.pat.kind {
1087 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) => {
1091 // Replace the ident for bindings that aren't simple.
1092 let name = format!("__arg{}", index);
1093 let ident = Ident::from_str(&name);
1099 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1101 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1104 // If this is the simple case, this parameter will end up being the same as the
1105 // original parameter, but with a different pattern id.
1106 let mut stmt_attrs = AttrVec::new();
1107 stmt_attrs.extend(parameter.attrs.iter().cloned());
1108 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1109 let new_parameter = hir::Param {
1110 attrs: parameter.attrs,
1111 hir_id: parameter.hir_id,
1112 pat: new_parameter_pat,
1113 span: parameter.span,
1116 if is_simple_parameter {
1117 // If this is the simple case, then we only insert one statement that is
1118 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1119 // `HirId`s are densely assigned.
1120 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1121 let stmt = this.stmt_let_pat(
1126 hir::LocalSource::AsyncFn,
1128 statements.push(stmt);
1130 // If this is not the simple case, then we construct two statements:
1133 // let __argN = __argN;
1134 // let <pat> = __argN;
1137 // The first statement moves the parameter into the closure and thus ensures
1138 // that the drop order is correct.
1140 // The second statement creates the bindings that the user wrote.
1142 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1143 // because the user may have specified a `ref mut` binding in the next
1145 let (move_pat, move_id) = this.pat_ident_binding_mode(
1148 hir::BindingAnnotation::Mutable,
1150 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1151 let move_stmt = this.stmt_let_pat(
1156 hir::LocalSource::AsyncFn,
1159 // Construct the `let <pat> = __argN;` statement. We re-use the original
1160 // parameter's pattern so that `HirId`s are densely assigned.
1161 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1162 let pattern_stmt = this.stmt_let_pat(
1167 hir::LocalSource::AsyncFn,
1170 statements.push(move_stmt);
1171 statements.push(pattern_stmt);
1174 parameters.push(new_parameter);
1177 let body_span = body.map_or(span, |b| b.span);
1178 let async_expr = this.make_async_expr(
1183 hir::AsyncGeneratorKind::Fn,
1185 // Create a block from the user's function body:
1186 let user_body = this.lower_block_expr_opt(body_span, body);
1188 // Transform into `drop-temps { <user-body> }`, an expression:
1189 let desugared_span =
1190 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1191 let user_body = this.expr_drop_temps(
1193 this.arena.alloc(user_body),
1197 // As noted above, create the final block like
1201 // let $param_pattern = $raw_param;
1203 // drop-temps { <user-body> }
1206 let body = this.block_all(
1208 this.arena.alloc_from_iter(statements),
1212 this.expr_block(body, AttrVec::new())
1217 this.arena.alloc_from_iter(parameters),
1218 this.expr(body_span, async_expr, AttrVec::new()),
1223 fn lower_method_sig(
1225 generics: &Generics,
1228 impl_trait_return_allow: bool,
1229 is_async: Option<NodeId>,
1230 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1231 let header = self.lower_fn_header(sig.header);
1232 let (generics, decl) = self.add_in_band_defs(
1235 AnonymousLifetimeMode::PassThrough,
1239 Some((fn_def_id, idty)),
1240 impl_trait_return_allow,
1245 (generics, hir::FnSig { header, decl })
1248 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1250 unsafety: self.lower_unsafety(h.unsafety),
1251 asyncness: self.lower_asyncness(h.asyncness.node),
1252 constness: self.lower_constness(h.constness),
1253 abi: self.lower_extern(h.ext),
1257 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1258 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1259 self.error_on_invalid_abi(abi);
1264 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1266 Extern::None => abi::Abi::Rust,
1267 Extern::Implicit => abi::Abi::C,
1268 Extern::Explicit(abi) => self.lower_abi(abi),
1272 fn error_on_invalid_abi(&self, abi: StrLit) {
1273 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1274 .span_label(abi.span, "invalid ABI")
1275 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1279 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
1281 IsAsync::Async { .. } => hir::IsAsync::Async,
1282 IsAsync::NotAsync => hir::IsAsync::NotAsync,
1286 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1288 Const::Yes(_) => hir::Constness::Const,
1289 Const::No => hir::Constness::NotConst,
1293 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1295 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1296 Unsafe::No => hir::Unsafety::Normal,
1300 pub(super) fn lower_generics_mut(
1302 generics: &Generics,
1303 itctx: ImplTraitContext<'_, 'hir>,
1304 ) -> GenericsCtor<'hir> {
1305 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1306 // FIXME: this could probably be done with less rightward drift. It also looks like two
1307 // control paths where `report_error` is called are the only paths that advance to after the
1308 // match statement, so the error reporting could probably just be moved there.
1309 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1310 for pred in &generics.where_clause.predicates {
1311 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1312 'next_bound: for bound in &bound_pred.bounds {
1313 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1314 let report_error = |this: &mut Self| {
1315 this.diagnostic().span_err(
1316 bound_pred.bounded_ty.span,
1317 "`?Trait` bounds are only permitted at the \
1318 point where a type parameter is declared",
1321 // Check if the where clause type is a plain type parameter.
1322 match bound_pred.bounded_ty.kind {
1323 TyKind::Path(None, ref path)
1324 if path.segments.len() == 1
1325 && bound_pred.bound_generic_params.is_empty() =>
1327 if let Some(Res::Def(DefKind::TyParam, def_id)) = self
1329 .get_partial_res(bound_pred.bounded_ty.id)
1330 .map(|d| d.base_res())
1332 if let Some(node_id) =
1333 self.resolver.definitions().as_local_node_id(def_id)
1335 for param in &generics.params {
1337 GenericParamKind::Type { .. } => {
1338 if node_id == param.id {
1342 .push(bound.clone());
1343 continue 'next_bound;
1353 _ => report_error(self),
1361 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1362 where_clause: self.lower_where_clause(&generics.where_clause),
1363 span: generics.span,
1367 pub(super) fn lower_generics(
1369 generics: &Generics,
1370 itctx: ImplTraitContext<'_, 'hir>,
1371 ) -> hir::Generics<'hir> {
1372 let generics_ctor = self.lower_generics_mut(generics, itctx);
1373 generics_ctor.into_generics(self.arena)
1376 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1377 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1379 predicates: this.arena.alloc_from_iter(
1380 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1387 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1389 WherePredicate::BoundPredicate(WhereBoundPredicate {
1390 ref bound_generic_params,
1395 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1396 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1397 bound_generic_params: this.lower_generic_params(
1398 bound_generic_params,
1399 &NodeMap::default(),
1400 ImplTraitContext::disallowed(),
1402 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1403 bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| {
1405 // Ignore `?Trait` bounds.
1406 // They were copied into type parameters already.
1407 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1409 this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1417 WherePredicate::RegionPredicate(WhereRegionPredicate {
1421 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1423 lifetime: self.lower_lifetime(lifetime),
1424 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1426 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1427 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1428 hir_id: self.lower_node_id(id),
1429 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1430 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1438 /// Helper struct for delayed construction of Generics.
1439 pub(super) struct GenericsCtor<'hir> {
1440 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1441 where_clause: hir::WhereClause<'hir>,
1445 impl<'hir> GenericsCtor<'hir> {
1446 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1448 params: arena.alloc_from_iter(self.params),
1449 where_clause: self.where_clause,