1 use super::{AnonymousLifetimeMode, LoweringContext, ParamMode};
2 use super::{ImplTraitContext, ImplTraitPosition};
5 use rustc_ast::node_id::NodeMap;
7 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_errors::struct_span_err;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::LocalDefId;
14 use rustc_span::source_map::{respan, DesugaringKind};
15 use rustc_span::symbol::{kw, sym, Ident};
17 use rustc_target::spec::abi;
18 use smallvec::{smallvec, SmallVec};
24 pub(super) struct ItemLowerer<'a, 'lowering, 'hir> {
25 pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>,
28 impl ItemLowerer<'_, '_, '_> {
29 fn with_trait_impl_ref<T>(
31 impl_ref: &Option<TraitRef>,
32 f: impl FnOnce(&mut Self) -> T,
34 let old = self.lctx.is_in_trait_impl;
35 self.lctx.is_in_trait_impl = impl_ref.is_some();
37 self.lctx.is_in_trait_impl = old;
42 impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
43 fn visit_item(&mut self, item: &'a Item) {
44 let hir_id = self.lctx.with_hir_id_owner(item.id, |lctx| {
45 lctx.without_in_scope_lifetime_defs(|lctx| {
46 let hir_item = lctx.lower_item(item);
47 lctx.insert_item(hir_item)
51 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
52 let this = &mut ItemLowerer { lctx: this };
54 ItemKind::Mod(..) => {
55 let def_id = this.lctx.lower_node_id(item.id).expect_owner();
56 let old_current_module = mem::replace(&mut this.lctx.current_module, def_id);
57 visit::walk_item(this, item);
58 this.lctx.current_module = old_current_module;
60 ItemKind::Impl(box ImplKind { ref of_trait, .. }) => {
61 this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
63 _ => visit::walk_item(this, item),
68 fn visit_fn(&mut self, fk: FnKind<'a>, sp: Span, _: NodeId) {
70 FnKind::Fn(FnCtxt::Foreign, _, sig, _, _) => {
71 self.visit_fn_header(&sig.header);
72 visit::walk_fn_decl(self, &sig.decl);
73 // Don't visit the foreign function body even if it has one, since lowering the
74 // body would have no meaning and will have already been caught as a parse error.
76 _ => visit::walk_fn(self, fk, sp),
80 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
81 self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
83 let hir_item = lctx.lower_trait_item(item);
84 lctx.insert_trait_item(hir_item);
87 let hir_item = lctx.lower_impl_item(item);
88 lctx.insert_impl_item(hir_item);
92 visit::walk_assoc_item(self, item, ctxt);
95 fn visit_foreign_item(&mut self, item: &'a ForeignItem) {
96 self.lctx.allocate_hir_id_counter(item.id);
97 self.lctx.with_hir_id_owner(item.id, |lctx| {
98 let hir_item = lctx.lower_foreign_item(item);
99 lctx.insert_foreign_item(hir_item);
102 visit::walk_foreign_item(self, item);
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::ItemId,
115 f: impl FnOnce(&mut Self) -> T,
117 let old_len = self.in_scope_lifetimes.len();
119 let parent_generics = match self.owners[parent_hir_id.def_id].unwrap().expect_item().kind {
120 hir::ItemKind::Impl(hir::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.normalize_to_macros_2_0()),
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>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
140 let old_in_scope_lifetimes = mem::replace(&mut self.in_scope_lifetimes, vec![]);
142 // this vector is only used when walking over impl headers,
143 // input types, and the like, and should not be non-empty in
145 assert!(self.lifetimes_to_define.is_empty());
149 assert!(self.in_scope_lifetimes.is_empty());
150 self.in_scope_lifetimes = old_in_scope_lifetimes;
155 pub(super) fn lower_mod(&mut self, items: &[P<Item>], inner: Span) -> hir::Mod<'hir> {
157 inner: self.lower_span(inner),
158 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_id(x))),
162 pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
163 let node_ids = match i.kind {
164 ItemKind::Use(ref use_tree) => {
165 let mut vec = smallvec![i.id];
166 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
169 ItemKind::Fn(..) | ItemKind::Impl(box ImplKind { of_trait: None, .. }) => {
172 _ => smallvec![i.id],
177 .map(|node_id| hir::ItemId {
178 def_id: self.allocate_hir_id_counter(node_id).expect_owner(),
183 fn lower_item_id_use_tree(
187 vec: &mut SmallVec<[NodeId; 1]>,
190 UseTreeKind::Nested(ref nested_vec) => {
191 for &(ref nested, id) in nested_vec {
193 self.lower_item_id_use_tree(nested, id, vec);
196 UseTreeKind::Glob => {}
197 UseTreeKind::Simple(_, id1, id2) => {
199 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
207 pub fn lower_item(&mut self, i: &Item) -> hir::Item<'hir> {
208 let mut ident = i.ident;
209 let mut vis = self.lower_visibility(&i.vis, None);
210 let hir_id = self.lower_node_id(i.id);
211 let attrs = self.lower_attrs(hir_id, &i.attrs);
212 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
214 def_id: hir_id.expect_owner(),
215 ident: self.lower_ident(ident),
218 span: self.lower_span(i.span),
228 attrs: Option<&'hir [Attribute]>,
229 vis: &mut hir::Visibility<'hir>,
231 ) -> hir::ItemKind<'hir> {
233 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
234 ItemKind::Use(ref use_tree) => {
235 // Start with an empty prefix.
236 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
238 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
240 ItemKind::Static(ref t, m, ref e) => {
241 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
242 hir::ItemKind::Static(ty, m, body_id)
244 ItemKind::Const(_, ref t, ref e) => {
245 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
246 hir::ItemKind::Const(ty, body_id)
248 ItemKind::Fn(box FnKind(
250 FnSig { ref decl, header, span: fn_sig_span },
254 let fn_def_id = self.resolver.local_def_id(id);
255 self.with_new_scopes(|this| {
256 this.current_item = Some(ident.span);
258 // Note: we don't need to change the return type from `T` to
259 // `impl Future<Output = T>` here because lower_body
260 // only cares about the input argument patterns in the function
261 // declaration (decl), not the return types.
262 let asyncness = header.asyncness;
264 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
266 let (generics, decl) = this.add_in_band_defs(
269 AnonymousLifetimeMode::PassThrough,
271 let ret_id = asyncness.opt_return_id();
274 Some((fn_def_id.to_def_id(), idty)),
280 let sig = hir::FnSig {
282 header: this.lower_fn_header(header),
283 span: this.lower_span(fn_sig_span),
285 hir::ItemKind::Fn(sig, generics, body_id)
288 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
289 ModKind::Loaded(items, _, inner_span) => {
290 hir::ItemKind::Mod(self.lower_mod(items, *inner_span))
292 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
294 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
295 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
298 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
300 ItemKind::GlobalAsm(ref asm) => {
301 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
303 ItemKind::TyAlias(box TyAliasKind(_, ref gen, _, Some(ref ty))) => {
306 // type Foo = impl Trait
311 // opaque type Foo1: Trait
312 let ty = self.lower_ty(
314 ImplTraitContext::TypeAliasesOpaqueTy {
315 capturable_lifetimes: &mut FxHashSet::default(),
318 let generics = self.lower_generics(gen, ImplTraitContext::disallowed());
319 hir::ItemKind::TyAlias(ty, generics)
321 ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, None)) => {
322 let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
323 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
324 hir::ItemKind::TyAlias(ty, generics)
326 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
328 variants: self.arena.alloc_from_iter(
329 enum_definition.variants.iter().map(|x| self.lower_variant(x)),
332 self.lower_generics(generics, ImplTraitContext::disallowed()),
334 ItemKind::Struct(ref struct_def, ref generics) => {
335 let struct_def = self.lower_variant_data(hir_id, struct_def);
336 hir::ItemKind::Struct(
338 self.lower_generics(generics, ImplTraitContext::disallowed()),
341 ItemKind::Union(ref vdata, ref generics) => {
342 let vdata = self.lower_variant_data(hir_id, vdata);
343 hir::ItemKind::Union(
345 self.lower_generics(generics, ImplTraitContext::disallowed()),
348 ItemKind::Impl(box ImplKind {
353 generics: ref ast_generics,
354 of_trait: ref trait_ref,
356 items: ref impl_items,
358 // Lower the "impl header" first. This ordering is important
359 // for in-band lifetimes! Consider `'a` here:
361 // impl Foo<'a> for u32 {
362 // fn method(&'a self) { .. }
365 // Because we start by lowering the `Foo<'a> for u32`
366 // part, we will add `'a` to the list of generics on
367 // the impl. When we then encounter it later in the
368 // method, it will not be considered an in-band
369 // lifetime to be added, but rather a reference to a
371 let lowered_trait_def_id = self.lower_node_id(id).expect_owner();
372 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
374 lowered_trait_def_id,
375 AnonymousLifetimeMode::CreateParameter,
377 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
378 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
381 if let Some(ref trait_ref) = trait_ref {
382 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
386 .push(lowered_trait_def_id);
390 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
392 (trait_ref, lowered_ty)
397 self.with_in_scope_lifetime_defs(&ast_generics.params, |this| {
398 this.arena.alloc_from_iter(
399 impl_items.iter().map(|item| this.lower_impl_item_ref(item)),
403 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
404 // to not cause an assertion failure inside the `lower_defaultness` function.
406 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
407 let polarity = match polarity {
408 ImplPolarity::Positive => ImplPolarity::Positive,
409 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
411 hir::ItemKind::Impl(hir::Impl {
412 unsafety: self.lower_unsafety(unsafety),
416 constness: self.lower_constness(constness),
420 items: new_impl_items,
423 ItemKind::Trait(box TraitKind(
430 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
433 .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item)));
434 hir::ItemKind::Trait(
436 self.lower_unsafety(unsafety),
437 self.lower_generics(generics, ImplTraitContext::disallowed()),
442 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
443 self.lower_generics(generics, ImplTraitContext::disallowed()),
444 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
446 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
447 let body = P(self.lower_mac_args(body));
449 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules })
451 ItemKind::MacCall(..) => {
452 panic!("`TyMac` should have been expanded by now")
462 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
463 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Binding));
464 (ty, self.lower_const_body(span, body))
472 vis: &mut hir::Visibility<'hir>,
474 attrs: Option<&'hir [Attribute]>,
475 ) -> hir::ItemKind<'hir> {
476 debug!("lower_use_tree(tree={:?})", tree);
477 debug!("lower_use_tree: vis = {:?}", vis);
479 let path = &tree.prefix;
480 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
483 UseTreeKind::Simple(rename, id1, id2) => {
484 *ident = tree.ident();
486 // First, apply the prefix to the path.
487 let mut path = Path { segments, span: path.span, tokens: None };
489 // Correctly resolve `self` imports.
490 if path.segments.len() > 1
491 && path.segments.last().unwrap().ident.name == kw::SelfLower
493 let _ = path.segments.pop();
494 if rename.is_none() {
495 *ident = path.segments.last().unwrap().ident;
499 let mut resolutions = self.expect_full_res_from_use(id);
500 // We want to return *something* from this function, so hold onto the first item
502 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
504 // Here, we are looping over namespaces, if they exist for the definition
505 // being imported. We only handle type and value namespaces because we
506 // won't be dealing with macros in the rest of the compiler.
507 // Essentially a single `use` which imports two names is desugared into
509 for (res, &new_node_id) in iter::zip(resolutions, &[id1, id2]) {
511 let mut path = path.clone();
512 for seg in &mut path.segments {
513 seg.id = self.resolver.next_node_id();
515 let span = path.span;
517 self.with_hir_id_owner(new_node_id, |this| {
518 let new_id = this.lower_node_id(new_node_id);
519 let res = this.lower_res(res);
520 let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None);
521 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
522 let vis = this.rebuild_vis(&vis);
523 if let Some(attrs) = attrs {
524 this.attrs.insert(new_id, attrs);
527 this.insert_item(hir::Item {
528 def_id: new_id.expect_owner(),
529 ident: this.lower_ident(ident),
532 span: this.lower_span(span),
537 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None);
538 hir::ItemKind::Use(path, hir::UseKind::Single)
540 UseTreeKind::Glob => {
541 let path = self.lower_path(
543 &Path { segments, span: path.span, tokens: None },
546 hir::ItemKind::Use(path, hir::UseKind::Glob)
548 UseTreeKind::Nested(ref trees) => {
549 // Nested imports are desugared into simple imports.
550 // So, if we start with
553 // pub(x) use foo::{a, b};
556 // we will create three items:
559 // pub(x) use foo::a;
560 // pub(x) use foo::b;
561 // pub(x) use foo::{}; // <-- this is called the `ListStem`
564 // The first two are produced by recursively invoking
565 // `lower_use_tree` (and indeed there may be things
566 // like `use foo::{a::{b, c}}` and so forth). They
567 // wind up being directly added to
568 // `self.items`. However, the structure of this
569 // function also requires us to return one item, and
570 // for that we return the `{}` import (called the
573 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
575 // Add all the nested `PathListItem`s to the HIR.
576 for &(ref use_tree, id) in trees {
577 let new_hir_id = self.lower_node_id(id);
579 let mut prefix = prefix.clone();
581 // Give the segments new node-ids since they are being cloned.
582 for seg in &mut prefix.segments {
583 seg.id = self.resolver.next_node_id();
586 // Each `use` import is an item and thus are owners of the
587 // names in the path. Up to this point the nested import is
588 // the current owner, since we want each desugared import to
589 // own its own names, we have to adjust the owner before
590 // lowering the rest of the import.
591 self.with_hir_id_owner(id, |this| {
592 let mut vis = this.rebuild_vis(&vis);
593 let mut ident = *ident;
596 this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs);
597 if let Some(attrs) = attrs {
598 this.attrs.insert(new_hir_id, attrs);
601 this.insert_item(hir::Item {
602 def_id: new_hir_id.expect_owner(),
603 ident: this.lower_ident(ident),
606 span: this.lower_span(use_tree.span),
611 // Subtle and a bit hacky: we lower the privacy level
612 // of the list stem to "private" most of the time, but
613 // not for "restricted" paths. The key thing is that
614 // we don't want it to stay as `pub` (with no caveats)
615 // because that affects rustdoc and also the lints
616 // about `pub` items. But we can't *always* make it
617 // private -- particularly not for restricted paths --
618 // because it contains node-ids that would then be
619 // unused, failing the check that HirIds are "densely
622 hir::VisibilityKind::Public
623 | hir::VisibilityKind::Crate(_)
624 | hir::VisibilityKind::Inherited => {
626 self.lower_span(prefix.span.shrink_to_lo()),
627 hir::VisibilityKind::Inherited,
630 hir::VisibilityKind::Restricted { .. } => {
631 // Do nothing here, as described in the comment on the match.
635 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
636 let res = self.lower_res(res);
637 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None);
638 hir::ItemKind::Use(path, hir::UseKind::ListStem)
643 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
644 /// many times in the HIR tree; for each occurrence, we need to assign distinct
645 /// `NodeId`s. (See, e.g., #56128.)
646 fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> {
647 debug!("rebuild_use_path(path = {:?})", path);
649 self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment {
651 hir_id: seg.hir_id.map(|_| self.next_id()),
654 infer_args: seg.infer_args,
656 self.arena.alloc(hir::Path { span: path.span, res: path.res, segments })
659 fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> {
660 let vis_kind = match vis.node {
661 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
662 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
663 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
664 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
665 hir::VisibilityKind::Restricted {
666 path: self.rebuild_use_path(path),
667 hir_id: self.next_id(),
671 respan(self.lower_span(vis.span), vis_kind)
674 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
675 let hir_id = self.lower_node_id(i.id);
676 let def_id = hir_id.expect_owner();
677 self.lower_attrs(hir_id, &i.attrs);
680 ident: self.lower_ident(i.ident),
682 ForeignItemKind::Fn(box FnKind(_, ref sig, ref generics, _)) => {
683 let fdec = &sig.decl;
684 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
687 AnonymousLifetimeMode::PassThrough,
690 // Disallow `impl Trait` in foreign items.
691 this.lower_fn_decl(fdec, None, false, None),
692 this.lower_fn_params_to_names(fdec),
697 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
699 ForeignItemKind::Static(ref t, m, _) => {
700 let ty = self.lower_ty(t, ImplTraitContext::disallowed());
701 hir::ForeignItemKind::Static(ty, m)
703 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
704 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
706 vis: self.lower_visibility(&i.vis, None),
707 span: self.lower_span(i.span),
711 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef<'hir> {
712 hir::ForeignItemRef {
713 id: hir::ForeignItemId { def_id: self.lower_node_id(i.id).expect_owner() },
714 ident: self.lower_ident(i.ident),
715 span: self.lower_span(i.span),
716 vis: self.lower_visibility(&i.vis, Some(i.id)),
720 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
721 let id = self.lower_node_id(v.id);
722 self.lower_attrs(id, &v.attrs);
725 data: self.lower_variant_data(id, &v.data),
726 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
727 ident: self.lower_ident(v.ident),
728 span: self.lower_span(v.span),
732 fn lower_variant_data(
734 parent_id: hir::HirId,
736 ) -> hir::VariantData<'hir> {
738 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
740 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
743 VariantData::Tuple(ref fields, id) => {
744 let ctor_id = self.lower_node_id(id);
745 self.alias_attrs(ctor_id, parent_id);
746 hir::VariantData::Tuple(
747 self.arena.alloc_from_iter(
748 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
753 VariantData::Unit(id) => {
754 let ctor_id = self.lower_node_id(id);
755 self.alias_attrs(ctor_id, parent_id);
756 hir::VariantData::Unit(ctor_id)
761 pub(super) fn lower_field_def(
763 (index, f): (usize, &FieldDef),
764 ) -> hir::FieldDef<'hir> {
765 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
766 let t = self.lower_path_ty(
770 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
771 ImplTraitContext::disallowed(),
775 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
777 let hir_id = self.lower_node_id(f.id);
778 self.lower_attrs(hir_id, &f.attrs);
780 span: self.lower_span(f.span),
782 ident: match f.ident {
783 Some(ident) => self.lower_ident(ident),
784 // FIXME(jseyfried): positional field hygiene.
785 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
787 vis: self.lower_visibility(&f.vis, None),
792 fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
793 let hir_id = self.lower_node_id(i.id);
794 let trait_item_def_id = hir_id.expect_owner();
796 let (generics, kind) = match i.kind {
797 AssocItemKind::Const(_, ref ty, ref default) => {
798 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
799 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
800 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
802 AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, None)) => {
803 let names = self.lower_fn_params_to_names(&sig.decl);
804 let (generics, sig) =
805 self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
806 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
808 AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, Some(ref body))) => {
809 let asyncness = sig.header.asyncness;
811 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
812 let (generics, sig) = self.lower_method_sig(
817 asyncness.opt_return_id(),
819 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
821 AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref default)) => {
822 let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
823 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
824 let kind = hir::TraitItemKind::Type(
825 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
831 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
834 self.lower_attrs(hir_id, &i.attrs);
836 def_id: trait_item_def_id,
837 ident: self.lower_ident(i.ident),
840 span: self.lower_span(i.span),
844 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
845 let (kind, has_default) = match &i.kind {
846 AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
847 AssocItemKind::TyAlias(box TyAliasKind(_, _, _, default)) => {
848 (hir::AssocItemKind::Type, default.is_some())
850 AssocItemKind::Fn(box FnKind(_, sig, _, default)) => {
851 (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, default.is_some())
853 AssocItemKind::MacCall(..) => unimplemented!(),
855 let id = hir::TraitItemId { def_id: self.lower_node_id(i.id).expect_owner() };
856 let defaultness = hir::Defaultness::Default { has_value: has_default };
859 ident: self.lower_ident(i.ident),
860 span: self.lower_span(i.span),
866 /// Construct `ExprKind::Err` for the given `span`.
867 crate fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
868 self.expr(span, hir::ExprKind::Err, AttrVec::new())
871 fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
872 let impl_item_def_id = self.resolver.local_def_id(i.id);
874 let (generics, kind) = match &i.kind {
875 AssocItemKind::Const(_, ty, expr) => {
876 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
878 hir::Generics::empty(),
879 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
882 AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => {
883 self.current_item = Some(i.span);
884 let asyncness = sig.header.asyncness;
886 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
887 let impl_trait_return_allow = !self.is_in_trait_impl;
888 let (generics, sig) = self.lower_method_sig(
892 impl_trait_return_allow,
893 asyncness.opt_return_id(),
896 (generics, hir::ImplItemKind::Fn(sig, body_id))
898 AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, ty)) => {
899 let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
900 let kind = match ty {
902 let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err));
903 hir::ImplItemKind::TyAlias(ty)
906 let ty = self.lower_ty(
908 ImplTraitContext::TypeAliasesOpaqueTy {
909 capturable_lifetimes: &mut FxHashSet::default(),
912 hir::ImplItemKind::TyAlias(ty)
917 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
920 // Since `default impl` is not yet implemented, this is always true in impls.
921 let has_value = true;
922 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
923 let hir_id = self.lower_node_id(i.id);
924 self.lower_attrs(hir_id, &i.attrs);
926 def_id: hir_id.expect_owner(),
927 ident: self.lower_ident(i.ident),
929 vis: self.lower_visibility(&i.vis, None),
932 span: self.lower_span(i.span),
936 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> {
937 // Since `default impl` is not yet implemented, this is always true in impls.
938 let has_value = true;
939 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
941 id: hir::ImplItemId { def_id: self.lower_node_id(i.id).expect_owner() },
942 ident: self.lower_ident(i.ident),
943 span: self.lower_span(i.span),
944 vis: self.lower_visibility(&i.vis, Some(i.id)),
946 kind: match &i.kind {
947 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
948 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
949 AssocItemKind::Fn(box FnKind(_, sig, ..)) => {
950 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
952 AssocItemKind::MacCall(..) => unimplemented!(),
957 /// If an `explicit_owner` is given, this method allocates the `HirId` in
958 /// the address space of that item instead of the item currently being
959 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
960 /// lower a `Visibility` value although we haven't lowered the owning
961 /// `ImplItem` in question yet.
965 explicit_owner: Option<NodeId>,
966 ) -> hir::Visibility<'hir> {
967 let node = match v.kind {
968 VisibilityKind::Public => hir::VisibilityKind::Public,
969 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
970 VisibilityKind::Restricted { ref path, id } => {
971 debug!("lower_visibility: restricted path id = {:?}", id);
972 let lowered_id = if let Some(owner) = explicit_owner {
973 self.lower_node_id_with_owner(id, owner)
975 self.lower_node_id(id)
977 let res = self.expect_full_res(id);
978 let res = self.lower_res(res);
979 hir::VisibilityKind::Restricted {
980 path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner),
984 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
986 respan(self.lower_span(v.span), node)
989 fn lower_defaultness(
993 ) -> (hir::Defaultness, Option<Span>) {
995 Defaultness::Default(sp) => {
996 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
998 Defaultness::Final => {
1000 (hir::Defaultness::Final, None)
1007 params: &'hir [hir::Param<'hir>],
1008 value: hir::Expr<'hir>,
1010 let body = hir::Body { generator_kind: self.generator_kind, params, value };
1012 self.bodies.insert(id, body);
1016 pub(super) fn lower_body(
1018 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1020 let prev_gen_kind = self.generator_kind.take();
1021 let task_context = self.task_context.take();
1022 let (parameters, result) = f(self);
1023 let body_id = self.record_body(parameters, result);
1024 self.task_context = task_context;
1025 self.generator_kind = prev_gen_kind;
1029 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1030 let hir_id = self.lower_node_id(param.id);
1031 self.lower_attrs(hir_id, ¶m.attrs);
1034 pat: self.lower_pat(¶m.pat),
1035 ty_span: self.lower_span(param.ty.span),
1036 span: self.lower_span(param.span),
1040 pub(super) fn lower_fn_body(
1043 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1045 self.lower_body(|this| {
1047 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1053 fn lower_fn_body_block(
1057 body: Option<&Block>,
1059 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1062 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1064 Some(block) => self.lower_block_expr(block),
1065 None => self.expr_err(span),
1069 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1070 self.lower_body(|this| {
1074 Some(expr) => this.lower_expr_mut(expr),
1075 None => this.expr_err(span),
1081 fn lower_maybe_async_body(
1086 body: Option<&Block>,
1088 let closure_id = match asyncness {
1089 Async::Yes { closure_id, .. } => closure_id,
1090 Async::No => return self.lower_fn_body_block(span, decl, body),
1093 self.lower_body(|this| {
1094 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1095 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1097 // Async function parameters are lowered into the closure body so that they are
1098 // captured and so that the drop order matches the equivalent non-async functions.
1102 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1108 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1110 // let __arg2 = __arg2;
1111 // let <pattern> = __arg2;
1112 // let __arg1 = __arg1;
1113 // let <pattern> = __arg1;
1114 // let __arg0 = __arg0;
1115 // let <pattern> = __arg0;
1116 // drop-temps { <body> } // see comments later in fn for details
1120 // If `<pattern>` is a simple ident, then it is lowered to a single
1121 // `let <pattern> = <pattern>;` statement as an optimization.
1123 // Note that the body is embedded in `drop-temps`; an
1124 // equivalent desugaring would be `return { <body>
1125 // };`. The key point is that we wish to drop all the
1126 // let-bound variables and temporaries created in the body
1127 // (and its tail expression!) before we drop the
1128 // parameters (c.f. rust-lang/rust#64512).
1129 for (index, parameter) in decl.inputs.iter().enumerate() {
1130 let parameter = this.lower_param(parameter);
1131 let span = parameter.pat.span;
1133 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1134 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1135 let (ident, is_simple_parameter) = match parameter.pat.kind {
1136 hir::PatKind::Binding(
1137 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
1142 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1143 // we can keep the same name for the parameter.
1144 // This lets rustdoc render it correctly in documentation.
1145 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1146 hir::PatKind::Wild => {
1147 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1150 // Replace the ident for bindings that aren't simple.
1151 let name = format!("__arg{}", index);
1152 let ident = Ident::from_str(&name);
1158 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1160 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1163 // If this is the simple case, this parameter will end up being the same as the
1164 // original parameter, but with a different pattern id.
1165 let stmt_attrs = this.attrs.get(¶meter.hir_id).copied();
1166 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1167 let new_parameter = hir::Param {
1168 hir_id: parameter.hir_id,
1169 pat: new_parameter_pat,
1170 ty_span: this.lower_span(parameter.ty_span),
1171 span: this.lower_span(parameter.span),
1174 if is_simple_parameter {
1175 // If this is the simple case, then we only insert one statement that is
1176 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1177 // `HirId`s are densely assigned.
1178 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1179 let stmt = this.stmt_let_pat(
1184 hir::LocalSource::AsyncFn,
1186 statements.push(stmt);
1188 // If this is not the simple case, then we construct two statements:
1191 // let __argN = __argN;
1192 // let <pat> = __argN;
1195 // The first statement moves the parameter into the closure and thus ensures
1196 // that the drop order is correct.
1198 // The second statement creates the bindings that the user wrote.
1200 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1201 // because the user may have specified a `ref mut` binding in the next
1203 let (move_pat, move_id) = this.pat_ident_binding_mode(
1206 hir::BindingAnnotation::Mutable,
1208 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1209 let move_stmt = this.stmt_let_pat(
1214 hir::LocalSource::AsyncFn,
1217 // Construct the `let <pat> = __argN;` statement. We re-use the original
1218 // parameter's pattern so that `HirId`s are densely assigned.
1219 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1220 let pattern_stmt = this.stmt_let_pat(
1225 hir::LocalSource::AsyncFn,
1228 statements.push(move_stmt);
1229 statements.push(pattern_stmt);
1232 parameters.push(new_parameter);
1235 let body_span = body.map_or(span, |b| b.span);
1236 let async_expr = this.make_async_expr(
1241 hir::AsyncGeneratorKind::Fn,
1243 // Create a block from the user's function body:
1244 let user_body = this.lower_block_expr_opt(body_span, body);
1246 // Transform into `drop-temps { <user-body> }`, an expression:
1247 let desugared_span =
1248 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1249 let user_body = this.expr_drop_temps(
1251 this.arena.alloc(user_body),
1255 // As noted above, create the final block like
1259 // let $param_pattern = $raw_param;
1261 // drop-temps { <user-body> }
1264 let body = this.block_all(
1266 this.arena.alloc_from_iter(statements),
1270 this.expr_block(body, AttrVec::new())
1275 this.arena.alloc_from_iter(parameters),
1276 this.expr(body_span, async_expr, AttrVec::new()),
1281 fn lower_method_sig(
1283 generics: &Generics,
1285 fn_def_id: LocalDefId,
1286 impl_trait_return_allow: bool,
1287 is_async: Option<NodeId>,
1288 ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) {
1289 let header = self.lower_fn_header(sig.header);
1290 let (generics, decl) = self.add_in_band_defs(
1293 AnonymousLifetimeMode::PassThrough,
1297 Some((fn_def_id.to_def_id(), idty)),
1298 impl_trait_return_allow,
1303 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1306 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1308 unsafety: self.lower_unsafety(h.unsafety),
1309 asyncness: self.lower_asyncness(h.asyncness),
1310 constness: self.lower_constness(h.constness),
1311 abi: self.lower_extern(h.ext),
1315 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1316 abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1317 self.error_on_invalid_abi(abi);
1322 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1324 Extern::None => abi::Abi::Rust,
1325 Extern::Implicit => abi::Abi::FALLBACK,
1326 Extern::Explicit(abi) => self.lower_abi(abi),
1330 fn error_on_invalid_abi(&self, abi: StrLit) {
1331 struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol)
1332 .span_label(abi.span, "invalid ABI")
1333 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1337 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1339 Async::Yes { .. } => hir::IsAsync::Async,
1340 Async::No => hir::IsAsync::NotAsync,
1344 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1346 Const::Yes(_) => hir::Constness::Const,
1347 Const::No => hir::Constness::NotConst,
1351 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1353 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1354 Unsafe::No => hir::Unsafety::Normal,
1358 pub(super) fn lower_generics_mut(
1360 generics: &Generics,
1361 itctx: ImplTraitContext<'_, 'hir>,
1362 ) -> GenericsCtor<'hir> {
1363 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1364 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
1365 for pred in &generics.where_clause.predicates {
1366 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1367 'next_bound: for bound in &bound_pred.bounds {
1368 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
1369 // Check if the where clause type is a plain type parameter.
1372 .get_partial_res(bound_pred.bounded_ty.id)
1373 .map(|d| (d.base_res(), d.unresolved_segments()))
1375 Some((Res::Def(DefKind::TyParam, def_id), 0))
1376 if bound_pred.bound_generic_params.is_empty() =>
1378 for param in &generics.params {
1379 if def_id == self.resolver.local_def_id(param.id).to_def_id() {
1380 add_bounds.entry(param.id).or_default().push(bound.clone());
1381 continue 'next_bound;
1387 self.diagnostic().span_err(
1388 bound_pred.bounded_ty.span,
1389 "`?Trait` bounds are only permitted at the \
1390 point where a type parameter is declared",
1398 params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(),
1399 where_clause: self.lower_where_clause(&generics.where_clause),
1400 span: self.lower_span(generics.span),
1404 pub(super) fn lower_generics(
1406 generics: &Generics,
1407 itctx: ImplTraitContext<'_, 'hir>,
1408 ) -> hir::Generics<'hir> {
1409 let generics_ctor = self.lower_generics_mut(generics, itctx);
1410 generics_ctor.into_generics(self.arena)
1413 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> {
1414 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1416 predicates: this.arena.alloc_from_iter(
1417 wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)),
1419 span: this.lower_span(wc.span),
1424 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1426 WherePredicate::BoundPredicate(WhereBoundPredicate {
1427 ref bound_generic_params,
1432 self.with_in_scope_lifetime_defs(&bound_generic_params, |this| {
1433 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1434 bound_generic_params: this.lower_generic_params(
1435 bound_generic_params,
1436 &NodeMap::default(),
1437 ImplTraitContext::disallowed(),
1439 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
1440 bounds: this.arena.alloc_from_iter(bounds.iter().map(
1441 |bound| match bound {
1442 // We used to ignore `?Trait` bounds, as they were copied into type
1443 // parameters already, but we need to keep them around only for
1444 // diagnostics when we suggest removal of `?Sized` bounds. See
1445 // `suggest_constraining_type_param`. This will need to change if
1446 // we ever allow something *other* than `?Sized`.
1447 GenericBound::Trait(p, TraitBoundModifier::Maybe) => {
1448 hir::GenericBound::Unsized(this.lower_span(p.span))
1450 _ => this.lower_param_bound(bound, ImplTraitContext::disallowed()),
1453 span: this.lower_span(span),
1457 WherePredicate::RegionPredicate(WhereRegionPredicate {
1461 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1462 span: self.lower_span(span),
1463 lifetime: self.lower_lifetime(lifetime),
1464 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
1466 WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
1467 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1468 hir_id: self.lower_node_id(id),
1469 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
1470 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
1471 span: self.lower_span(span),
1478 /// Helper struct for delayed construction of Generics.
1479 pub(super) struct GenericsCtor<'hir> {
1480 pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>,
1481 where_clause: hir::WhereClause<'hir>,
1485 impl<'hir> GenericsCtor<'hir> {
1486 pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> {
1488 params: arena.alloc_from_iter(self.params),
1489 where_clause: self.where_clause,