1 use super::errors::{InvalidAbi, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
7 use rustc_ast::visit::AssocCtxt;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::sorted_map::SortedMap;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
14 use rustc_hir::PredicateOrigin;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
17 use rustc_span::source_map::DesugaringKind;
18 use rustc_span::symbol::{kw, sym, Ident};
20 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
25 pub(super) struct ItemLowerer<'a, 'hir> {
26 pub(super) tcx: TyCtxt<'hir>,
27 pub(super) resolver: &'a mut ResolverAstLowering,
28 pub(super) ast_arena: &'a Arena<'static>,
29 pub(super) ast_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
30 pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
33 /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
34 /// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
35 /// clause if it exists.
36 fn add_ty_alias_where_clause(
37 generics: &mut ast::Generics,
38 mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
42 where_clauses = (where_clauses.1, where_clauses.0);
44 if where_clauses.0.0 || !where_clauses.1.0 {
45 generics.where_clause.has_where_token = where_clauses.0.0;
46 generics.where_clause.span = where_clauses.0.1;
48 generics.where_clause.has_where_token = where_clauses.1.0;
49 generics.where_clause.span = where_clauses.1.1;
53 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
57 f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
59 let mut lctx = LoweringContext {
62 resolver: self.resolver,
63 arena: self.tcx.hir_arena,
64 ast_arena: self.ast_arena,
68 attrs: SortedMap::default(),
69 children: FxHashMap::default(),
70 current_hir_id_owner: CRATE_DEF_ID,
71 item_local_id_counter: hir::ItemLocalId::new(0),
72 node_id_to_local_id: Default::default(),
73 local_id_to_def_id: SortedMap::new(),
74 trait_map: Default::default(),
79 is_in_loop_condition: false,
80 is_in_trait_impl: false,
81 is_in_dyn_type: false,
85 impl_trait_defs: Vec::new(),
86 impl_trait_bounds: Vec::new(),
87 allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
88 allow_gen_future: Some([sym::gen_future][..].into()),
89 allow_into_future: Some([sym::into_future][..].into()),
90 generics_def_id_map: Default::default(),
92 lctx.with_hir_id_owner(owner, |lctx| f(lctx));
94 for (def_id, info) in lctx.children {
95 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
96 debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
97 self.owners[def_id] = info;
101 pub(super) fn lower_node(
104 ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
105 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
106 if let hir::MaybeOwner::Phantom = self.owners[def_id] {
107 let node = self.ast_index[def_id];
109 AstOwner::NonOwner => {}
110 AstOwner::Crate(c) => self.lower_crate(c),
111 AstOwner::Item(item) => self.lower_item(item),
112 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
113 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
120 #[instrument(level = "debug", skip(self, c))]
121 fn lower_crate(&mut self, c: &Crate) {
122 debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
123 self.with_lctx(CRATE_NODE_ID, |lctx| {
124 let module = lctx.lower_mod(&c.items, &c.spans);
125 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
126 hir::OwnerNode::Crate(module)
130 #[instrument(level = "debug", skip(self))]
131 fn lower_item(&mut self, item: &Item) {
132 self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
135 fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
136 let def_id = self.resolver.node_id_to_def_id[&item.id];
138 let parent_id = self.tcx.local_parent(def_id);
139 let parent_hir = self.lower_node(parent_id).unwrap();
140 self.with_lctx(item.id, |lctx| {
141 // Evaluate with the lifetimes in `params` in-scope.
142 // This is used to track which lifetimes have already been defined,
143 // and which need to be replicated when lowering an async fn.
144 match parent_hir.node().expect_item().kind {
145 hir::ItemKind::Impl(hir::Impl { ref of_trait, .. }) => {
146 lctx.is_in_trait_impl = of_trait.is_some();
152 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
153 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
158 fn lower_foreign_item(&mut self, item: &ForeignItem) {
159 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
163 impl<'hir> LoweringContext<'_, 'hir> {
164 pub(super) fn lower_mod(
168 ) -> &'hir hir::Mod<'hir> {
169 self.arena.alloc(hir::Mod {
170 spans: hir::ModSpans {
171 inner_span: self.lower_span(spans.inner_span),
172 inject_use_span: self.lower_span(spans.inject_use_span),
174 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
178 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
179 let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }];
180 if let ItemKind::Use(ref use_tree) = &i.kind {
181 self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
186 fn lower_item_id_use_tree(
190 vec: &mut SmallVec<[hir::ItemId; 1]>,
193 UseTreeKind::Nested(ref nested_vec) => {
194 for &(ref nested, id) in nested_vec {
195 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
196 self.lower_item_id_use_tree(nested, id, vec);
199 UseTreeKind::Glob => {}
200 UseTreeKind::Simple(_, id1, id2) => {
202 iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
204 vec.push(hir::ItemId { def_id: self.local_def_id(id) });
210 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
211 let mut ident = i.ident;
212 let vis_span = self.lower_span(i.vis.span);
213 let hir_id = self.lower_node_id(i.id);
214 let attrs = self.lower_attrs(hir_id, &i.attrs);
215 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
216 let item = hir::Item {
217 def_id: hir_id.expect_owner(),
218 ident: self.lower_ident(ident),
221 span: self.lower_span(i.span),
223 self.arena.alloc(item)
232 attrs: Option<&'hir [Attribute]>,
235 ) -> hir::ItemKind<'hir> {
237 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
238 ItemKind::Use(ref use_tree) => {
239 // Start with an empty prefix.
240 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
242 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
244 ItemKind::Static(ref t, m, ref e) => {
245 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
246 hir::ItemKind::Static(ty, m, body_id)
248 ItemKind::Const(_, ref t, ref e) => {
249 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
250 hir::ItemKind::Const(ty, body_id)
252 ItemKind::Fn(box Fn {
253 sig: FnSig { ref decl, header, span: fn_sig_span },
258 self.with_new_scopes(|this| {
259 this.current_item = Some(ident.span);
261 // Note: we don't need to change the return type from `T` to
262 // `impl Future<Output = T>` here because lower_body
263 // only cares about the input argument patterns in the function
264 // declaration (decl), not the return types.
265 let asyncness = header.asyncness;
267 this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
269 let itctx = ImplTraitContext::Universal;
270 let (generics, decl) = this.lower_generics(generics, id, itctx, |this| {
271 let ret_id = asyncness.opt_return_id();
272 this.lower_fn_decl(&decl, Some(id), FnDeclKind::Fn, ret_id)
274 let sig = hir::FnSig {
276 header: this.lower_fn_header(header),
277 span: this.lower_span(fn_sig_span),
279 hir::ItemKind::Fn(sig, generics, body_id)
282 ItemKind::Mod(_, ref mod_kind) => match mod_kind {
283 ModKind::Loaded(items, _, spans) => {
284 hir::ItemKind::Mod(self.lower_mod(items, spans))
286 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
288 ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
289 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
292 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
294 ItemKind::GlobalAsm(ref asm) => {
295 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
297 ItemKind::TyAlias(box TyAlias {
305 // type Foo = impl Trait
310 // opaque type Foo1: Trait
311 let mut generics = generics.clone();
312 add_ty_alias_where_clause(&mut generics, where_clauses, true);
313 let (generics, ty) = self.lower_generics(
316 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
317 |this| this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy),
319 hir::ItemKind::TyAlias(ty, generics)
321 ItemKind::TyAlias(box TyAlias {
322 ref generics, ref where_clauses, ty: None, ..
324 let mut generics = generics.clone();
325 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
326 let (generics, ty) = self.lower_generics(
329 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
330 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
332 hir::ItemKind::TyAlias(ty, generics)
334 ItemKind::Enum(ref enum_definition, ref generics) => {
335 let (generics, variants) = self.lower_generics(
338 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
340 this.arena.alloc_from_iter(
341 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
345 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
347 ItemKind::Struct(ref struct_def, ref generics) => {
348 let (generics, struct_def) = self.lower_generics(
351 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
352 |this| this.lower_variant_data(hir_id, struct_def),
354 hir::ItemKind::Struct(struct_def, generics)
356 ItemKind::Union(ref vdata, ref generics) => {
357 let (generics, vdata) = self.lower_generics(
360 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
361 |this| this.lower_variant_data(hir_id, vdata),
363 hir::ItemKind::Union(vdata, generics)
365 ItemKind::Impl(box Impl {
370 generics: ref ast_generics,
371 of_trait: ref trait_ref,
373 items: ref impl_items,
375 // Lower the "impl header" first. This ordering is important
376 // for in-band lifetimes! Consider `'a` here:
378 // impl Foo<'a> for u32 {
379 // fn method(&'a self) { .. }
382 // Because we start by lowering the `Foo<'a> for u32`
383 // part, we will add `'a` to the list of generics on
384 // the impl. When we then encounter it later in the
385 // method, it will not be considered an in-band
386 // lifetime to be added, but rather a reference to a
388 let itctx = ImplTraitContext::Universal;
389 let (generics, (trait_ref, lowered_ty)) =
390 self.lower_generics(ast_generics, id, itctx, |this| {
391 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
392 this.lower_trait_ref(
394 ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
398 let lowered_ty = this
399 .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
401 (trait_ref, lowered_ty)
404 let new_impl_items = self
406 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
408 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
409 // to not cause an assertion failure inside the `lower_defaultness` function.
411 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
412 let polarity = match polarity {
413 ImplPolarity::Positive => ImplPolarity::Positive,
414 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
416 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
417 unsafety: self.lower_unsafety(unsafety),
421 constness: self.lower_constness(constness),
425 items: new_impl_items,
428 ItemKind::Trait(box Trait {
435 let (generics, (unsafety, items, bounds)) = self.lower_generics(
438 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
440 let bounds = this.lower_param_bounds(
442 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
444 let items = this.arena.alloc_from_iter(
445 items.iter().map(|item| this.lower_trait_item_ref(item)),
447 let unsafety = this.lower_unsafety(unsafety);
448 (unsafety, items, bounds)
451 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
453 ItemKind::TraitAlias(ref generics, ref bounds) => {
454 let (generics, bounds) = self.lower_generics(
457 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
459 this.lower_param_bounds(
461 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
465 hir::ItemKind::TraitAlias(generics, bounds)
467 ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
468 let body = P(self.lower_mac_args(body));
469 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
470 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
472 ItemKind::MacCall(..) => {
473 panic!("`TyMac` should have been expanded by now")
483 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
484 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
485 (ty, self.lower_const_body(span, body))
488 #[instrument(level = "debug", skip(self))]
496 attrs: Option<&'hir [Attribute]>,
497 ) -> hir::ItemKind<'hir> {
498 let path = &tree.prefix;
499 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
502 UseTreeKind::Simple(rename, id1, id2) => {
503 *ident = tree.ident();
505 // First, apply the prefix to the path.
506 let mut path = Path { segments, span: path.span, tokens: None };
508 // Correctly resolve `self` imports.
509 if path.segments.len() > 1
510 && path.segments.last().unwrap().ident.name == kw::SelfLower
512 let _ = path.segments.pop();
513 if rename.is_none() {
514 *ident = path.segments.last().unwrap().ident;
518 let mut resolutions = self.expect_full_res_from_use(id).fuse();
519 // We want to return *something* from this function, so hold onto the first item
521 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
523 // Here, we are looping over namespaces, if they exist for the definition
524 // being imported. We only handle type and value namespaces because we
525 // won't be dealing with macros in the rest of the compiler.
526 // Essentially a single `use` which imports two names is desugared into
528 for new_node_id in [id1, id2] {
529 let new_id = self.local_def_id(new_node_id);
530 let Some(res) = resolutions.next() else {
531 // Associate an HirId to both ids even if there is no resolution.
532 let _old = self.children.insert(
534 hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
536 debug_assert!(_old.is_none());
540 let mut path = path.clone();
541 for seg in &mut path.segments {
542 seg.id = self.next_node_id();
544 let span = path.span;
546 self.with_hir_id_owner(new_node_id, |this| {
547 let res = this.lower_res(res);
548 let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
549 let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
550 if let Some(attrs) = attrs {
551 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
554 let item = hir::Item {
556 ident: this.lower_ident(ident),
559 span: this.lower_span(span),
561 hir::OwnerNode::Item(this.arena.alloc(item))
565 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
566 hir::ItemKind::Use(path, hir::UseKind::Single)
568 UseTreeKind::Glob => {
569 let path = self.lower_path(
571 &Path { segments, span: path.span, tokens: None },
574 hir::ItemKind::Use(path, hir::UseKind::Glob)
576 UseTreeKind::Nested(ref trees) => {
577 // Nested imports are desugared into simple imports.
578 // So, if we start with
581 // pub(x) use foo::{a, b};
584 // we will create three items:
587 // pub(x) use foo::a;
588 // pub(x) use foo::b;
589 // pub(x) use foo::{}; // <-- this is called the `ListStem`
592 // The first two are produced by recursively invoking
593 // `lower_use_tree` (and indeed there may be things
594 // like `use foo::{a::{b, c}}` and so forth). They
595 // wind up being directly added to
596 // `self.items`. However, the structure of this
597 // function also requires us to return one item, and
598 // for that we return the `{}` import (called the
601 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
603 // Add all the nested `PathListItem`s to the HIR.
604 for &(ref use_tree, id) in trees {
605 let new_hir_id = self.local_def_id(id);
607 let mut prefix = prefix.clone();
609 // Give the segments new node-ids since they are being cloned.
610 for seg in &mut prefix.segments {
611 seg.id = self.next_node_id();
614 // Each `use` import is an item and thus are owners of the
615 // names in the path. Up to this point the nested import is
616 // the current owner, since we want each desugared import to
617 // own its own names, we have to adjust the owner before
618 // lowering the rest of the import.
619 self.with_hir_id_owner(id, |this| {
620 let mut ident = *ident;
623 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
624 if let Some(attrs) = attrs {
625 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
628 let item = hir::Item {
630 ident: this.lower_ident(ident),
633 span: this.lower_span(use_tree.span),
635 hir::OwnerNode::Item(this.arena.alloc(item))
639 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
640 let res = self.lower_res(res);
641 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
642 hir::ItemKind::Use(path, hir::UseKind::ListStem)
647 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
648 let hir_id = self.lower_node_id(i.id);
649 let def_id = hir_id.expect_owner();
650 self.lower_attrs(hir_id, &i.attrs);
651 let item = hir::ForeignItem {
653 ident: self.lower_ident(i.ident),
655 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
656 let fdec = &sig.decl;
657 let itctx = ImplTraitContext::Universal;
658 let (generics, (fn_dec, fn_args)) =
659 self.lower_generics(generics, i.id, itctx, |this| {
661 // Disallow `impl Trait` in foreign items.
662 this.lower_fn_decl(fdec, None, FnDeclKind::ExternFn, None),
663 this.lower_fn_params_to_names(fdec),
667 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
669 ForeignItemKind::Static(ref t, m, _) => {
671 self.lower_ty(t, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
672 hir::ForeignItemKind::Static(ty, m)
674 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
675 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
677 vis_span: self.lower_span(i.vis.span),
678 span: self.lower_span(i.span),
680 self.arena.alloc(item)
683 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
684 hir::ForeignItemRef {
685 id: hir::ForeignItemId { def_id: self.local_def_id(i.id) },
686 ident: self.lower_ident(i.ident),
687 span: self.lower_span(i.span),
691 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
692 let id = self.lower_node_id(v.id);
693 self.lower_attrs(id, &v.attrs);
696 data: self.lower_variant_data(id, &v.data),
697 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
698 ident: self.lower_ident(v.ident),
699 span: self.lower_span(v.span),
703 fn lower_variant_data(
705 parent_id: hir::HirId,
707 ) -> hir::VariantData<'hir> {
709 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
711 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
714 VariantData::Tuple(ref fields, id) => {
715 let ctor_id = self.lower_node_id(id);
716 self.alias_attrs(ctor_id, parent_id);
717 hir::VariantData::Tuple(
718 self.arena.alloc_from_iter(
719 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
724 VariantData::Unit(id) => {
725 let ctor_id = self.lower_node_id(id);
726 self.alias_attrs(ctor_id, parent_id);
727 hir::VariantData::Unit(ctor_id)
732 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
733 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
734 let t = self.lower_path_ty(
738 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
739 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
743 self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
745 let hir_id = self.lower_node_id(f.id);
746 self.lower_attrs(hir_id, &f.attrs);
748 span: self.lower_span(f.span),
750 ident: match f.ident {
751 Some(ident) => self.lower_ident(ident),
752 // FIXME(jseyfried): positional field hygiene.
753 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
755 vis_span: self.lower_span(f.vis.span),
760 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
761 let hir_id = self.lower_node_id(i.id);
762 let trait_item_def_id = hir_id.expect_owner();
764 let (generics, kind, has_default) = match i.kind {
765 AssocItemKind::Const(_, ref ty, ref default) => {
766 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
767 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
768 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
770 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
771 let names = self.lower_fn_params_to_names(&sig.decl);
772 let (generics, sig) =
773 self.lower_method_sig(generics, sig, i.id, FnDeclKind::Trait, None);
774 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
776 AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
777 let asyncness = sig.header.asyncness;
779 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
780 let (generics, sig) = self.lower_method_sig(
785 asyncness.opt_return_id(),
787 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
789 AssocItemKind::TyAlias(box TyAlias {
796 let mut generics = generics.clone();
797 add_ty_alias_where_clause(&mut generics, where_clauses, false);
798 let (generics, kind) = self.lower_generics(
801 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
803 let ty = ty.as_ref().map(|x| {
804 this.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
806 hir::TraitItemKind::Type(
807 this.lower_param_bounds(
809 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
815 (generics, kind, ty.is_some())
817 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
820 self.lower_attrs(hir_id, &i.attrs);
821 let item = hir::TraitItem {
822 def_id: trait_item_def_id,
823 ident: self.lower_ident(i.ident),
826 span: self.lower_span(i.span),
827 defaultness: hir::Defaultness::Default { has_value: has_default },
829 self.arena.alloc(item)
832 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
833 let kind = match &i.kind {
834 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
835 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
836 AssocItemKind::Fn(box Fn { sig, .. }) => {
837 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
839 AssocItemKind::MacCall(..) => unimplemented!(),
841 let id = hir::TraitItemId { def_id: self.local_def_id(i.id) };
844 ident: self.lower_ident(i.ident),
845 span: self.lower_span(i.span),
850 /// Construct `ExprKind::Err` for the given `span`.
851 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
852 self.expr(span, hir::ExprKind::Err, AttrVec::new())
855 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
856 // Since `default impl` is not yet implemented, this is always true in impls.
857 let has_value = true;
858 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
860 let (generics, kind) = match &i.kind {
861 AssocItemKind::Const(_, ty, expr) => {
862 let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
864 hir::Generics::empty(),
865 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
868 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
869 self.current_item = Some(i.span);
870 let asyncness = sig.header.asyncness;
872 self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
873 let (generics, sig) = self.lower_method_sig(
877 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
878 asyncness.opt_return_id(),
881 (generics, hir::ImplItemKind::Fn(sig, body_id))
883 AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
884 let mut generics = generics.clone();
885 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
889 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
892 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
893 hir::ImplItemKind::TyAlias(ty)
896 let ty = this.lower_ty(ty, ImplTraitContext::TypeAliasesOpaqueTy);
897 hir::ImplItemKind::TyAlias(ty)
902 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
905 let hir_id = self.lower_node_id(i.id);
906 self.lower_attrs(hir_id, &i.attrs);
907 let item = hir::ImplItem {
908 def_id: hir_id.expect_owner(),
909 ident: self.lower_ident(i.ident),
912 vis_span: self.lower_span(i.vis.span),
913 span: self.lower_span(i.span),
916 self.arena.alloc(item)
919 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
921 id: hir::ImplItemId { def_id: self.local_def_id(i.id) },
922 ident: self.lower_ident(i.ident),
923 span: self.lower_span(i.span),
924 kind: match &i.kind {
925 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
926 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
927 AssocItemKind::Fn(box Fn { sig, .. }) => {
928 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
930 AssocItemKind::MacCall(..) => unimplemented!(),
932 trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
936 fn lower_defaultness(
940 ) -> (hir::Defaultness, Option<Span>) {
942 Defaultness::Default(sp) => {
943 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
945 Defaultness::Final => {
947 (hir::Defaultness::Final, None)
954 params: &'hir [hir::Param<'hir>],
955 value: hir::Expr<'hir>,
957 let body = hir::Body {
958 generator_kind: self.generator_kind,
960 value: self.arena.alloc(value),
963 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
964 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
968 pub(super) fn lower_body(
970 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
972 let prev_gen_kind = self.generator_kind.take();
973 let task_context = self.task_context.take();
974 let (parameters, result) = f(self);
975 let body_id = self.record_body(parameters, result);
976 self.task_context = task_context;
977 self.generator_kind = prev_gen_kind;
981 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
982 let hir_id = self.lower_node_id(param.id);
983 self.lower_attrs(hir_id, ¶m.attrs);
986 pat: self.lower_pat(¶m.pat),
987 ty_span: self.lower_span(param.ty.span),
988 span: self.lower_span(param.span),
992 pub(super) fn lower_fn_body(
995 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
997 self.lower_body(|this| {
999 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1005 fn lower_fn_body_block(
1009 body: Option<&Block>,
1011 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1014 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1016 Some(block) => self.lower_block_expr(block),
1017 None => self.expr_err(span),
1021 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1022 self.lower_body(|this| {
1026 Some(expr) => this.lower_expr_mut(expr),
1027 None => this.expr_err(span),
1033 fn lower_maybe_async_body(
1038 body: Option<&Block>,
1040 let closure_id = match asyncness {
1041 Async::Yes { closure_id, .. } => closure_id,
1042 Async::No => return self.lower_fn_body_block(span, decl, body),
1045 self.lower_body(|this| {
1046 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1047 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1049 // Async function parameters are lowered into the closure body so that they are
1050 // captured and so that the drop order matches the equivalent non-async functions.
1054 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1060 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1062 // let __arg2 = __arg2;
1063 // let <pattern> = __arg2;
1064 // let __arg1 = __arg1;
1065 // let <pattern> = __arg1;
1066 // let __arg0 = __arg0;
1067 // let <pattern> = __arg0;
1068 // drop-temps { <body> } // see comments later in fn for details
1072 // If `<pattern>` is a simple ident, then it is lowered to a single
1073 // `let <pattern> = <pattern>;` statement as an optimization.
1075 // Note that the body is embedded in `drop-temps`; an
1076 // equivalent desugaring would be `return { <body>
1077 // };`. The key point is that we wish to drop all the
1078 // let-bound variables and temporaries created in the body
1079 // (and its tail expression!) before we drop the
1080 // parameters (c.f. rust-lang/rust#64512).
1081 for (index, parameter) in decl.inputs.iter().enumerate() {
1082 let parameter = this.lower_param(parameter);
1083 let span = parameter.pat.span;
1085 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1086 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1087 let (ident, is_simple_parameter) = match parameter.pat.kind {
1088 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1091 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1092 // we can keep the same name for the parameter.
1093 // This lets rustdoc render it correctly in documentation.
1094 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1095 hir::PatKind::Wild => {
1096 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1099 // Replace the ident for bindings that aren't simple.
1100 let name = format!("__arg{}", index);
1101 let ident = Ident::from_str(&name);
1107 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1109 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1112 // If this is the simple case, this parameter will end up being the same as the
1113 // original parameter, but with a different pattern id.
1114 let stmt_attrs = this.attrs.get(¶meter.hir_id.local_id).copied();
1115 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1116 let new_parameter = hir::Param {
1117 hir_id: parameter.hir_id,
1118 pat: new_parameter_pat,
1119 ty_span: this.lower_span(parameter.ty_span),
1120 span: this.lower_span(parameter.span),
1123 if is_simple_parameter {
1124 // If this is the simple case, then we only insert one statement that is
1125 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1126 // `HirId`s are densely assigned.
1127 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1128 let stmt = this.stmt_let_pat(
1133 hir::LocalSource::AsyncFn,
1135 statements.push(stmt);
1137 // If this is not the simple case, then we construct two statements:
1140 // let __argN = __argN;
1141 // let <pat> = __argN;
1144 // The first statement moves the parameter into the closure and thus ensures
1145 // that the drop order is correct.
1147 // The second statement creates the bindings that the user wrote.
1149 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1150 // because the user may have specified a `ref mut` binding in the next
1152 let (move_pat, move_id) = this.pat_ident_binding_mode(
1155 hir::BindingAnnotation::MUT,
1157 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1158 let move_stmt = this.stmt_let_pat(
1163 hir::LocalSource::AsyncFn,
1166 // Construct the `let <pat> = __argN;` statement. We re-use the original
1167 // parameter's pattern so that `HirId`s are densely assigned.
1168 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1169 let pattern_stmt = this.stmt_let_pat(
1174 hir::LocalSource::AsyncFn,
1177 statements.push(move_stmt);
1178 statements.push(pattern_stmt);
1181 parameters.push(new_parameter);
1184 let body_span = body.map_or(span, |b| b.span);
1185 let async_expr = this.make_async_expr(
1190 hir::AsyncGeneratorKind::Fn,
1192 // Create a block from the user's function body:
1193 let user_body = this.lower_block_expr_opt(body_span, body);
1195 // Transform into `drop-temps { <user-body> }`, an expression:
1196 let desugared_span =
1197 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1198 let user_body = this.expr_drop_temps(
1200 this.arena.alloc(user_body),
1204 // As noted above, create the final block like
1208 // let $param_pattern = $raw_param;
1210 // drop-temps { <user-body> }
1213 let body = this.block_all(
1215 this.arena.alloc_from_iter(statements),
1219 this.expr_block(body, AttrVec::new())
1224 this.arena.alloc_from_iter(parameters),
1225 this.expr(body_span, async_expr, AttrVec::new()),
1230 fn lower_method_sig(
1232 generics: &Generics,
1236 is_async: Option<NodeId>,
1237 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1238 let header = self.lower_fn_header(sig.header);
1239 let itctx = ImplTraitContext::Universal;
1240 let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
1241 this.lower_fn_decl(&sig.decl, Some(id), kind, is_async)
1243 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1246 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1248 unsafety: self.lower_unsafety(h.unsafety),
1249 asyncness: self.lower_asyncness(h.asyncness),
1250 constness: self.lower_constness(h.constness),
1251 abi: self.lower_extern(h.ext),
1255 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1256 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1257 self.error_on_invalid_abi(abi);
1262 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1264 Extern::None => abi::Abi::Rust,
1265 Extern::Implicit(_) => abi::Abi::FALLBACK,
1266 Extern::Explicit(abi, _) => self.lower_abi(abi),
1270 fn error_on_invalid_abi(&self, abi: StrLit) {
1271 self.tcx.sess.emit_err(InvalidAbi {
1274 valid_abis: abi::all_names().join(", "),
1278 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1280 Async::Yes { .. } => hir::IsAsync::Async,
1281 Async::No => hir::IsAsync::NotAsync,
1285 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1287 Const::Yes(_) => hir::Constness::Const,
1288 Const::No => hir::Constness::NotConst,
1292 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1294 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1295 Unsafe::No => hir::Unsafety::Normal,
1299 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1300 /// the carried impl trait definitions and bounds.
1301 #[instrument(level = "debug", skip(self, f))]
1302 fn lower_generics<T>(
1304 generics: &Generics,
1305 parent_node_id: NodeId,
1306 itctx: ImplTraitContext,
1307 f: impl FnOnce(&mut Self) -> T,
1308 ) -> (&'hir hir::Generics<'hir>, T) {
1309 debug_assert!(self.impl_trait_defs.is_empty());
1310 debug_assert!(self.impl_trait_bounds.is_empty());
1312 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1313 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1314 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1315 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1316 // where clauses for `?Sized`.
1317 for pred in &generics.where_clause.predicates {
1318 let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1321 let compute_is_param = || {
1322 // Check if the where clause type is a plain type parameter.
1325 .get_partial_res(bound_pred.bounded_ty.id)
1326 .map(|d| (d.base_res(), d.unresolved_segments()))
1328 Some((Res::Def(DefKind::TyParam, def_id), 0))
1329 if bound_pred.bound_generic_params.is_empty() =>
1334 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1336 // Either the `bounded_ty` is not a plain type parameter, or
1337 // it's not found in the generic type parameters list.
1341 // We only need to compute this once per `WherePredicate`, but don't
1342 // need to compute this at all unless there is a Maybe bound.
1343 let mut is_param: Option<bool> = None;
1344 for bound in &bound_pred.bounds {
1345 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1348 let is_param = *is_param.get_or_insert_with(compute_is_param);
1350 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1355 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1356 predicates.extend(generics.params.iter().filter_map(|param| {
1357 self.lower_generic_bound_predicate(
1363 PredicateOrigin::GenericParam,
1371 .map(|predicate| self.lower_where_predicate(predicate)),
1374 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1375 self.lower_generic_params_mut(&generics.params).collect();
1377 // Introduce extra lifetimes if late resolution tells us to.
1378 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1379 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1380 self.lifetime_res_to_generic_param(ident, node_id, res)
1383 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1384 let where_clause_span = self.lower_span(generics.where_clause.span);
1385 let span = self.lower_span(generics.span);
1388 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1389 params.extend(impl_trait_defs.into_iter());
1391 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1392 predicates.extend(impl_trait_bounds.into_iter());
1394 let lowered_generics = self.arena.alloc(hir::Generics {
1395 params: self.arena.alloc_from_iter(params),
1396 predicates: self.arena.alloc_from_iter(predicates),
1397 has_where_clause_predicates,
1402 (lowered_generics, res)
1405 pub(super) fn lower_generic_bound_predicate(
1409 kind: &GenericParamKind,
1410 bounds: &[GenericBound],
1411 itctx: ImplTraitContext,
1412 origin: PredicateOrigin,
1413 ) -> Option<hir::WherePredicate<'hir>> {
1414 // Do not create a clause if we do not have anything inside it.
1415 if bounds.is_empty() {
1419 let bounds = self.lower_param_bounds(bounds, itctx);
1421 let ident = self.lower_ident(ident);
1422 let param_span = ident.span;
1425 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1426 let bound_span = bound.span();
1427 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1428 // as we use this method to get a span appropriate for suggestions.
1429 if !bound_span.can_be_used_for_suggestions() {
1431 } else if let Some(span) = span {
1432 Some(span.to(bound_span))
1437 .unwrap_or(param_span.shrink_to_hi());
1439 GenericParamKind::Const { .. } => None,
1440 GenericParamKind::Type { .. } => {
1441 let def_id = self.local_def_id(id).to_def_id();
1442 let hir_id = self.next_id();
1443 let res = Res::Def(DefKind::TyParam, def_id);
1444 let ty_path = self.arena.alloc(hir::Path {
1449 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1451 let ty_id = self.next_id();
1453 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1454 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1455 bounded_ty: self.arena.alloc(bounded_ty),
1458 bound_generic_params: &[],
1462 GenericParamKind::Lifetime => {
1463 let ident_span = self.lower_span(ident.span);
1464 let ident = self.lower_ident(ident);
1465 let lt_id = self.next_node_id();
1466 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1467 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1471 in_where_clause: false,
1477 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1479 WherePredicate::BoundPredicate(WhereBoundPredicate {
1480 ref bound_generic_params,
1484 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1485 bound_generic_params: self.lower_generic_params(bound_generic_params),
1487 .lower_ty(bounded_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1488 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1489 self.lower_param_bound(
1491 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1494 span: self.lower_span(span),
1495 origin: PredicateOrigin::WhereClause,
1497 WherePredicate::RegionPredicate(WhereRegionPredicate {
1501 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1502 span: self.lower_span(span),
1503 lifetime: self.lower_lifetime(lifetime),
1504 bounds: self.lower_param_bounds(
1506 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1508 in_where_clause: true,
1510 WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1511 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1513 .lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1515 .lower_ty(rhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
1516 span: self.lower_span(span),