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::{InferCtxt, 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,
79 is_type_alias_impl_trait,
84 ///////////////////////////////////////////////////////////////////////////
86 /// Context specific to some particular item. This is what implements
89 /// # `ItemCtxt` vs `FnCtxt`
91 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
92 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
93 /// It's also used for the bodies of items like structs where the body (the fields)
94 /// are just signatures.
96 /// This is in contrast to `FnCtxt`, which is used to type-check bodies of
97 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
99 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
100 /// while `FnCtxt` does do inference.
102 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
104 /// # Trait predicates
106 /// `ItemCtxt` has information about the predicates that are defined
107 /// on the trait. Unfortunately, this predicate information is
108 /// available in various different forms at various points in the
109 /// process. So we can't just store a pointer to e.g., the AST or the
110 /// parsed ty form, we have to be more flexible. To this end, the
111 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
112 /// `get_type_parameter_bounds` requests, drawing the information from
113 /// the AST (`hir::Generics`), recursively.
114 pub struct ItemCtxt<'tcx> {
119 ///////////////////////////////////////////////////////////////////////////
122 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
124 impl<'v> Visitor<'v> for HirPlaceholderCollector {
125 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
126 if let hir::TyKind::Infer = t.kind {
129 intravisit::walk_ty(self, t)
131 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
133 hir::GenericArg::Infer(inf) => {
134 self.0.push(inf.span);
135 intravisit::walk_inf(self, inf);
137 hir::GenericArg::Type(t) => self.visit_ty(t),
141 fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
142 if let &hir::ArrayLen::Infer(_, span) = length {
145 intravisit::walk_array_len(self, length)
149 struct CollectItemTypesVisitor<'tcx> {
153 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
154 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
155 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
156 pub(crate) fn placeholder_type_error<'tcx>(
158 generics: Option<&hir::Generics<'_>>,
159 placeholder_types: Vec<Span>,
161 hir_ty: Option<&hir::Ty<'_>>,
164 if placeholder_types.is_empty() {
168 placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
172 pub(crate) fn placeholder_type_error_diag<'tcx>(
174 generics: Option<&hir::Generics<'_>>,
175 placeholder_types: Vec<Span>,
176 additional_spans: Vec<Span>,
178 hir_ty: Option<&hir::Ty<'_>>,
180 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
181 if placeholder_types.is_empty() {
182 return bad_placeholder(tcx, additional_spans, kind);
185 let params = generics.map(|g| g.params).unwrap_or_default();
186 let type_name = params.next_type_param_name(None);
187 let mut sugg: Vec<_> =
188 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
190 if let Some(generics) = generics {
191 if let Some(arg) = params.iter().find(|arg| {
192 matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
194 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
195 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
196 sugg.push((arg.span, (*type_name).to_string()));
197 } else if let Some(span) = generics.span_for_param_suggestion() {
198 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
199 sugg.push((span, format!(", {}", type_name)));
201 sugg.push((generics.span, format!("<{}>", type_name)));
206 bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
208 // Suggest, but only if it is not a function in const or static
210 let mut is_fn = false;
211 let mut is_const_or_static = false;
213 if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
216 // Check if parent is const or static
217 let parent_id = tcx.hir().parent_id(hir_ty.hir_id);
218 let parent_node = tcx.hir().get(parent_id);
220 is_const_or_static = matches!(
222 Node::Item(&hir::Item {
223 kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
225 }) | Node::TraitItem(&hir::TraitItem {
226 kind: hir::TraitItemKind::Const(..),
228 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
232 // if function is wrapped around a const or static,
233 // then don't show the suggestion
234 if !(is_fn && is_const_or_static) {
235 err.multipart_suggestion(
236 "use type parameters instead",
238 Applicability::HasPlaceholders,
246 fn reject_placeholder_type_signatures_in_item<'tcx>(
248 item: &'tcx hir::Item<'tcx>,
250 let (generics, suggest) = match &item.kind {
251 hir::ItemKind::Union(_, generics)
252 | hir::ItemKind::Enum(_, generics)
253 | hir::ItemKind::TraitAlias(generics, _)
254 | hir::ItemKind::Trait(_, _, generics, ..)
255 | hir::ItemKind::Impl(hir::Impl { generics, .. })
256 | hir::ItemKind::Struct(_, generics) => (generics, true),
257 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
258 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
259 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
263 let mut visitor = HirPlaceholderCollector::default();
264 visitor.visit_item(item);
266 placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
269 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
270 type NestedFilter = nested_filter::OnlyBodies;
272 fn nested_visit_map(&mut self) -> Self::Map {
276 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
277 convert_item(self.tcx, item.item_id());
278 reject_placeholder_type_signatures_in_item(self.tcx, item);
279 intravisit::walk_item(self, item);
282 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
283 for param in generics.params {
285 hir::GenericParamKind::Lifetime { .. } => {}
286 hir::GenericParamKind::Type { default: Some(_), .. } => {
287 self.tcx.ensure().type_of(param.def_id);
289 hir::GenericParamKind::Type { .. } => {}
290 hir::GenericParamKind::Const { default, .. } => {
291 self.tcx.ensure().type_of(param.def_id);
292 if let Some(default) = default {
293 // need to store default and type of default
294 self.tcx.ensure().type_of(default.def_id);
295 self.tcx.ensure().const_param_default(param.def_id);
300 intravisit::walk_generics(self, generics);
303 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
304 if let hir::ExprKind::Closure(closure) = expr.kind {
305 self.tcx.ensure().generics_of(closure.def_id);
306 self.tcx.ensure().codegen_fn_attrs(closure.def_id);
307 // We do not call `type_of` for closures here as that
308 // depends on typecheck and would therefore hide
309 // any further errors in case one typeck fails.
311 intravisit::walk_expr(self, expr);
314 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
315 convert_trait_item(self.tcx, trait_item.trait_item_id());
316 intravisit::walk_trait_item(self, trait_item);
319 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
320 convert_impl_item(self.tcx, impl_item.impl_item_id());
321 intravisit::walk_impl_item(self, impl_item);
325 ///////////////////////////////////////////////////////////////////////////
326 // Utility types and common code for the above passes.
328 fn bad_placeholder<'tcx>(
330 mut spans: Vec<Span>,
332 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
333 let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
336 let mut err = struct_span_err!(
340 "the placeholder `_` is not allowed within types on item signatures for {}",
344 err.span_label(span, "not allowed in type signatures");
349 impl<'tcx> ItemCtxt<'tcx> {
350 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
351 ItemCtxt { tcx, item_def_id }
354 pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
355 self.astconv().ast_ty_to_ty(ast_ty)
358 pub fn hir_id(&self) -> hir::HirId {
359 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
362 pub fn node(&self) -> hir::Node<'tcx> {
363 self.tcx.hir().get(self.hir_id())
367 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
368 fn tcx(&self) -> TyCtxt<'tcx> {
372 fn item_def_id(&self) -> DefId {
376 fn get_type_parameter_bounds(
381 ) -> ty::GenericPredicates<'tcx> {
382 self.tcx.at(span).type_param_predicates((
384 def_id.expect_local(),
389 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
393 fn allow_ty_infer(&self) -> bool {
397 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
398 self.tcx().ty_error_with_message(span, "bad placeholder type")
401 fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
402 let ty = self.tcx.fold_regions(ty, |r, _| match *r {
403 ty::ReErased => self.tcx.lifetimes.re_static,
406 self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
409 fn projected_ty_from_poly_trait_ref(
413 item_segment: &hir::PathSegment<'_>,
414 poly_trait_ref: ty::PolyTraitRef<'tcx>,
416 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
417 let item_substs = self.astconv().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 probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
509 // FIXME(#103640): Should we handle the case where `ty` is a projection?
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?
521 fn infcx(&self) -> Option<&InferCtxt<'tcx>> {
526 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
527 fn get_new_lifetime_name<'tcx>(
529 poly_trait_ref: ty::PolyTraitRef<'tcx>,
530 generics: &hir::Generics<'tcx>,
532 let existing_lifetimes = tcx
533 .collect_referenced_late_bound_regions(&poly_trait_ref)
536 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
537 Some(name.as_str().to_string())
542 .chain(generics.params.iter().filter_map(|param| {
543 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
544 Some(param.name.ident().as_str().to_string())
549 .collect::<FxHashSet<String>>();
551 let a_to_z_repeat_n = |n| {
552 (b'a'..=b'z').map(move |c| {
553 let mut s = '\''.to_string();
554 s.extend(std::iter::repeat(char::from(c)).take(n));
559 // If all single char lifetime names are present, we wrap around and double the chars.
560 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
563 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
564 let it = tcx.hir().item(item_id);
565 debug!("convert: item {} with id {}", it.ident, it.hir_id());
566 let def_id = item_id.owner_id.def_id;
569 // These don't define types.
570 hir::ItemKind::ExternCrate(_)
571 | hir::ItemKind::Use(..)
572 | hir::ItemKind::Macro(..)
573 | hir::ItemKind::Mod(_)
574 | hir::ItemKind::GlobalAsm(_) => {}
575 hir::ItemKind::ForeignMod { items, .. } => {
577 let item = tcx.hir().foreign_item(item.id);
578 tcx.ensure().generics_of(item.owner_id);
579 tcx.ensure().type_of(item.owner_id);
580 tcx.ensure().predicates_of(item.owner_id);
582 hir::ForeignItemKind::Fn(..) => {
583 tcx.ensure().codegen_fn_attrs(item.owner_id);
584 tcx.ensure().fn_sig(item.owner_id)
586 hir::ForeignItemKind::Static(..) => {
587 tcx.ensure().codegen_fn_attrs(item.owner_id);
588 let mut visitor = HirPlaceholderCollector::default();
589 visitor.visit_foreign_item(item);
590 placeholder_type_error(
603 hir::ItemKind::Enum(..) => {
604 tcx.ensure().generics_of(def_id);
605 tcx.ensure().type_of(def_id);
606 tcx.ensure().predicates_of(def_id);
607 convert_enum_variant_types(tcx, def_id.to_def_id());
609 hir::ItemKind::Impl { .. } => {
610 tcx.ensure().generics_of(def_id);
611 tcx.ensure().type_of(def_id);
612 tcx.ensure().impl_trait_ref(def_id);
613 tcx.ensure().predicates_of(def_id);
615 hir::ItemKind::Trait(..) => {
616 tcx.ensure().generics_of(def_id);
617 tcx.ensure().trait_def(def_id);
618 tcx.at(it.span).super_predicates_of(def_id);
619 tcx.ensure().predicates_of(def_id);
621 hir::ItemKind::TraitAlias(..) => {
622 tcx.ensure().generics_of(def_id);
623 tcx.at(it.span).super_predicates_of(def_id);
624 tcx.ensure().predicates_of(def_id);
626 hir::ItemKind::Struct(struct_def, _) | hir::ItemKind::Union(struct_def, _) => {
627 tcx.ensure().generics_of(def_id);
628 tcx.ensure().type_of(def_id);
629 tcx.ensure().predicates_of(def_id);
631 for f in struct_def.fields() {
632 tcx.ensure().generics_of(f.def_id);
633 tcx.ensure().type_of(f.def_id);
634 tcx.ensure().predicates_of(f.def_id);
637 if let Some(ctor_def_id) = struct_def.ctor_def_id() {
638 convert_variant_ctor(tcx, ctor_def_id);
642 // Don't call `type_of` on opaque types, since that depends on type
643 // checking function bodies. `check_item_type` ensures that it's called
645 hir::ItemKind::OpaqueTy(..) => {
646 tcx.ensure().generics_of(def_id);
647 tcx.ensure().predicates_of(def_id);
648 tcx.ensure().explicit_item_bounds(def_id);
649 tcx.ensure().item_bounds(def_id);
652 hir::ItemKind::TyAlias(..) => {
653 tcx.ensure().generics_of(def_id);
654 tcx.ensure().type_of(def_id);
655 tcx.ensure().predicates_of(def_id);
658 hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
659 tcx.ensure().generics_of(def_id);
660 tcx.ensure().type_of(def_id);
661 tcx.ensure().predicates_of(def_id);
662 if !is_suggestable_infer_ty(ty) {
663 let mut visitor = HirPlaceholderCollector::default();
664 visitor.visit_item(it);
665 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
669 hir::ItemKind::Fn(..) => {
670 tcx.ensure().generics_of(def_id);
671 tcx.ensure().type_of(def_id);
672 tcx.ensure().predicates_of(def_id);
673 tcx.ensure().fn_sig(def_id);
674 tcx.ensure().codegen_fn_attrs(def_id);
679 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
680 let trait_item = tcx.hir().trait_item(trait_item_id);
681 let def_id = trait_item_id.owner_id;
682 tcx.ensure().generics_of(def_id);
684 match trait_item.kind {
685 hir::TraitItemKind::Fn(..) => {
686 tcx.ensure().codegen_fn_attrs(def_id);
687 tcx.ensure().type_of(def_id);
688 tcx.ensure().fn_sig(def_id);
691 hir::TraitItemKind::Const(.., Some(_)) => {
692 tcx.ensure().type_of(def_id);
695 hir::TraitItemKind::Const(hir_ty, _) => {
696 tcx.ensure().type_of(def_id);
697 // Account for `const C: _;`.
698 let mut visitor = HirPlaceholderCollector::default();
699 visitor.visit_trait_item(trait_item);
700 if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
701 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
705 hir::TraitItemKind::Type(_, Some(_)) => {
706 tcx.ensure().item_bounds(def_id);
707 tcx.ensure().type_of(def_id);
708 // Account for `type T = _;`.
709 let mut visitor = HirPlaceholderCollector::default();
710 visitor.visit_trait_item(trait_item);
711 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
714 hir::TraitItemKind::Type(_, None) => {
715 tcx.ensure().item_bounds(def_id);
716 // #74612: Visit and try to find bad placeholders
717 // even if there is no concrete type.
718 let mut visitor = HirPlaceholderCollector::default();
719 visitor.visit_trait_item(trait_item);
721 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
725 tcx.ensure().predicates_of(def_id);
728 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
729 let def_id = impl_item_id.owner_id;
730 tcx.ensure().generics_of(def_id);
731 tcx.ensure().type_of(def_id);
732 tcx.ensure().predicates_of(def_id);
733 let impl_item = tcx.hir().impl_item(impl_item_id);
734 match impl_item.kind {
735 hir::ImplItemKind::Fn(..) => {
736 tcx.ensure().codegen_fn_attrs(def_id);
737 tcx.ensure().fn_sig(def_id);
739 hir::ImplItemKind::Type(_) => {
740 // Account for `type T = _;`
741 let mut visitor = HirPlaceholderCollector::default();
742 visitor.visit_impl_item(impl_item);
744 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
746 hir::ImplItemKind::Const(..) => {}
750 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
751 tcx.ensure().generics_of(def_id);
752 tcx.ensure().type_of(def_id);
753 tcx.ensure().predicates_of(def_id);
756 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
757 let def = tcx.adt_def(def_id);
758 let repr_type = def.repr().discr_type();
759 let initial = repr_type.initial_discriminant(tcx);
760 let mut prev_discr = None::<Discr<'_>>;
762 // fill the discriminant values and field types
763 for variant in def.variants() {
764 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
766 if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
767 def.eval_explicit_discr(tcx, const_def_id)
768 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
771 let span = tcx.def_span(variant.def_id);
772 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
773 .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
775 "explicitly set `{} = {}` if that is desired outcome",
776 tcx.item_name(variant.def_id),
782 .unwrap_or(wrapped_discr),
785 for f in &variant.fields {
786 tcx.ensure().generics_of(f.did);
787 tcx.ensure().type_of(f.did);
788 tcx.ensure().predicates_of(f.did);
791 // Convert the ctor, if any. This also registers the variant as
793 if let Some(ctor_def_id) = variant.ctor_def_id() {
794 convert_variant_ctor(tcx, ctor_def_id.expect_local());
801 variant_did: Option<LocalDefId>,
803 discr: ty::VariantDiscr,
804 def: &hir::VariantData<'_>,
805 adt_kind: ty::AdtKind,
806 parent_did: LocalDefId,
807 ) -> ty::VariantDef {
808 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
813 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
814 if let Some(prev_span) = dup_span {
815 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
821 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
825 did: f.def_id.to_def_id(),
827 vis: tcx.visibility(f.def_id),
831 let recovered = match def {
832 hir::VariantData::Struct(_, r) => *r,
837 variant_did.map(LocalDefId::to_def_id),
838 def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
842 parent_did.to_def_id(),
844 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
845 || variant_did.map_or(false, |variant_did| {
846 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
851 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtDef<'_> {
854 let def_id = def_id.expect_local();
855 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
856 let Node::Item(item) = tcx.hir().get(hir_id) else {
860 let repr = tcx.repr_options_of_def(def_id.to_def_id());
861 let (kind, variants) = match &item.kind {
862 ItemKind::Enum(def, _) => {
863 let mut distance_from_explicit = 0;
868 let discr = if let Some(e) = &v.disr_expr {
869 distance_from_explicit = 0;
870 ty::VariantDiscr::Explicit(e.def_id.to_def_id())
872 ty::VariantDiscr::Relative(distance_from_explicit)
874 distance_from_explicit += 1;
888 (AdtKind::Enum, variants)
890 ItemKind::Struct(def, _) | ItemKind::Union(def, _) => {
891 let adt_kind = match item.kind {
892 ItemKind::Struct(..) => AdtKind::Struct,
895 let variants = std::iter::once(convert_variant(
899 ty::VariantDiscr::Relative(0),
910 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
913 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
914 let item = tcx.hir().expect_item(def_id.expect_local());
916 let (is_auto, unsafety, items) = match item.kind {
917 hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
918 (is_auto == hir::IsAuto::Yes, unsafety, items)
920 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
921 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
924 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
925 if paren_sugar && !tcx.features().unboxed_closures {
929 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
930 which traits can use parenthetical notation",
932 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
936 let is_marker = tcx.has_attr(def_id, sym::marker);
937 let skip_array_during_method_dispatch =
938 tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
939 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
940 ty::trait_def::TraitSpecializationKind::Marker
941 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
942 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
944 ty::trait_def::TraitSpecializationKind::None
946 let must_implement_one_of = tcx
947 .get_attr(def_id, sym::rustc_must_implement_one_of)
948 // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
949 // and that they are all identifiers
950 .and_then(|attr| match attr.meta_item_list() {
951 Some(items) if items.len() < 2 => {
955 "the `#[rustc_must_implement_one_of]` attribute must be \
956 used with at least 2 args",
964 .map(|item| item.ident().ok_or(item.span()))
965 .collect::<Result<Box<[_]>, _>>()
968 .struct_span_err(span, "must be a name of an associated function")
972 .zip(Some(attr.span)),
973 // Error is reported by `rustc_attr!`
976 // Check that all arguments of `#[rustc_must_implement_one_of]` reference
977 // functions in the trait with default implementations
978 .and_then(|(list, attr_span)| {
979 let errors = list.iter().filter_map(|ident| {
980 let item = items.iter().find(|item| item.ident == *ident);
983 Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
984 if !tcx.impl_defaultness(item.id.owner_id).has_value() {
988 "function doesn't have a default implementation",
990 .span_note(attr_span, "required by this annotation")
1000 .struct_span_err(item.span, "not a function")
1001 .span_note(attr_span, "required by this annotation")
1003 "all `#[rustc_must_implement_one_of]` arguments must be associated \
1010 .struct_span_err(ident.span, "function not found in this trait")
1018 (errors.count() == 0).then_some(list)
1020 // Check for duplicates
1022 let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1023 let mut no_dups = true;
1025 for ident in &*list {
1026 if let Some(dup) = set.insert(ident.name, ident.span) {
1028 .struct_span_err(vec![dup, ident.span], "functions names are duplicated")
1029 .note("all `#[rustc_must_implement_one_of]` arguments must be unique")
1036 no_dups.then_some(list)
1045 skip_array_during_method_dispatch,
1047 must_implement_one_of,
1051 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1052 generic_args.iter().any(|arg| match arg {
1053 hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1054 hir::GenericArg::Infer(_) => true,
1059 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1060 /// use inference to provide suggestions for the appropriate type if possible.
1061 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1066 Slice(ty) => is_suggestable_infer_ty(ty),
1067 Array(ty, length) => {
1068 is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1070 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1071 Ptr(mut_ty) | Ref(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1072 OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1073 Path(hir::QPath::TypeRelative(ty, segment)) => {
1074 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1076 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1077 ty_opt.map_or(false, is_suggestable_infer_ty)
1078 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1084 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1085 if let hir::FnRetTy::Return(ty) = output {
1086 if is_suggestable_infer_ty(ty) {
1093 #[instrument(level = "debug", skip(tcx))]
1094 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<ty::PolyFnSig<'_>> {
1095 use rustc_hir::Node::*;
1098 let def_id = def_id.expect_local();
1099 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1101 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1103 let output = match tcx.hir().get(hir_id) {
1104 TraitItem(hir::TraitItem {
1105 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1109 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1110 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1113 ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1114 // Do not try to infer the return type for a impl method coming from a trait
1115 if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1116 tcx.hir().get_parent(hir_id)
1117 && i.of_trait.is_some()
1119 icx.astconv().ty_of_fn(
1121 sig.header.unsafety,
1128 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1132 TraitItem(hir::TraitItem {
1133 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1137 icx.astconv().ty_of_fn(hir_id, header.unsafety, header.abi, decl, Some(generics), None)
1140 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1141 let abi = tcx.hir().get_foreign_abi(hir_id);
1142 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1145 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1146 let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1147 let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1148 ty::Binder::dummy(tcx.mk_fn_sig(
1152 hir::Unsafety::Normal,
1157 Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1158 // Closure signatures are not like other function
1159 // signatures and cannot be accessed through `fn_sig`. For
1160 // example, a closure signature excludes the `self`
1161 // argument. In any case they are embedded within the
1162 // closure type as part of the `ClosureSubsts`.
1164 // To get the signature of a closure, you should use the
1165 // `sig` method on the `ClosureSubsts`:
1167 // substs.as_closure().sig(def_id, tcx)
1169 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1174 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1177 ty::EarlyBinder(output)
1180 fn infer_return_ty_for_fn_sig<'tcx>(
1182 sig: &hir::FnSig<'_>,
1183 generics: &hir::Generics<'_>,
1185 icx: &ItemCtxt<'tcx>,
1186 ) -> ty::PolyFnSig<'tcx> {
1187 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1189 match get_infer_ret_ty(&sig.decl.output) {
1191 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1192 // Typeck doesn't expect erased regions to be returned from `type_of`.
1193 let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1194 ty::ReErased => tcx.lifetimes.re_static,
1198 let mut visitor = HirPlaceholderCollector::default();
1199 visitor.visit_ty(ty);
1200 let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1201 let ret_ty = fn_sig.output();
1202 if let Some(ret_ty) = ret_ty.make_suggestable(tcx, false) {
1203 diag.span_suggestion(
1205 "replace with the correct return type",
1207 Applicability::MachineApplicable,
1209 } else if matches!(ret_ty.kind(), ty::FnDef(..))
1210 && let Some(fn_sig) = ret_ty.fn_sig(tcx).make_suggestable(tcx, false)
1212 diag.span_suggestion(
1214 "replace with the correct return type",
1216 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 // FIXME(vincenzopalazzo): remove the hir item when the refactoring is stable
1251 fn suggest_impl_trait<'tcx>(
1255 _hir_id: hir::HirId,
1257 ) -> Option<String> {
1258 let format_as_assoc: fn(_, _, _, _, _) -> _ =
1260 _: ty::SubstsRef<'tcx>,
1261 trait_def_id: DefId,
1262 assoc_item_def_id: DefId,
1263 item_ty: Ty<'tcx>| {
1264 let trait_name = tcx.item_name(trait_def_id);
1265 let assoc_name = tcx.item_name(assoc_item_def_id);
1266 Some(format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1268 let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1270 substs: ty::SubstsRef<'tcx>,
1271 trait_def_id: DefId,
1273 item_ty: Ty<'tcx>| {
1274 let trait_name = tcx.item_name(trait_def_id);
1275 let args_tuple = substs.type_at(1);
1276 let ty::Tuple(types) = *args_tuple.kind() else { return None; };
1277 let types = types.make_suggestable(tcx, false)?;
1279 if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") };
1281 "impl {trait_name}({}){maybe_ret}",
1282 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1286 for (trait_def_id, assoc_item_def_id, formatter) in [
1288 tcx.get_diagnostic_item(sym::Iterator),
1289 tcx.get_diagnostic_item(sym::IteratorItem),
1293 tcx.lang_items().future_trait(),
1294 tcx.get_diagnostic_item(sym::FutureOutput),
1297 (tcx.lang_items().fn_trait(), tcx.lang_items().fn_once_output(), format_as_parenthesized),
1299 tcx.lang_items().fn_mut_trait(),
1300 tcx.lang_items().fn_once_output(),
1301 format_as_parenthesized,
1304 tcx.lang_items().fn_once_trait(),
1305 tcx.lang_items().fn_once_output(),
1306 format_as_parenthesized,
1309 let Some(trait_def_id) = trait_def_id else { continue; };
1310 let Some(assoc_item_def_id) = assoc_item_def_id else { continue; };
1311 if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1314 let param_env = tcx.param_env(def_id);
1315 let infcx = tcx.infer_ctxt().build();
1316 let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
1317 if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) }
1319 if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions()
1323 let ocx = ObligationCtxt::new_in_snapshot(&infcx);
1324 let item_ty = ocx.normalize(
1325 &ObligationCause::misc(span, def_id),
1327 tcx.mk_projection(assoc_item_def_id, substs),
1329 // FIXME(compiler-errors): We may benefit from resolving regions here.
1330 if ocx.select_where_possible().is_empty()
1331 && let item_ty = infcx.resolve_vars_if_possible(item_ty)
1332 && let Some(item_ty) = item_ty.make_suggestable(tcx, false)
1333 && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty)
1341 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::EarlyBinder<ty::TraitRef<'_>>> {
1342 let icx = ItemCtxt::new(tcx, def_id);
1343 let impl_ = tcx.hir().expect_item(def_id.expect_local()).expect_impl();
1347 .map(|ast_trait_ref| {
1348 let selfty = tcx.type_of(def_id);
1349 icx.astconv().instantiate_mono_trait_ref(
1352 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1355 .map(ty::EarlyBinder)
1358 fn check_impl_constness(
1360 constness: hir::Constness,
1361 ast_trait_ref: &hir::TraitRef<'_>,
1362 ) -> ty::BoundConstness {
1364 hir::Constness::Const => {
1365 if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1366 let trait_name = tcx.item_name(trait_def_id).to_string();
1367 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1368 trait_ref_span: ast_trait_ref.path.span,
1370 local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1374 ty::BoundConstness::NotConst
1376 ty::BoundConstness::ConstIfConst
1379 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1383 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1384 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1385 let item = tcx.hir().expect_item(def_id.expect_local());
1387 hir::ItemKind::Impl(hir::Impl {
1388 polarity: hir::ImplPolarity::Negative(span),
1392 if is_rustc_reservation {
1393 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1394 tcx.sess.span_err(span, "reservation impls can't be negative");
1396 ty::ImplPolarity::Negative
1398 hir::ItemKind::Impl(hir::Impl {
1399 polarity: hir::ImplPolarity::Positive,
1403 if is_rustc_reservation {
1404 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1406 ty::ImplPolarity::Positive
1408 hir::ItemKind::Impl(hir::Impl {
1409 polarity: hir::ImplPolarity::Positive,
1413 if is_rustc_reservation {
1414 ty::ImplPolarity::Reservation
1416 ty::ImplPolarity::Positive
1419 item => bug!("impl_polarity: {:?} not an impl", item),
1423 /// Returns the early-bound lifetimes declared in this generics
1424 /// listing. For anything other than fns/methods, this is just all
1425 /// the lifetimes that are declared. For fns or methods, we have to
1426 /// screen out those that do not appear in any where-clauses etc using
1427 /// `resolve_lifetime::early_bound_lifetimes`.
1428 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1430 generics: &'a hir::Generics<'a>,
1431 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1432 generics.params.iter().filter(move |param| match param.kind {
1433 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1438 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1439 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1440 /// inferred constraints concerning which regions outlive other regions.
1441 #[instrument(level = "debug", skip(tcx))]
1442 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1443 let mut result = tcx.explicit_predicates_of(def_id);
1444 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1445 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1446 if !inferred_outlives.is_empty() {
1448 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1449 def_id, inferred_outlives,
1451 let inferred_outlives_iter =
1452 inferred_outlives.iter().map(|(clause, span)| ((*clause).to_predicate(tcx), *span));
1453 if result.predicates.is_empty() {
1454 result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
1456 result.predicates = tcx.arena.alloc_from_iter(
1457 result.predicates.into_iter().copied().chain(inferred_outlives_iter),
1462 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1466 fn compute_sig_of_foreign_fn_decl<'tcx>(
1469 decl: &'tcx hir::FnDecl<'tcx>,
1471 ) -> ty::PolyFnSig<'tcx> {
1472 let unsafety = if abi == abi::Abi::RustIntrinsic {
1473 intrinsic_operation_unsafety(tcx, def_id)
1475 hir::Unsafety::Unsafe
1477 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1479 ItemCtxt::new(tcx, def_id).astconv().ty_of_fn(hir_id, unsafety, abi, decl, None, None);
1481 // Feature gate SIMD types in FFI, since I am not sure that the
1482 // ABIs are handled at all correctly. -huonw
1483 if abi != abi::Abi::RustIntrinsic
1484 && abi != abi::Abi::PlatformIntrinsic
1485 && !tcx.features().simd_ffi
1487 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1492 .span_to_snippet(ast_ty.span)
1493 .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1498 "use of SIMD type{} in FFI is highly experimental and \
1499 may result in invalid code",
1503 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1507 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1510 if let hir::FnRetTy::Return(ty) = decl.output {
1511 check(ty, fty.output().skip_binder())
1518 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1519 match tcx.hir().get_if_local(def_id) {
1520 Some(Node::ForeignItem(..)) => true,
1522 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1526 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1527 match tcx.hir().get_if_local(def_id) {
1528 Some(Node::Expr(&rustc_hir::Expr {
1529 kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1531 })) => tcx.hir().body(body).generator_kind(),
1533 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1537 fn is_type_alias_impl_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1538 match tcx.hir().get_if_local(def_id) {
1539 Some(Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(opaque), .. })) => {
1540 matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias)
1542 Some(_) => bug!("tried getting opaque_ty_origin for non-opaque: {:?}", def_id),
1543 _ => bug!("tried getting opaque_ty_origin for non-local def-id {:?}", def_id),