1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *inter-procedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
17 use crate::astconv::AstConv;
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
20 use hir::def::DefKind;
21 use rustc_data_structures::captures::Captures;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
25 use rustc_hir::def_id::{DefId, LocalDefId};
26 use rustc_hir::intravisit::{self, Visitor};
27 use rustc_hir::{GenericParamKind, Node};
28 use rustc_infer::infer::TyCtxtInferExt;
29 use rustc_infer::traits::ObligationCause;
30 use rustc_middle::hir::nested_filter;
31 use rustc_middle::ty::query::Providers;
32 use rustc_middle::ty::util::{Discr, IntTypeExt};
33 use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, ToPredicate, Ty, TyCtxt};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_target::spec::abi;
37 use rustc_trait_selection::infer::InferCtxtExt;
38 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
39 use rustc_trait_selection::traits::ObligationCtxt;
48 ///////////////////////////////////////////////////////////////////////////
51 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
52 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
55 pub fn provide(providers: &mut Providers) {
56 lifetimes::provide(providers);
57 *providers = Providers {
58 opt_const_param_of: type_of::opt_const_param_of,
59 type_of: type_of::type_of,
60 item_bounds: item_bounds::item_bounds,
61 explicit_item_bounds: item_bounds::explicit_item_bounds,
62 generics_of: generics_of::generics_of,
63 predicates_of: predicates_of::predicates_of,
64 predicates_defined_on,
65 explicit_predicates_of: predicates_of::explicit_predicates_of,
66 super_predicates_of: predicates_of::super_predicates_of,
67 super_predicates_that_define_assoc_type:
68 predicates_of::super_predicates_that_define_assoc_type,
69 trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds,
70 type_param_predicates: predicates_of::type_param_predicates,
78 collect_mod_item_types,
83 ///////////////////////////////////////////////////////////////////////////
85 /// Context specific to some particular item. This is what implements
88 /// # `ItemCtxt` vs `FnCtxt`
90 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
91 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
92 /// It's also used for the bodies of items like structs where the body (the fields)
93 /// are just signatures.
95 /// This is in contrast to `FnCtxt`, which is used to type-check bodies of
96 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
98 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
99 /// while `FnCtxt` does do inference.
101 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
103 /// # Trait predicates
105 /// `ItemCtxt` has information about the predicates that are defined
106 /// on the trait. Unfortunately, this predicate information is
107 /// available in various different forms at various points in the
108 /// process. So we can't just store a pointer to e.g., the AST or the
109 /// parsed ty form, we have to be more flexible. To this end, the
110 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
111 /// `get_type_parameter_bounds` requests, drawing the information from
112 /// the AST (`hir::Generics`), recursively.
113 pub struct ItemCtxt<'tcx> {
118 ///////////////////////////////////////////////////////////////////////////
121 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
123 impl<'v> Visitor<'v> for HirPlaceholderCollector {
124 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
125 if let hir::TyKind::Infer = t.kind {
128 intravisit::walk_ty(self, t)
130 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
132 hir::GenericArg::Infer(inf) => {
133 self.0.push(inf.span);
134 intravisit::walk_inf(self, inf);
136 hir::GenericArg::Type(t) => self.visit_ty(t),
140 fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
141 if let &hir::ArrayLen::Infer(_, span) = length {
144 intravisit::walk_array_len(self, length)
148 struct CollectItemTypesVisitor<'tcx> {
152 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
153 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
154 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
155 pub(crate) fn placeholder_type_error<'tcx>(
157 generics: Option<&hir::Generics<'_>>,
158 placeholder_types: Vec<Span>,
160 hir_ty: Option<&hir::Ty<'_>>,
163 if placeholder_types.is_empty() {
167 placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
171 pub(crate) fn placeholder_type_error_diag<'tcx>(
173 generics: Option<&hir::Generics<'_>>,
174 placeholder_types: Vec<Span>,
175 additional_spans: Vec<Span>,
177 hir_ty: Option<&hir::Ty<'_>>,
179 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
180 if placeholder_types.is_empty() {
181 return bad_placeholder(tcx, additional_spans, kind);
184 let params = generics.map(|g| g.params).unwrap_or_default();
185 let type_name = params.next_type_param_name(None);
186 let mut sugg: Vec<_> =
187 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
189 if let Some(generics) = generics {
190 if let Some(arg) = params.iter().find(|arg| {
191 matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
193 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
194 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
195 sugg.push((arg.span, (*type_name).to_string()));
196 } else if let Some(span) = generics.span_for_param_suggestion() {
197 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
198 sugg.push((span, format!(", {}", type_name)));
200 sugg.push((generics.span, format!("<{}>", type_name)));
205 bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
207 // Suggest, but only if it is not a function in const or static
209 let mut is_fn = false;
210 let mut is_const_or_static = false;
212 if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
215 // Check if parent is const or static
216 let parent_id = tcx.hir().parent_id(hir_ty.hir_id);
217 let parent_node = tcx.hir().get(parent_id);
219 is_const_or_static = matches!(
221 Node::Item(&hir::Item {
222 kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
224 }) | Node::TraitItem(&hir::TraitItem {
225 kind: hir::TraitItemKind::Const(..),
227 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
231 // if function is wrapped around a const or static,
232 // then don't show the suggestion
233 if !(is_fn && is_const_or_static) {
234 err.multipart_suggestion(
235 "use type parameters instead",
237 Applicability::HasPlaceholders,
245 fn reject_placeholder_type_signatures_in_item<'tcx>(
247 item: &'tcx hir::Item<'tcx>,
249 let (generics, suggest) = match &item.kind {
250 hir::ItemKind::Union(_, generics)
251 | hir::ItemKind::Enum(_, generics)
252 | hir::ItemKind::TraitAlias(generics, _)
253 | hir::ItemKind::Trait(_, _, generics, ..)
254 | hir::ItemKind::Impl(hir::Impl { generics, .. })
255 | hir::ItemKind::Struct(_, generics) => (generics, true),
256 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
257 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
258 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
262 let mut visitor = HirPlaceholderCollector::default();
263 visitor.visit_item(item);
265 placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
268 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
269 type NestedFilter = nested_filter::OnlyBodies;
271 fn nested_visit_map(&mut self) -> Self::Map {
275 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
276 convert_item(self.tcx, item.item_id());
277 reject_placeholder_type_signatures_in_item(self.tcx, item);
278 intravisit::walk_item(self, item);
281 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
282 for param in generics.params {
284 hir::GenericParamKind::Lifetime { .. } => {}
285 hir::GenericParamKind::Type { default: Some(_), .. } => {
286 self.tcx.ensure().type_of(param.def_id);
288 hir::GenericParamKind::Type { .. } => {}
289 hir::GenericParamKind::Const { default, .. } => {
290 self.tcx.ensure().type_of(param.def_id);
291 if let Some(default) = default {
292 // need to store default and type of default
293 self.tcx.ensure().type_of(default.def_id);
294 self.tcx.ensure().const_param_default(param.def_id);
299 intravisit::walk_generics(self, generics);
302 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
303 if let hir::ExprKind::Closure(closure) = expr.kind {
304 self.tcx.ensure().generics_of(closure.def_id);
305 self.tcx.ensure().codegen_fn_attrs(closure.def_id);
306 // We do not call `type_of` for closures here as that
307 // depends on typecheck and would therefore hide
308 // any further errors in case one typeck fails.
310 intravisit::walk_expr(self, expr);
313 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
314 convert_trait_item(self.tcx, trait_item.trait_item_id());
315 intravisit::walk_trait_item(self, trait_item);
318 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
319 convert_impl_item(self.tcx, impl_item.impl_item_id());
320 intravisit::walk_impl_item(self, impl_item);
324 ///////////////////////////////////////////////////////////////////////////
325 // Utility types and common code for the above passes.
327 fn bad_placeholder<'tcx>(
329 mut spans: Vec<Span>,
331 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
332 let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
335 let mut err = struct_span_err!(
339 "the placeholder `_` is not allowed within types on item signatures for {}",
343 err.span_label(span, "not allowed in type signatures");
348 impl<'tcx> ItemCtxt<'tcx> {
349 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
350 ItemCtxt { tcx, item_def_id }
353 pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
354 self.astconv().ast_ty_to_ty(ast_ty)
357 pub fn hir_id(&self) -> hir::HirId {
358 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
361 pub fn node(&self) -> hir::Node<'tcx> {
362 self.tcx.hir().get(self.hir_id())
366 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
367 fn tcx(&self) -> TyCtxt<'tcx> {
371 fn item_def_id(&self) -> DefId {
375 fn get_type_parameter_bounds(
380 ) -> ty::GenericPredicates<'tcx> {
381 self.tcx.at(span).type_param_predicates((
383 def_id.expect_local(),
388 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
392 fn allow_ty_infer(&self) -> bool {
396 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
397 self.tcx().ty_error_with_message(span, "bad placeholder type")
400 fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
401 let ty = self.tcx.fold_regions(ty, |r, _| match *r {
402 ty::ReErased => self.tcx.lifetimes.re_static,
405 self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
408 fn projected_ty_from_poly_trait_ref(
412 item_segment: &hir::PathSegment<'_>,
413 poly_trait_ref: ty::PolyTraitRef<'tcx>,
415 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
416 let item_substs = self.astconv().create_substs_for_associated_item(
422 self.tcx().mk_projection(item_def_id, item_substs)
424 // There are no late-bound regions; we can just ignore the binder.
425 let mut err = struct_span_err!(
429 "cannot use the associated type of a trait \
430 with uninferred generic parameters"
434 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
438 .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
440 hir::ItemKind::Enum(_, generics)
441 | hir::ItemKind::Struct(_, generics)
442 | hir::ItemKind::Union(_, generics) => {
443 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
444 let (lt_sp, sugg) = match generics.params {
445 [] => (generics.span, format!("<{}>", lt_name)),
447 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
450 let suggestions = vec![
453 span.with_hi(item_segment.ident.span.lo()),
456 // Replace the existing lifetimes with a new named lifetime.
457 self.tcx.replace_late_bound_regions_uncached(
460 self.tcx.mk_region(ty::ReEarlyBound(
461 ty::EarlyBoundRegion {
464 name: Symbol::intern(<_name),
472 err.multipart_suggestion(
473 "use a fully qualified path with explicit lifetimes",
475 Applicability::MaybeIncorrect,
481 hir::Node::Item(hir::Item {
483 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
487 | hir::Node::ForeignItem(_)
488 | hir::Node::TraitItem(_)
489 | hir::Node::ImplItem(_) => {
490 err.span_suggestion_verbose(
491 span.with_hi(item_segment.ident.span.lo()),
492 "use a fully qualified path with inferred lifetimes",
495 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
496 self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
498 Applicability::MaybeIncorrect,
503 self.tcx().ty_error_with_guaranteed(err.emit())
507 fn probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
508 // FIXME(#103640): Should we handle the case where `ty` is a projection?
512 fn set_tainted_by_errors(&self, _: ErrorGuaranteed) {
513 // There's no obvious place to track this, so just let it go.
516 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
517 // There's no place to record types from signatures?
521 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
522 fn get_new_lifetime_name<'tcx>(
524 poly_trait_ref: ty::PolyTraitRef<'tcx>,
525 generics: &hir::Generics<'tcx>,
527 let existing_lifetimes = tcx
528 .collect_referenced_late_bound_regions(&poly_trait_ref)
531 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
532 Some(name.as_str().to_string())
537 .chain(generics.params.iter().filter_map(|param| {
538 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
539 Some(param.name.ident().as_str().to_string())
544 .collect::<FxHashSet<String>>();
546 let a_to_z_repeat_n = |n| {
547 (b'a'..=b'z').map(move |c| {
548 let mut s = '\''.to_string();
549 s.extend(std::iter::repeat(char::from(c)).take(n));
554 // If all single char lifetime names are present, we wrap around and double the chars.
555 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
558 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
559 let it = tcx.hir().item(item_id);
560 debug!("convert: item {} with id {}", it.ident, it.hir_id());
561 let def_id = item_id.owner_id.def_id;
564 // These don't define types.
565 hir::ItemKind::ExternCrate(_)
566 | hir::ItemKind::Use(..)
567 | hir::ItemKind::Macro(..)
568 | hir::ItemKind::Mod(_)
569 | hir::ItemKind::GlobalAsm(_) => {}
570 hir::ItemKind::ForeignMod { items, .. } => {
572 let item = tcx.hir().foreign_item(item.id);
573 tcx.ensure().generics_of(item.owner_id);
574 tcx.ensure().type_of(item.owner_id);
575 tcx.ensure().predicates_of(item.owner_id);
577 hir::ForeignItemKind::Fn(..) => {
578 tcx.ensure().codegen_fn_attrs(item.owner_id);
579 tcx.ensure().fn_sig(item.owner_id)
581 hir::ForeignItemKind::Static(..) => {
582 tcx.ensure().codegen_fn_attrs(item.owner_id);
583 let mut visitor = HirPlaceholderCollector::default();
584 visitor.visit_foreign_item(item);
585 placeholder_type_error(
598 hir::ItemKind::Enum(..) => {
599 tcx.ensure().generics_of(def_id);
600 tcx.ensure().type_of(def_id);
601 tcx.ensure().predicates_of(def_id);
602 convert_enum_variant_types(tcx, def_id.to_def_id());
604 hir::ItemKind::Impl { .. } => {
605 tcx.ensure().generics_of(def_id);
606 tcx.ensure().type_of(def_id);
607 tcx.ensure().impl_trait_ref(def_id);
608 tcx.ensure().predicates_of(def_id);
610 hir::ItemKind::Trait(..) => {
611 tcx.ensure().generics_of(def_id);
612 tcx.ensure().trait_def(def_id);
613 tcx.at(it.span).super_predicates_of(def_id);
614 tcx.ensure().predicates_of(def_id);
616 hir::ItemKind::TraitAlias(..) => {
617 tcx.ensure().generics_of(def_id);
618 tcx.at(it.span).super_predicates_of(def_id);
619 tcx.ensure().predicates_of(def_id);
621 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
622 tcx.ensure().generics_of(def_id);
623 tcx.ensure().type_of(def_id);
624 tcx.ensure().predicates_of(def_id);
626 for f in struct_def.fields() {
627 tcx.ensure().generics_of(f.def_id);
628 tcx.ensure().type_of(f.def_id);
629 tcx.ensure().predicates_of(f.def_id);
632 if let Some(ctor_def_id) = struct_def.ctor_def_id() {
633 convert_variant_ctor(tcx, ctor_def_id);
637 // Don't call `type_of` on opaque types, since that depends on type
638 // checking function bodies. `check_item_type` ensures that it's called
640 hir::ItemKind::OpaqueTy(..) => {
641 tcx.ensure().generics_of(def_id);
642 tcx.ensure().predicates_of(def_id);
643 tcx.ensure().explicit_item_bounds(def_id);
644 tcx.ensure().item_bounds(def_id);
647 hir::ItemKind::TyAlias(..) => {
648 tcx.ensure().generics_of(def_id);
649 tcx.ensure().type_of(def_id);
650 tcx.ensure().predicates_of(def_id);
653 hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
654 tcx.ensure().generics_of(def_id);
655 tcx.ensure().type_of(def_id);
656 tcx.ensure().predicates_of(def_id);
657 if !is_suggestable_infer_ty(ty) {
658 let mut visitor = HirPlaceholderCollector::default();
659 visitor.visit_item(it);
660 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
664 hir::ItemKind::Fn(..) => {
665 tcx.ensure().generics_of(def_id);
666 tcx.ensure().type_of(def_id);
667 tcx.ensure().predicates_of(def_id);
668 tcx.ensure().fn_sig(def_id);
669 tcx.ensure().codegen_fn_attrs(def_id);
674 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
675 let trait_item = tcx.hir().trait_item(trait_item_id);
676 let def_id = trait_item_id.owner_id;
677 tcx.ensure().generics_of(def_id);
679 match trait_item.kind {
680 hir::TraitItemKind::Fn(..) => {
681 tcx.ensure().codegen_fn_attrs(def_id);
682 tcx.ensure().type_of(def_id);
683 tcx.ensure().fn_sig(def_id);
686 hir::TraitItemKind::Const(.., Some(_)) => {
687 tcx.ensure().type_of(def_id);
690 hir::TraitItemKind::Const(hir_ty, _) => {
691 tcx.ensure().type_of(def_id);
692 // Account for `const C: _;`.
693 let mut visitor = HirPlaceholderCollector::default();
694 visitor.visit_trait_item(trait_item);
695 if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
696 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
700 hir::TraitItemKind::Type(_, Some(_)) => {
701 tcx.ensure().item_bounds(def_id);
702 tcx.ensure().type_of(def_id);
703 // Account for `type T = _;`.
704 let mut visitor = HirPlaceholderCollector::default();
705 visitor.visit_trait_item(trait_item);
706 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
709 hir::TraitItemKind::Type(_, None) => {
710 tcx.ensure().item_bounds(def_id);
711 // #74612: Visit and try to find bad placeholders
712 // even if there is no concrete type.
713 let mut visitor = HirPlaceholderCollector::default();
714 visitor.visit_trait_item(trait_item);
716 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
720 tcx.ensure().predicates_of(def_id);
723 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
724 let def_id = impl_item_id.owner_id;
725 tcx.ensure().generics_of(def_id);
726 tcx.ensure().type_of(def_id);
727 tcx.ensure().predicates_of(def_id);
728 let impl_item = tcx.hir().impl_item(impl_item_id);
729 match impl_item.kind {
730 hir::ImplItemKind::Fn(..) => {
731 tcx.ensure().codegen_fn_attrs(def_id);
732 tcx.ensure().fn_sig(def_id);
734 hir::ImplItemKind::Type(_) => {
735 // Account for `type T = _;`
736 let mut visitor = HirPlaceholderCollector::default();
737 visitor.visit_impl_item(impl_item);
739 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
741 hir::ImplItemKind::Const(..) => {}
745 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
746 tcx.ensure().generics_of(def_id);
747 tcx.ensure().type_of(def_id);
748 tcx.ensure().predicates_of(def_id);
751 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
752 let def = tcx.adt_def(def_id);
753 let repr_type = def.repr().discr_type();
754 let initial = repr_type.initial_discriminant(tcx);
755 let mut prev_discr = None::<Discr<'_>>;
757 // fill the discriminant values and field types
758 for variant in def.variants() {
759 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
761 if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
762 def.eval_explicit_discr(tcx, const_def_id)
763 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
766 let span = tcx.def_span(variant.def_id);
767 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
768 .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
770 "explicitly set `{} = {}` if that is desired outcome",
771 tcx.item_name(variant.def_id),
777 .unwrap_or(wrapped_discr),
780 for f in &variant.fields {
781 tcx.ensure().generics_of(f.did);
782 tcx.ensure().type_of(f.did);
783 tcx.ensure().predicates_of(f.did);
786 // Convert the ctor, if any. This also registers the variant as
788 if let Some(ctor_def_id) = variant.ctor_def_id() {
789 convert_variant_ctor(tcx, ctor_def_id.expect_local());
796 variant_did: Option<LocalDefId>,
798 discr: ty::VariantDiscr,
799 def: &hir::VariantData<'_>,
800 adt_kind: ty::AdtKind,
801 parent_did: LocalDefId,
802 ) -> ty::VariantDef {
803 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
808 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
809 if let Some(prev_span) = dup_span {
810 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
816 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
820 did: f.def_id.to_def_id(),
822 vis: tcx.visibility(f.def_id),
826 let recovered = match def {
827 hir::VariantData::Struct(_, r) => *r,
832 variant_did.map(LocalDefId::to_def_id),
833 def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
837 parent_did.to_def_id(),
839 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
840 || variant_did.map_or(false, |variant_did| {
841 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
846 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtDef<'_> {
849 let def_id = def_id.expect_local();
850 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
851 let Node::Item(item) = tcx.hir().get(hir_id) else {
855 let repr = tcx.repr_options_of_def(def_id.to_def_id());
856 let (kind, variants) = match item.kind {
857 ItemKind::Enum(ref def, _) => {
858 let mut distance_from_explicit = 0;
863 let discr = if let Some(ref e) = v.disr_expr {
864 distance_from_explicit = 0;
865 ty::VariantDiscr::Explicit(e.def_id.to_def_id())
867 ty::VariantDiscr::Relative(distance_from_explicit)
869 distance_from_explicit += 1;
883 (AdtKind::Enum, variants)
885 ItemKind::Struct(ref def, _) | ItemKind::Union(ref def, _) => {
886 let adt_kind = match item.kind {
887 ItemKind::Struct(..) => AdtKind::Struct,
890 let variants = std::iter::once(convert_variant(
894 ty::VariantDiscr::Relative(0),
905 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
908 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
909 let item = tcx.hir().expect_item(def_id.expect_local());
911 let (is_auto, unsafety, items) = match item.kind {
912 hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
913 (is_auto == hir::IsAuto::Yes, unsafety, items)
915 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
916 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
919 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
920 if paren_sugar && !tcx.features().unboxed_closures {
924 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
925 which traits can use parenthetical notation",
927 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
931 let is_marker = tcx.has_attr(def_id, sym::marker);
932 let skip_array_during_method_dispatch =
933 tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
934 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
935 ty::trait_def::TraitSpecializationKind::Marker
936 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
937 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
939 ty::trait_def::TraitSpecializationKind::None
941 let must_implement_one_of = tcx
942 .get_attr(def_id, sym::rustc_must_implement_one_of)
943 // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
944 // and that they are all identifiers
945 .and_then(|attr| match attr.meta_item_list() {
946 Some(items) if items.len() < 2 => {
950 "the `#[rustc_must_implement_one_of]` attribute must be \
951 used with at least 2 args",
959 .map(|item| item.ident().ok_or(item.span()))
960 .collect::<Result<Box<[_]>, _>>()
963 .struct_span_err(span, "must be a name of an associated function")
967 .zip(Some(attr.span)),
968 // Error is reported by `rustc_attr!`
971 // Check that all arguments of `#[rustc_must_implement_one_of]` reference
972 // functions in the trait with default implementations
973 .and_then(|(list, attr_span)| {
974 let errors = list.iter().filter_map(|ident| {
975 let item = items.iter().find(|item| item.ident == *ident);
978 Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
979 if !tcx.impl_defaultness(item.id.owner_id).has_value() {
983 "function doesn't have a default implementation",
985 .span_note(attr_span, "required by this annotation")
995 .struct_span_err(item.span, "not a function")
996 .span_note(attr_span, "required by this annotation")
998 "all `#[rustc_must_implement_one_of]` arguments must be associated \
1005 .struct_span_err(ident.span, "function not found in this trait")
1013 (errors.count() == 0).then_some(list)
1015 // Check for duplicates
1017 let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1018 let mut no_dups = true;
1020 for ident in &*list {
1021 if let Some(dup) = set.insert(ident.name, ident.span) {
1023 .struct_span_err(vec![dup, ident.span], "functions names are duplicated")
1024 .note("all `#[rustc_must_implement_one_of]` arguments must be unique")
1031 no_dups.then_some(list)
1040 skip_array_during_method_dispatch,
1042 must_implement_one_of,
1046 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1047 generic_args.iter().any(|arg| match arg {
1048 hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1049 hir::GenericArg::Infer(_) => true,
1054 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1055 /// use inference to provide suggestions for the appropriate type if possible.
1056 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1061 Slice(ty) => is_suggestable_infer_ty(ty),
1062 Array(ty, length) => {
1063 is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1065 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1066 Ptr(mut_ty) | Ref(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1067 OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1068 Path(hir::QPath::TypeRelative(ty, segment)) => {
1069 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1071 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1072 ty_opt.map_or(false, is_suggestable_infer_ty)
1073 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1079 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1080 if let hir::FnRetTy::Return(ty) = output {
1081 if is_suggestable_infer_ty(ty) {
1088 #[instrument(level = "debug", skip(tcx))]
1089 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1090 use rustc_hir::Node::*;
1093 let def_id = def_id.expect_local();
1094 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1096 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1098 match tcx.hir().get(hir_id) {
1099 TraitItem(hir::TraitItem {
1100 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1104 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1105 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1108 ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1109 // Do not try to infer the return type for a impl method coming from a trait
1110 if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1111 tcx.hir().get_parent(hir_id)
1112 && i.of_trait.is_some()
1114 icx.astconv().ty_of_fn(
1116 sig.header.unsafety,
1123 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1127 TraitItem(hir::TraitItem {
1128 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1132 icx.astconv().ty_of_fn(hir_id, header.unsafety, header.abi, decl, Some(generics), None)
1135 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1136 let abi = tcx.hir().get_foreign_abi(hir_id);
1137 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1140 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1141 let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1142 let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1143 ty::Binder::dummy(tcx.mk_fn_sig(
1147 hir::Unsafety::Normal,
1152 Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1153 // Closure signatures are not like other function
1154 // signatures and cannot be accessed through `fn_sig`. For
1155 // example, a closure signature excludes the `self`
1156 // argument. In any case they are embedded within the
1157 // closure type as part of the `ClosureSubsts`.
1159 // To get the signature of a closure, you should use the
1160 // `sig` method on the `ClosureSubsts`:
1162 // substs.as_closure().sig(def_id, tcx)
1164 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1169 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1174 fn infer_return_ty_for_fn_sig<'tcx>(
1176 sig: &hir::FnSig<'_>,
1177 generics: &hir::Generics<'_>,
1179 icx: &ItemCtxt<'tcx>,
1180 ) -> ty::PolyFnSig<'tcx> {
1181 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1183 match get_infer_ret_ty(&sig.decl.output) {
1185 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1186 // Typeck doesn't expect erased regions to be returned from `type_of`.
1187 let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1188 ty::ReErased => tcx.lifetimes.re_static,
1192 let mut visitor = HirPlaceholderCollector::default();
1193 visitor.visit_ty(ty);
1194 let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1195 let ret_ty = fn_sig.output();
1196 if ret_ty.is_suggestable(tcx, false) {
1197 diag.span_suggestion(
1199 "replace with the correct return type",
1201 Applicability::MachineApplicable,
1203 } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1204 let fn_sig = ret_ty.fn_sig(tcx);
1209 .all(|t| t.is_suggestable(tcx, false))
1211 diag.span_suggestion(
1213 "replace with the correct return type",
1215 Applicability::MachineApplicable,
1218 } else if let Some(sugg) = suggest_impl_trait(tcx, ret_ty, ty.span, hir_id, def_id) {
1219 diag.span_suggestion(
1221 "replace with an appropriate return type",
1223 Applicability::MachineApplicable,
1225 } else if ret_ty.is_closure() {
1226 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1228 // Also note how `Fn` traits work just in case!
1229 if ret_ty.is_closure() {
1231 "for more information on `Fn` traits and closure types, see \
1232 https://doc.rust-lang.org/book/ch13-01-closures.html",
1237 ty::Binder::dummy(fn_sig)
1239 None => icx.astconv().ty_of_fn(
1241 sig.header.unsafety,
1250 fn suggest_impl_trait<'tcx>(
1256 ) -> Option<String> {
1257 let format_as_assoc: fn(_, _, _, _, _) -> _ =
1259 _: ty::SubstsRef<'tcx>,
1260 trait_def_id: DefId,
1261 assoc_item_def_id: DefId,
1262 item_ty: Ty<'tcx>| {
1263 let trait_name = tcx.item_name(trait_def_id);
1264 let assoc_name = tcx.item_name(assoc_item_def_id);
1265 Some(format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1267 let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1269 substs: ty::SubstsRef<'tcx>,
1270 trait_def_id: DefId,
1272 item_ty: Ty<'tcx>| {
1273 let trait_name = tcx.item_name(trait_def_id);
1274 let args_tuple = substs.type_at(1);
1275 let ty::Tuple(types) = *args_tuple.kind() else { return None; };
1276 if !types.is_suggestable(tcx, false) {
1280 if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") };
1282 "impl {trait_name}({}){maybe_ret}",
1283 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1287 for (trait_def_id, assoc_item_def_id, formatter) in [
1289 tcx.get_diagnostic_item(sym::Iterator),
1290 tcx.get_diagnostic_item(sym::IteratorItem),
1294 tcx.lang_items().future_trait(),
1295 tcx.get_diagnostic_item(sym::FutureOutput),
1298 (tcx.lang_items().fn_trait(), tcx.lang_items().fn_once_output(), format_as_parenthesized),
1300 tcx.lang_items().fn_mut_trait(),
1301 tcx.lang_items().fn_once_output(),
1302 format_as_parenthesized,
1305 tcx.lang_items().fn_once_trait(),
1306 tcx.lang_items().fn_once_output(),
1307 format_as_parenthesized,
1310 let Some(trait_def_id) = trait_def_id else { continue; };
1311 let Some(assoc_item_def_id) = assoc_item_def_id else { continue; };
1312 if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1315 let param_env = tcx.param_env(def_id);
1316 let infcx = tcx.infer_ctxt().build();
1317 let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
1318 if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) }
1320 if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions()
1324 let ocx = ObligationCtxt::new_in_snapshot(&infcx);
1325 let item_ty = ocx.normalize(
1326 &ObligationCause::misc(span, hir_id),
1328 tcx.mk_projection(assoc_item_def_id, substs),
1330 // FIXME(compiler-errors): We may benefit from resolving regions here.
1331 if ocx.select_where_possible().is_empty()
1332 && let item_ty = infcx.resolve_vars_if_possible(item_ty)
1333 && item_ty.is_suggestable(tcx, false)
1334 && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty)
1342 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::EarlyBinder<ty::TraitRef<'_>>> {
1343 let icx = ItemCtxt::new(tcx, def_id);
1344 let item = tcx.hir().expect_item(def_id.expect_local());
1346 hir::ItemKind::Impl(ref impl_) => impl_
1349 .map(|ast_trait_ref| {
1350 let selfty = tcx.type_of(def_id);
1351 icx.astconv().instantiate_mono_trait_ref(
1354 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1357 .map(ty::EarlyBinder),
1362 fn check_impl_constness(
1364 constness: hir::Constness,
1365 ast_trait_ref: &hir::TraitRef<'_>,
1366 ) -> ty::BoundConstness {
1368 hir::Constness::Const => {
1369 if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1370 let trait_name = tcx.item_name(trait_def_id).to_string();
1371 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1372 trait_ref_span: ast_trait_ref.path.span,
1374 local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1378 ty::BoundConstness::NotConst
1380 ty::BoundConstness::ConstIfConst
1383 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1387 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1388 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1389 let item = tcx.hir().expect_item(def_id.expect_local());
1391 hir::ItemKind::Impl(hir::Impl {
1392 polarity: hir::ImplPolarity::Negative(span),
1396 if is_rustc_reservation {
1397 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1398 tcx.sess.span_err(span, "reservation impls can't be negative");
1400 ty::ImplPolarity::Negative
1402 hir::ItemKind::Impl(hir::Impl {
1403 polarity: hir::ImplPolarity::Positive,
1407 if is_rustc_reservation {
1408 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1410 ty::ImplPolarity::Positive
1412 hir::ItemKind::Impl(hir::Impl {
1413 polarity: hir::ImplPolarity::Positive,
1417 if is_rustc_reservation {
1418 ty::ImplPolarity::Reservation
1420 ty::ImplPolarity::Positive
1423 item => bug!("impl_polarity: {:?} not an impl", item),
1427 /// Returns the early-bound lifetimes declared in this generics
1428 /// listing. For anything other than fns/methods, this is just all
1429 /// the lifetimes that are declared. For fns or methods, we have to
1430 /// screen out those that do not appear in any where-clauses etc using
1431 /// `resolve_lifetime::early_bound_lifetimes`.
1432 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1434 generics: &'a hir::Generics<'a>,
1435 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1436 generics.params.iter().filter(move |param| match param.kind {
1437 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1442 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1443 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1444 /// inferred constraints concerning which regions outlive other regions.
1445 #[instrument(level = "debug", skip(tcx))]
1446 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1447 let mut result = tcx.explicit_predicates_of(def_id);
1448 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1449 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1450 if !inferred_outlives.is_empty() {
1452 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1453 def_id, inferred_outlives,
1455 let inferred_outlives_iter =
1456 inferred_outlives.iter().map(|(clause, span)| ((*clause).to_predicate(tcx), *span));
1457 if result.predicates.is_empty() {
1458 result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
1460 result.predicates = tcx.arena.alloc_from_iter(
1461 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
1466 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1470 fn compute_sig_of_foreign_fn_decl<'tcx>(
1473 decl: &'tcx hir::FnDecl<'tcx>,
1475 ) -> ty::PolyFnSig<'tcx> {
1476 let unsafety = if abi == abi::Abi::RustIntrinsic {
1477 intrinsic_operation_unsafety(tcx, def_id)
1479 hir::Unsafety::Unsafe
1481 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1483 ItemCtxt::new(tcx, def_id).astconv().ty_of_fn(hir_id, unsafety, abi, decl, None, None);
1485 // Feature gate SIMD types in FFI, since I am not sure that the
1486 // ABIs are handled at all correctly. -huonw
1487 if abi != abi::Abi::RustIntrinsic
1488 && abi != abi::Abi::PlatformIntrinsic
1489 && !tcx.features().simd_ffi
1491 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1496 .span_to_snippet(ast_ty.span)
1497 .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1502 "use of SIMD type{} in FFI is highly experimental and \
1503 may result in invalid code",
1507 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1511 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1514 if let hir::FnRetTy::Return(ref ty) = decl.output {
1515 check(ty, fty.output().skip_binder())
1522 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1523 match tcx.hir().get_if_local(def_id) {
1524 Some(Node::ForeignItem(..)) => true,
1526 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1530 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1531 match tcx.hir().get_if_local(def_id) {
1532 Some(Node::Expr(&rustc_hir::Expr {
1533 kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1535 })) => tcx.hir().body(body).generator_kind(),
1537 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),