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().get_parent_node(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 <dyn AstConv<'_>>::ast_ty_to_ty(self, 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 = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
423 self.tcx().mk_projection(item_def_id, item_substs)
425 // There are no late-bound regions; we can just ignore the binder.
426 let mut err = struct_span_err!(
430 "cannot use the associated type of a trait \
431 with uninferred generic parameters"
435 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
439 .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
441 hir::ItemKind::Enum(_, generics)
442 | hir::ItemKind::Struct(_, generics)
443 | hir::ItemKind::Union(_, generics) => {
444 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
445 let (lt_sp, sugg) = match generics.params {
446 [] => (generics.span, format!("<{}>", lt_name)),
448 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
451 let suggestions = vec![
454 span.with_hi(item_segment.ident.span.lo()),
457 // Replace the existing lifetimes with a new named lifetime.
458 self.tcx.replace_late_bound_regions_uncached(
461 self.tcx.mk_region(ty::ReEarlyBound(
462 ty::EarlyBoundRegion {
465 name: Symbol::intern(<_name),
473 err.multipart_suggestion(
474 "use a fully qualified path with explicit lifetimes",
476 Applicability::MaybeIncorrect,
482 hir::Node::Item(hir::Item {
484 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
488 | hir::Node::ForeignItem(_)
489 | hir::Node::TraitItem(_)
490 | hir::Node::ImplItem(_) => {
491 err.span_suggestion_verbose(
492 span.with_hi(item_segment.ident.span.lo()),
493 "use a fully qualified path with inferred lifetimes",
496 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
497 self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
499 Applicability::MaybeIncorrect,
504 self.tcx().ty_error_with_guaranteed(err.emit())
508 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
509 // Types in item signatures are not normalized to avoid undue dependencies.
513 fn set_tainted_by_errors(&self, _: ErrorGuaranteed) {
514 // There's no obvious place to track this, so just let it go.
517 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
518 // There's no place to record types from signatures?
522 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
523 fn get_new_lifetime_name<'tcx>(
525 poly_trait_ref: ty::PolyTraitRef<'tcx>,
526 generics: &hir::Generics<'tcx>,
528 let existing_lifetimes = tcx
529 .collect_referenced_late_bound_regions(&poly_trait_ref)
532 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
533 Some(name.as_str().to_string())
538 .chain(generics.params.iter().filter_map(|param| {
539 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
540 Some(param.name.ident().as_str().to_string())
545 .collect::<FxHashSet<String>>();
547 let a_to_z_repeat_n = |n| {
548 (b'a'..=b'z').map(move |c| {
549 let mut s = '\''.to_string();
550 s.extend(std::iter::repeat(char::from(c)).take(n));
555 // If all single char lifetime names are present, we wrap around and double the chars.
556 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
559 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
560 let it = tcx.hir().item(item_id);
561 debug!("convert: item {} with id {}", it.ident, it.hir_id());
562 let def_id = item_id.owner_id.def_id;
565 // These don't define types.
566 hir::ItemKind::ExternCrate(_)
567 | hir::ItemKind::Use(..)
568 | hir::ItemKind::Macro(..)
569 | hir::ItemKind::Mod(_)
570 | hir::ItemKind::GlobalAsm(_) => {}
571 hir::ItemKind::ForeignMod { items, .. } => {
573 let item = tcx.hir().foreign_item(item.id);
574 tcx.ensure().generics_of(item.owner_id);
575 tcx.ensure().type_of(item.owner_id);
576 tcx.ensure().predicates_of(item.owner_id);
578 hir::ForeignItemKind::Fn(..) => {
579 tcx.ensure().codegen_fn_attrs(item.owner_id);
580 tcx.ensure().fn_sig(item.owner_id)
582 hir::ForeignItemKind::Static(..) => {
583 tcx.ensure().codegen_fn_attrs(item.owner_id);
584 let mut visitor = HirPlaceholderCollector::default();
585 visitor.visit_foreign_item(item);
586 placeholder_type_error(
599 hir::ItemKind::Enum(..) => {
600 tcx.ensure().generics_of(def_id);
601 tcx.ensure().type_of(def_id);
602 tcx.ensure().predicates_of(def_id);
603 convert_enum_variant_types(tcx, def_id.to_def_id());
605 hir::ItemKind::Impl { .. } => {
606 tcx.ensure().generics_of(def_id);
607 tcx.ensure().type_of(def_id);
608 tcx.ensure().impl_trait_ref(def_id);
609 tcx.ensure().predicates_of(def_id);
611 hir::ItemKind::Trait(..) => {
612 tcx.ensure().generics_of(def_id);
613 tcx.ensure().trait_def(def_id);
614 tcx.at(it.span).super_predicates_of(def_id);
615 tcx.ensure().predicates_of(def_id);
617 hir::ItemKind::TraitAlias(..) => {
618 tcx.ensure().generics_of(def_id);
619 tcx.at(it.span).super_predicates_of(def_id);
620 tcx.ensure().predicates_of(def_id);
622 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
623 tcx.ensure().generics_of(def_id);
624 tcx.ensure().type_of(def_id);
625 tcx.ensure().predicates_of(def_id);
627 for f in struct_def.fields() {
628 tcx.ensure().generics_of(f.def_id);
629 tcx.ensure().type_of(f.def_id);
630 tcx.ensure().predicates_of(f.def_id);
633 if let Some(ctor_def_id) = struct_def.ctor_def_id() {
634 convert_variant_ctor(tcx, ctor_def_id);
638 // Don't call `type_of` on opaque types, since that depends on type
639 // checking function bodies. `check_item_type` ensures that it's called
641 hir::ItemKind::OpaqueTy(..) => {
642 tcx.ensure().generics_of(def_id);
643 tcx.ensure().predicates_of(def_id);
644 tcx.ensure().explicit_item_bounds(def_id);
645 tcx.ensure().item_bounds(def_id);
648 hir::ItemKind::TyAlias(..) => {
649 tcx.ensure().generics_of(def_id);
650 tcx.ensure().type_of(def_id);
651 tcx.ensure().predicates_of(def_id);
654 hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
655 tcx.ensure().generics_of(def_id);
656 tcx.ensure().type_of(def_id);
657 tcx.ensure().predicates_of(def_id);
658 if !is_suggestable_infer_ty(ty) {
659 let mut visitor = HirPlaceholderCollector::default();
660 visitor.visit_item(it);
661 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
665 hir::ItemKind::Fn(..) => {
666 tcx.ensure().generics_of(def_id);
667 tcx.ensure().type_of(def_id);
668 tcx.ensure().predicates_of(def_id);
669 tcx.ensure().fn_sig(def_id);
670 tcx.ensure().codegen_fn_attrs(def_id);
675 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
676 let trait_item = tcx.hir().trait_item(trait_item_id);
677 let def_id = trait_item_id.owner_id;
678 tcx.ensure().generics_of(def_id);
680 match trait_item.kind {
681 hir::TraitItemKind::Fn(..) => {
682 tcx.ensure().codegen_fn_attrs(def_id);
683 tcx.ensure().type_of(def_id);
684 tcx.ensure().fn_sig(def_id);
687 hir::TraitItemKind::Const(.., Some(_)) => {
688 tcx.ensure().type_of(def_id);
691 hir::TraitItemKind::Const(hir_ty, _) => {
692 tcx.ensure().type_of(def_id);
693 // Account for `const C: _;`.
694 let mut visitor = HirPlaceholderCollector::default();
695 visitor.visit_trait_item(trait_item);
696 if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
697 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
701 hir::TraitItemKind::Type(_, Some(_)) => {
702 tcx.ensure().item_bounds(def_id);
703 tcx.ensure().type_of(def_id);
704 // Account for `type T = _;`.
705 let mut visitor = HirPlaceholderCollector::default();
706 visitor.visit_trait_item(trait_item);
707 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
710 hir::TraitItemKind::Type(_, None) => {
711 tcx.ensure().item_bounds(def_id);
712 // #74612: Visit and try to find bad placeholders
713 // even if there is no concrete type.
714 let mut visitor = HirPlaceholderCollector::default();
715 visitor.visit_trait_item(trait_item);
717 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
721 tcx.ensure().predicates_of(def_id);
724 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
725 let def_id = impl_item_id.owner_id;
726 tcx.ensure().generics_of(def_id);
727 tcx.ensure().type_of(def_id);
728 tcx.ensure().predicates_of(def_id);
729 let impl_item = tcx.hir().impl_item(impl_item_id);
730 match impl_item.kind {
731 hir::ImplItemKind::Fn(..) => {
732 tcx.ensure().codegen_fn_attrs(def_id);
733 tcx.ensure().fn_sig(def_id);
735 hir::ImplItemKind::Type(_) => {
736 // Account for `type T = _;`
737 let mut visitor = HirPlaceholderCollector::default();
738 visitor.visit_impl_item(impl_item);
740 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
742 hir::ImplItemKind::Const(..) => {}
746 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
747 tcx.ensure().generics_of(def_id);
748 tcx.ensure().type_of(def_id);
749 tcx.ensure().predicates_of(def_id);
752 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
753 let def = tcx.adt_def(def_id);
754 let repr_type = def.repr().discr_type();
755 let initial = repr_type.initial_discriminant(tcx);
756 let mut prev_discr = None::<Discr<'_>>;
758 // fill the discriminant values and field types
759 for variant in def.variants() {
760 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
762 if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
763 def.eval_explicit_discr(tcx, const_def_id)
764 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
767 let span = tcx.def_span(variant.def_id);
768 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
769 .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
771 "explicitly set `{} = {}` if that is desired outcome",
772 tcx.item_name(variant.def_id),
778 .unwrap_or(wrapped_discr),
781 for f in &variant.fields {
782 tcx.ensure().generics_of(f.did);
783 tcx.ensure().type_of(f.did);
784 tcx.ensure().predicates_of(f.did);
787 // Convert the ctor, if any. This also registers the variant as
789 if let Some(ctor_def_id) = variant.ctor_def_id() {
790 convert_variant_ctor(tcx, ctor_def_id.expect_local());
797 variant_did: Option<LocalDefId>,
799 discr: ty::VariantDiscr,
800 def: &hir::VariantData<'_>,
801 adt_kind: ty::AdtKind,
802 parent_did: LocalDefId,
803 ) -> ty::VariantDef {
804 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
809 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
810 if let Some(prev_span) = dup_span {
811 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
817 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
821 did: f.def_id.to_def_id(),
823 vis: tcx.visibility(f.def_id),
827 let recovered = match def {
828 hir::VariantData::Struct(_, r) => *r,
833 variant_did.map(LocalDefId::to_def_id),
834 def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
838 parent_did.to_def_id(),
840 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
841 || variant_did.map_or(false, |variant_did| {
842 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
847 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtDef<'_> {
850 let def_id = def_id.expect_local();
851 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
852 let Node::Item(item) = tcx.hir().get(hir_id) else {
856 let repr = tcx.repr_options_of_def(def_id.to_def_id());
857 let (kind, variants) = match item.kind {
858 ItemKind::Enum(ref def, _) => {
859 let mut distance_from_explicit = 0;
864 let discr = if let Some(ref e) = v.disr_expr {
865 distance_from_explicit = 0;
866 ty::VariantDiscr::Explicit(e.def_id.to_def_id())
868 ty::VariantDiscr::Relative(distance_from_explicit)
870 distance_from_explicit += 1;
884 (AdtKind::Enum, variants)
886 ItemKind::Struct(ref def, _) | ItemKind::Union(ref def, _) => {
887 let adt_kind = match item.kind {
888 ItemKind::Struct(..) => AdtKind::Struct,
891 let variants = std::iter::once(convert_variant(
895 ty::VariantDiscr::Relative(0),
906 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
909 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
910 let item = tcx.hir().expect_item(def_id.expect_local());
912 let (is_auto, unsafety, items) = match item.kind {
913 hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
914 (is_auto == hir::IsAuto::Yes, unsafety, items)
916 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
917 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
920 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
921 if paren_sugar && !tcx.features().unboxed_closures {
925 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
926 which traits can use parenthetical notation",
928 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
932 let is_marker = tcx.has_attr(def_id, sym::marker);
933 let skip_array_during_method_dispatch =
934 tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
935 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
936 ty::trait_def::TraitSpecializationKind::Marker
937 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
938 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
940 ty::trait_def::TraitSpecializationKind::None
942 let must_implement_one_of = tcx
943 .get_attr(def_id, sym::rustc_must_implement_one_of)
944 // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
945 // and that they are all identifiers
946 .and_then(|attr| match attr.meta_item_list() {
947 Some(items) if items.len() < 2 => {
951 "the `#[rustc_must_implement_one_of]` attribute must be \
952 used with at least 2 args",
960 .map(|item| item.ident().ok_or(item.span()))
961 .collect::<Result<Box<[_]>, _>>()
964 .struct_span_err(span, "must be a name of an associated function")
968 .zip(Some(attr.span)),
969 // Error is reported by `rustc_attr!`
972 // Check that all arguments of `#[rustc_must_implement_one_of]` reference
973 // functions in the trait with default implementations
974 .and_then(|(list, attr_span)| {
975 let errors = list.iter().filter_map(|ident| {
976 let item = items.iter().find(|item| item.ident == *ident);
979 Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
980 if !tcx.impl_defaultness(item.id.owner_id).has_value() {
984 "function doesn't have a default implementation",
986 .span_note(attr_span, "required by this annotation")
996 .struct_span_err(item.span, "not a function")
997 .span_note(attr_span, "required by this annotation")
999 "all `#[rustc_must_implement_one_of]` arguments must be associated \
1006 .struct_span_err(ident.span, "function not found in this trait")
1014 (errors.count() == 0).then_some(list)
1016 // Check for duplicates
1018 let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1019 let mut no_dups = true;
1021 for ident in &*list {
1022 if let Some(dup) = set.insert(ident.name, ident.span) {
1024 .struct_span_err(vec![dup, ident.span], "functions names are duplicated")
1025 .note("all `#[rustc_must_implement_one_of]` arguments must be unique")
1032 no_dups.then_some(list)
1041 skip_array_during_method_dispatch,
1043 must_implement_one_of,
1047 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1048 generic_args.iter().any(|arg| match arg {
1049 hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1050 hir::GenericArg::Infer(_) => true,
1055 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1056 /// use inference to provide suggestions for the appropriate type if possible.
1057 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1062 Slice(ty) => is_suggestable_infer_ty(ty),
1063 Array(ty, length) => {
1064 is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1066 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1067 Ptr(mut_ty) | Ref(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1068 OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1069 Path(hir::QPath::TypeRelative(ty, segment)) => {
1070 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1072 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1073 ty_opt.map_or(false, is_suggestable_infer_ty)
1074 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1080 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1081 if let hir::FnRetTy::Return(ty) = output {
1082 if is_suggestable_infer_ty(ty) {
1089 #[instrument(level = "debug", skip(tcx))]
1090 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1091 use rustc_hir::Node::*;
1094 let def_id = def_id.expect_local();
1095 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1097 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1099 match tcx.hir().get(hir_id) {
1100 TraitItem(hir::TraitItem {
1101 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1105 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1106 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1109 ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1110 // Do not try to infer the return type for a impl method coming from a trait
1111 if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1112 tcx.hir().get(tcx.hir().get_parent_node(hir_id))
1113 && i.of_trait.is_some()
1115 <dyn AstConv<'_>>::ty_of_fn(
1118 sig.header.unsafety,
1125 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1129 TraitItem(hir::TraitItem {
1130 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1133 }) => <dyn AstConv<'_>>::ty_of_fn(
1143 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1144 let abi = tcx.hir().get_foreign_abi(hir_id);
1145 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1148 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1149 let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1150 let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1151 ty::Binder::dummy(tcx.mk_fn_sig(
1155 hir::Unsafety::Normal,
1160 Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1161 // Closure signatures are not like other function
1162 // signatures and cannot be accessed through `fn_sig`. For
1163 // example, a closure signature excludes the `self`
1164 // argument. In any case they are embedded within the
1165 // closure type as part of the `ClosureSubsts`.
1167 // To get the signature of a closure, you should use the
1168 // `sig` method on the `ClosureSubsts`:
1170 // substs.as_closure().sig(def_id, tcx)
1172 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1177 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1182 fn infer_return_ty_for_fn_sig<'tcx>(
1184 sig: &hir::FnSig<'_>,
1185 generics: &hir::Generics<'_>,
1187 icx: &ItemCtxt<'tcx>,
1188 ) -> ty::PolyFnSig<'tcx> {
1189 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1191 match get_infer_ret_ty(&sig.decl.output) {
1193 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1194 // Typeck doesn't expect erased regions to be returned from `type_of`.
1195 let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1196 ty::ReErased => tcx.lifetimes.re_static,
1200 let mut visitor = HirPlaceholderCollector::default();
1201 visitor.visit_ty(ty);
1202 let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1203 let ret_ty = fn_sig.output();
1204 if ret_ty.is_suggestable(tcx, false) {
1205 diag.span_suggestion(
1207 "replace with the correct return type",
1209 Applicability::MachineApplicable,
1211 } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1212 let fn_sig = ret_ty.fn_sig(tcx);
1217 .all(|t| t.is_suggestable(tcx, false))
1219 diag.span_suggestion(
1221 "replace with the correct return type",
1223 Applicability::MachineApplicable,
1226 } else if let Some(sugg) = suggest_impl_trait(tcx, ret_ty, ty.span, hir_id, def_id) {
1227 diag.span_suggestion(
1229 "replace with an appropriate return type",
1231 Applicability::MachineApplicable,
1233 } else if ret_ty.is_closure() {
1234 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1236 // Also note how `Fn` traits work just in case!
1237 if ret_ty.is_closure() {
1239 "for more information on `Fn` traits and closure types, see \
1240 https://doc.rust-lang.org/book/ch13-01-closures.html",
1245 ty::Binder::dummy(fn_sig)
1247 None => <dyn AstConv<'_>>::ty_of_fn(
1250 sig.header.unsafety,
1259 fn suggest_impl_trait<'tcx>(
1265 ) -> Option<String> {
1266 let format_as_assoc: fn(_, _, _, _, _) -> _ =
1268 _: ty::SubstsRef<'tcx>,
1269 trait_def_id: DefId,
1270 assoc_item_def_id: DefId,
1271 item_ty: Ty<'tcx>| {
1272 let trait_name = tcx.item_name(trait_def_id);
1273 let assoc_name = tcx.item_name(assoc_item_def_id);
1274 Some(format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1276 let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1278 substs: ty::SubstsRef<'tcx>,
1279 trait_def_id: DefId,
1281 item_ty: Ty<'tcx>| {
1282 let trait_name = tcx.item_name(trait_def_id);
1283 let args_tuple = substs.type_at(1);
1284 let ty::Tuple(types) = *args_tuple.kind() else { return None; };
1285 if !types.is_suggestable(tcx, false) {
1289 if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") };
1291 "impl {trait_name}({}){maybe_ret}",
1292 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1296 for (trait_def_id, assoc_item_def_id, formatter) in [
1298 tcx.get_diagnostic_item(sym::Iterator),
1299 tcx.get_diagnostic_item(sym::IteratorItem),
1303 tcx.lang_items().future_trait(),
1304 tcx.get_diagnostic_item(sym::FutureOutput),
1307 (tcx.lang_items().fn_trait(), tcx.lang_items().fn_once_output(), format_as_parenthesized),
1309 tcx.lang_items().fn_mut_trait(),
1310 tcx.lang_items().fn_once_output(),
1311 format_as_parenthesized,
1314 tcx.lang_items().fn_once_trait(),
1315 tcx.lang_items().fn_once_output(),
1316 format_as_parenthesized,
1319 let Some(trait_def_id) = trait_def_id else { continue; };
1320 let Some(assoc_item_def_id) = assoc_item_def_id else { continue; };
1321 if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1324 let param_env = tcx.param_env(def_id);
1325 let infcx = tcx.infer_ctxt().build();
1326 let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
1327 if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) }
1329 if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions()
1333 let ocx = ObligationCtxt::new_in_snapshot(&infcx);
1334 let item_ty = ocx.normalize(
1335 &ObligationCause::misc(span, hir_id),
1337 tcx.mk_projection(assoc_item_def_id, substs),
1339 // FIXME(compiler-errors): We may benefit from resolving regions here.
1340 if ocx.select_where_possible().is_empty()
1341 && let item_ty = infcx.resolve_vars_if_possible(item_ty)
1342 && item_ty.is_suggestable(tcx, false)
1343 && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty)
1351 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1352 let icx = ItemCtxt::new(tcx, def_id);
1353 let item = tcx.hir().expect_item(def_id.expect_local());
1355 hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1356 let selfty = tcx.type_of(def_id);
1357 <dyn AstConv<'_>>::instantiate_mono_trait_ref(
1361 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1368 fn check_impl_constness(
1370 constness: hir::Constness,
1371 ast_trait_ref: &hir::TraitRef<'_>,
1372 ) -> ty::BoundConstness {
1374 hir::Constness::Const => {
1375 if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1376 let trait_name = tcx.item_name(trait_def_id).to_string();
1377 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1378 trait_ref_span: ast_trait_ref.path.span,
1380 local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1384 ty::BoundConstness::NotConst
1386 ty::BoundConstness::ConstIfConst
1389 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1393 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1394 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1395 let item = tcx.hir().expect_item(def_id.expect_local());
1397 hir::ItemKind::Impl(hir::Impl {
1398 polarity: hir::ImplPolarity::Negative(span),
1402 if is_rustc_reservation {
1403 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1404 tcx.sess.span_err(span, "reservation impls can't be negative");
1406 ty::ImplPolarity::Negative
1408 hir::ItemKind::Impl(hir::Impl {
1409 polarity: hir::ImplPolarity::Positive,
1413 if is_rustc_reservation {
1414 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1416 ty::ImplPolarity::Positive
1418 hir::ItemKind::Impl(hir::Impl {
1419 polarity: hir::ImplPolarity::Positive,
1423 if is_rustc_reservation {
1424 ty::ImplPolarity::Reservation
1426 ty::ImplPolarity::Positive
1429 item => bug!("impl_polarity: {:?} not an impl", item),
1433 /// Returns the early-bound lifetimes declared in this generics
1434 /// listing. For anything other than fns/methods, this is just all
1435 /// the lifetimes that are declared. For fns or methods, we have to
1436 /// screen out those that do not appear in any where-clauses etc using
1437 /// `resolve_lifetime::early_bound_lifetimes`.
1438 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1440 generics: &'a hir::Generics<'a>,
1441 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1442 generics.params.iter().filter(move |param| match param.kind {
1443 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1448 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1449 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1450 /// inferred constraints concerning which regions outlive other regions.
1451 #[instrument(level = "debug", skip(tcx))]
1452 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1453 let mut result = tcx.explicit_predicates_of(def_id);
1454 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1455 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1456 if !inferred_outlives.is_empty() {
1458 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1459 def_id, inferred_outlives,
1461 let inferred_outlives_iter =
1462 inferred_outlives.iter().map(|(clause, span)| ((*clause).to_predicate(tcx), *span));
1463 if result.predicates.is_empty() {
1464 result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
1466 result.predicates = tcx.arena.alloc_from_iter(
1467 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
1472 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1476 fn compute_sig_of_foreign_fn_decl<'tcx>(
1479 decl: &'tcx hir::FnDecl<'tcx>,
1481 ) -> ty::PolyFnSig<'tcx> {
1482 let unsafety = if abi == abi::Abi::RustIntrinsic {
1483 intrinsic_operation_unsafety(tcx, def_id)
1485 hir::Unsafety::Unsafe
1487 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1488 let fty = <dyn AstConv<'_>>::ty_of_fn(
1489 &ItemCtxt::new(tcx, def_id),
1498 // Feature gate SIMD types in FFI, since I am not sure that the
1499 // ABIs are handled at all correctly. -huonw
1500 if abi != abi::Abi::RustIntrinsic
1501 && abi != abi::Abi::PlatformIntrinsic
1502 && !tcx.features().simd_ffi
1504 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1509 .span_to_snippet(ast_ty.span)
1510 .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1515 "use of SIMD type{} in FFI is highly experimental and \
1516 may result in invalid code",
1520 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1524 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1527 if let hir::FnRetTy::Return(ref ty) = decl.output {
1528 check(ty, fty.output().skip_binder())
1535 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1536 match tcx.hir().get_if_local(def_id) {
1537 Some(Node::ForeignItem(..)) => true,
1539 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1543 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1544 match tcx.hir().get_if_local(def_id) {
1545 Some(Node::Expr(&rustc_hir::Expr {
1546 kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1548 })) => tcx.hir().body(body).generator_kind(),
1550 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),