1 use super::coercion::CoerceMany;
2 use super::compare_method::check_type_bounds;
3 use super::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl};
6 use rustc_attr as attr;
7 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::lang_items::LangItem;
12 use rustc_hir::{def::Res, ItemKind, Node, PathSegment};
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
15 use rustc_infer::traits::Obligation;
16 use rustc_middle::hir::nested_filter;
17 use rustc_middle::ty::fold::TypeFoldable;
18 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
19 use rustc_middle::ty::subst::GenericArgKind;
20 use rustc_middle::ty::util::{Discr, IntTypeExt};
21 use rustc_middle::ty::{self, ParamEnv, ToPredicate, Ty, TyCtxt};
22 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
23 use rustc_span::symbol::sym;
24 use rustc_span::{self, Span};
25 use rustc_target::spec::abi::Abi;
26 use rustc_trait_selection::traits;
27 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
28 use rustc_ty_utils::representability::{self, Representability};
31 use std::ops::ControlFlow;
33 pub fn check_wf_new(tcx: TyCtxt<'_>) {
34 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
35 tcx.hir().par_visit_all_item_likes(&visit);
38 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
39 match tcx.sess.target.is_abi_supported(abi) {
46 "`{abi}` is not a supported ABI for the current target",
51 tcx.struct_span_lint_hir(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
52 lint.build("use of calling convention not supported on this target").emit();
57 // This ABI is only allowed on function pointers
58 if abi == Abi::CCmseNonSecureCall {
63 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
69 /// Helper used for fns and closures. Does the grungy work of checking a function
70 /// body and returns the function context used for that purpose, since in the case of a fn item
71 /// there is still a bit more to do.
74 /// * inherited: other fields inherited from the enclosing fn (if any)
75 #[instrument(skip(inherited, body), level = "debug")]
76 pub(super) fn check_fn<'a, 'tcx>(
77 inherited: &'a Inherited<'a, 'tcx>,
78 param_env: ty::ParamEnv<'tcx>,
79 fn_sig: ty::FnSig<'tcx>,
80 decl: &'tcx hir::FnDecl<'tcx>,
82 body: &'tcx hir::Body<'tcx>,
83 can_be_generator: Option<hir::Movability>,
84 return_type_pre_known: bool,
85 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
86 // Create the function context. This is either derived from scratch or,
87 // in the case of closures, based on the outer context.
88 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
89 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
90 fcx.return_type_pre_known = return_type_pre_known;
96 let declared_ret_ty = fn_sig.output();
99 fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
105 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
106 fcx.ret_type_span = Some(decl.output.span());
108 let span = body.value.span;
110 fn_maybe_err(tcx, span, fn_sig.abi);
112 if fn_sig.abi == Abi::RustCall {
113 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
116 let item = match tcx.hir().get(fn_id) {
117 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
118 Node::ImplItem(hir::ImplItem {
119 kind: hir::ImplItemKind::Fn(header, ..), ..
121 Node::TraitItem(hir::TraitItem {
122 kind: hir::TraitItemKind::Fn(header, ..),
125 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
126 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
127 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
130 if let Some(header) = item {
131 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple");
135 if fn_sig.inputs().len() != expected_args {
138 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
139 // This will probably require wide-scale changes to support a TupleKind obligation
140 // We can't resolve this without knowing the type of the param
141 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
147 if body.generator_kind.is_some() && can_be_generator.is_some() {
149 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
150 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
152 // Resume type defaults to `()` if the generator has no argument.
153 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
155 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
158 GatherLocalsVisitor::new(&fcx).visit_body(body);
160 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
161 // (as it's created inside the body itself, not passed in from outside).
162 let maybe_va_list = if fn_sig.c_variadic {
163 let span = body.params.last().unwrap().span;
164 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
165 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
167 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
172 // Add formal parameters.
173 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
174 let inputs_fn = fn_sig.inputs().iter().copied();
175 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
176 // Check the pattern.
177 let ty_span = try { inputs_hir?.get(idx)?.span };
178 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
180 // Check that argument is Sized.
181 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
182 // for simple cases like `fn foo(x: Trait)`,
183 // where we would error once on the parameter as a whole, and once on the binding `x`.
184 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
185 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
188 fcx.write_ty(param.hir_id, param_ty);
191 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
193 fcx.in_tail_expr = true;
194 if let ty::Dynamic(..) = declared_ret_ty.kind() {
195 // FIXME: We need to verify that the return type is `Sized` after the return expression has
196 // been evaluated so that we have types available for all the nodes being returned, but that
197 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
198 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
199 // while keeping the current ordering we will ignore the tail expression's type because we
200 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
201 // because we will trigger "unreachable expression" lints unconditionally.
202 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
203 // case that a newcomer might make, returning a bare trait, and in that case we populate
204 // the tail expression's type so that the suggestion will be correct, but ignore all other
206 fcx.check_expr(&body.value);
207 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
209 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
210 fcx.check_return_expr(&body.value, false);
212 fcx.in_tail_expr = false;
214 // We insert the deferred_generator_interiors entry after visiting the body.
215 // This ensures that all nested generators appear before the entry of this generator.
216 // resolve_generator_interiors relies on this property.
217 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
219 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
220 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
222 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
223 Some(GeneratorTypes {
227 movability: can_be_generator.unwrap(),
233 // Finalize the return check by taking the LUB of the return types
234 // we saw and assigning it to the expected return type. This isn't
235 // really expected to fail, since the coercions would have failed
236 // earlier when trying to find a LUB.
237 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
238 let mut actual_return_ty = coercion.complete(&fcx);
239 debug!("actual_return_ty = {:?}", actual_return_ty);
240 if let ty::Dynamic(..) = declared_ret_ty.kind() {
241 // We have special-cased the case where the function is declared
242 // `-> dyn Foo` and we don't actually relate it to the
243 // `fcx.ret_coercion`, so just substitute a type variable.
245 fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
246 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
248 fcx.demand_suptype(span, declared_ret_ty, actual_return_ty);
250 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
251 if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
252 && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
254 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
255 if *declared_ret_ty.kind() != ty::Never {
256 sess.span_err(decl.output.span(), "return type should be `!`");
259 let inputs = fn_sig.inputs();
260 let span = hir.span(fn_id);
261 if inputs.len() == 1 {
262 let arg_is_panic_info = match *inputs[0].kind() {
263 ty::Ref(region, ty, mutbl) => match *ty.kind() {
264 ty::Adt(ref adt, _) => {
265 adt.did() == panic_info_did
266 && mutbl == hir::Mutability::Not
267 && !region.is_static()
274 if !arg_is_panic_info {
275 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
278 if let Node::Item(item) = hir.get(fn_id)
279 && let ItemKind::Fn(_, ref generics, _) = item.kind
280 && !generics.params.is_empty()
282 sess.span_err(span, "should have no type parameters");
285 let span = sess.source_map().guess_head_span(span);
286 sess.span_err(span, "function should have one argument");
289 sess.err("language item required, but not found: `panic_info`");
293 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
294 if let Some(alloc_error_handler_did) = tcx.lang_items().oom()
295 && alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id()
297 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
298 if *declared_ret_ty.kind() != ty::Never {
299 sess.span_err(decl.output.span(), "return type should be `!`");
302 let inputs = fn_sig.inputs();
303 let span = hir.span(fn_id);
304 if inputs.len() == 1 {
305 let arg_is_alloc_layout = match inputs[0].kind() {
306 ty::Adt(ref adt, _) => adt.did() == alloc_layout_did,
310 if !arg_is_alloc_layout {
311 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
314 if let Node::Item(item) = hir.get(fn_id)
315 && let ItemKind::Fn(_, ref generics, _) = item.kind
316 && !generics.params.is_empty()
320 "`#[alloc_error_handler]` function should have no type parameters",
324 let span = sess.source_map().guess_head_span(span);
325 sess.span_err(span, "function should have one argument");
328 sess.err("language item required, but not found: `alloc_layout`");
335 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
336 let def = tcx.adt_def(def_id);
337 def.destructor(tcx); // force the destructor to be evaluated
338 check_representable(tcx, span, def_id);
340 if def.repr().simd() {
341 check_simd(tcx, span, def_id);
344 check_transparent(tcx, span, def);
345 check_packed(tcx, span, def);
348 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
349 let def = tcx.adt_def(def_id);
350 def.destructor(tcx); // force the destructor to be evaluated
351 check_representable(tcx, span, def_id);
352 check_transparent(tcx, span, def);
353 check_union_fields(tcx, span, def_id);
354 check_packed(tcx, span, def);
357 /// Check that the fields of the `union` do not need dropping.
358 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
359 let item_type = tcx.type_of(item_def_id);
360 if let ty::Adt(def, substs) = item_type.kind() {
361 assert!(def.is_union());
362 let fields = &def.non_enum_variant().fields;
363 let param_env = tcx.param_env(item_def_id);
364 for field in fields {
365 let field_ty = field.ty(tcx, substs);
366 if field_ty.needs_drop(tcx, param_env) {
367 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
368 // We are currently checking the type this field came from, so it must be local.
369 Some(Node::Field(field)) => (field.span, field.ty.span),
370 _ => unreachable!("mir field has to correspond to hir field"),
376 "unions cannot contain fields that may need dropping"
379 "a type is guaranteed not to need dropping \
380 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
382 .multipart_suggestion_verbose(
383 "when the type does not implement `Copy`, \
384 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
386 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
387 (ty_span.shrink_to_hi(), ">".into()),
389 Applicability::MaybeIncorrect,
396 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
401 /// Check that a `static` is inhabited.
402 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
403 // Make sure statics are inhabited.
404 // Other parts of the compiler assume that there are no uninhabited places. In principle it
405 // would be enough to check this for `extern` statics, as statics with an initializer will
406 // have UB during initialization if they are uninhabited, but there also seems to be no good
407 // reason to allow any statics to be uninhabited.
408 let ty = tcx.type_of(def_id);
409 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
411 // Foreign statics that overflow their allowed size should emit an error
412 Err(LayoutError::SizeOverflow(_))
414 let node = tcx.hir().get_by_def_id(def_id);
417 hir::Node::ForeignItem(hir::ForeignItem {
418 kind: hir::ForeignItemKind::Static(..),
425 .struct_span_err(span, "extern static is too large for the current architecture")
429 // Generic statics are rejected, but we still reach this case.
431 tcx.sess.delay_span_bug(span, &e.to_string());
435 if layout.abi.is_uninhabited() {
436 tcx.struct_span_lint_hir(
438 tcx.hir().local_def_id_to_hir_id(def_id),
441 lint.build("static of uninhabited type")
442 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
449 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
450 /// projections that would result in "inheriting lifetimes".
451 pub(super) fn check_opaque<'tcx>(
454 substs: SubstsRef<'tcx>,
456 origin: &hir::OpaqueTyOrigin,
458 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
459 if tcx.type_of(def_id).references_error() {
462 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
465 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
468 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
469 /// in "inheriting lifetimes".
470 #[instrument(level = "debug", skip(tcx, span))]
471 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
476 let item = tcx.hir().expect_item(def_id);
477 debug!(?item, ?span);
479 struct FoundParentLifetime;
480 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
481 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
482 type BreakTy = FoundParentLifetime;
484 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
485 debug!("FindParentLifetimeVisitor: r={:?}", r);
486 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
487 if index < self.0.parent_count as u32 {
488 return ControlFlow::Break(FoundParentLifetime);
490 return ControlFlow::CONTINUE;
494 r.super_visit_with(self)
497 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
498 if let ty::ConstKind::Unevaluated(..) = c.val() {
499 // FIXME(#72219) We currently don't detect lifetimes within substs
500 // which would violate this check. Even though the particular substitution is not used
501 // within the const, this should still be fixed.
502 return ControlFlow::CONTINUE;
504 c.super_visit_with(self)
508 struct ProhibitOpaqueVisitor<'tcx> {
510 opaque_identity_ty: Ty<'tcx>,
511 generics: &'tcx ty::Generics,
512 selftys: Vec<(Span, Option<String>)>,
515 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
516 type BreakTy = Ty<'tcx>;
518 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
519 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
520 if t == self.opaque_identity_ty {
521 ControlFlow::CONTINUE
523 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
524 .map_break(|FoundParentLifetime| t)
529 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
530 type NestedFilter = nested_filter::OnlyBodies;
532 fn nested_visit_map(&mut self) -> Self::Map {
536 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
538 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
541 res: Some(Res::SelfTy { trait_: _, alias_to: impl_ref }),
546 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
547 self.selftys.push((path.span, impl_ty_name));
553 hir::intravisit::walk_ty(self, arg);
557 if let ItemKind::OpaqueTy(hir::OpaqueTy {
558 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
562 let mut visitor = ProhibitOpaqueVisitor {
563 opaque_identity_ty: tcx.mk_opaque(
565 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
567 generics: tcx.generics_of(def_id),
571 let prohibit_opaque = tcx
572 .explicit_item_bounds(def_id)
574 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
576 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
577 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
580 if let Some(ty) = prohibit_opaque.break_value() {
581 visitor.visit_item(&item);
582 let is_async = match item.kind {
583 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
584 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
589 let mut err = struct_span_err!(
593 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
595 if is_async { "async fn" } else { "impl Trait" },
598 for (span, name) in visitor.selftys {
601 "consider spelling out the type instead",
602 name.unwrap_or_else(|| format!("{:?}", ty)),
603 Applicability::MaybeIncorrect,
611 /// Checks that an opaque type does not contain cycles.
612 pub(super) fn check_opaque_for_cycles<'tcx>(
615 substs: SubstsRef<'tcx>,
617 origin: &hir::OpaqueTyOrigin,
618 ) -> Result<(), ErrorGuaranteed> {
619 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
620 let reported = match origin {
621 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
622 _ => opaque_type_cycle_error(tcx, def_id, span),
630 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
632 /// This is mostly checked at the places that specify the opaque type, but we
633 /// check those cases in the `param_env` of that function, which may have
634 /// bounds not on this opaque type:
636 /// type X<T> = impl Clone
637 /// fn f<T: Clone>(t: T) -> X<T> {
641 /// Without this check the above code is incorrectly accepted: we would ICE if
642 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
643 #[instrument(level = "debug", skip(tcx))]
644 fn check_opaque_meets_bounds<'tcx>(
647 substs: SubstsRef<'tcx>,
649 origin: &hir::OpaqueTyOrigin,
651 let hidden_type = tcx.type_of(def_id).subst(tcx, substs);
653 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
654 let defining_use_anchor = match *origin {
655 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
656 hir::OpaqueTyOrigin::TyAlias => def_id,
658 let param_env = tcx.param_env(defining_use_anchor);
660 tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
661 let inh = Inherited::new(infcx, def_id);
662 let infcx = &inh.infcx;
663 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
665 let misc_cause = traits::ObligationCause::misc(span, hir_id);
667 match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) {
668 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
670 tcx.sess.delay_span_bug(
672 &format!("could not unify `{hidden_type}` with revealed type:\n{ty_err}"),
677 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
678 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
679 // hidden type is well formed even without those bounds.
681 ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx);
682 inh.register_predicate(Obligation::new(misc_cause, param_env, predicate));
684 // Check that all obligations are satisfied by the implementation's
686 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
687 if !errors.is_empty() {
688 infcx.report_fulfillment_errors(&errors, None, false);
692 // Checked when type checking the function containing them.
693 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
694 // Can have different predicates to their defining use
695 hir::OpaqueTyOrigin::TyAlias => {
696 // Finally, resolve all regions. This catches wily misuses of
697 // lifetime parameters.
698 let fcx = FnCtxt::new(&inh, param_env, hir_id);
699 fcx.regionck_item(hir_id, span, FxHashSet::default());
703 // Clean up after ourselves
704 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
708 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
710 "check_item_type(it.def_id={:?}, it.name={})",
712 tcx.def_path_str(it.def_id.to_def_id())
714 let _indenter = indenter();
716 // Consts can play a role in type-checking, so they are included here.
717 hir::ItemKind::Static(..) => {
718 tcx.ensure().typeck(it.def_id);
719 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
720 check_static_inhabited(tcx, it.def_id, it.span);
722 hir::ItemKind::Const(..) => {
723 tcx.ensure().typeck(it.def_id);
725 hir::ItemKind::Enum(ref enum_definition, _) => {
726 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
728 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
729 hir::ItemKind::Impl(ref impl_) => {
730 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
731 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
732 check_impl_items_against_trait(
739 check_on_unimplemented(tcx, it);
742 hir::ItemKind::Trait(_, _, _, _, ref items) => {
743 check_on_unimplemented(tcx, it);
745 for item in items.iter() {
746 let item = tcx.hir().trait_item(item.id);
748 hir::TraitItemKind::Fn(ref sig, _) => {
749 let abi = sig.header.abi;
750 fn_maybe_err(tcx, item.ident.span, abi);
752 hir::TraitItemKind::Type(.., Some(default)) => {
753 let assoc_item = tcx.associated_item(item.def_id);
755 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
756 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
761 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
768 hir::ItemKind::Struct(..) => {
769 check_struct(tcx, it.def_id, it.span);
771 hir::ItemKind::Union(..) => {
772 check_union(tcx, it.def_id, it.span);
774 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
775 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
776 // `async-std` (and `pub async fn` in general).
777 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
778 // See https://github.com/rust-lang/rust/issues/75100
779 if !tcx.sess.opts.actually_rustdoc {
780 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
781 check_opaque(tcx, it.def_id, substs, it.span, &origin);
784 hir::ItemKind::TyAlias(..) => {
785 let pty_ty = tcx.type_of(it.def_id);
786 let generics = tcx.generics_of(it.def_id);
787 check_type_params_are_used(tcx, &generics, pty_ty);
789 hir::ItemKind::ForeignMod { abi, items } => {
790 check_abi(tcx, it.hir_id(), it.span, abi);
792 if abi == Abi::RustIntrinsic {
794 let item = tcx.hir().foreign_item(item.id);
795 intrinsic::check_intrinsic_type(tcx, item);
797 } else if abi == Abi::PlatformIntrinsic {
799 let item = tcx.hir().foreign_item(item.id);
800 intrinsic::check_platform_intrinsic_type(tcx, item);
804 let def_id = item.id.def_id;
805 let generics = tcx.generics_of(def_id);
806 let own_counts = generics.own_counts();
807 if generics.params.len() - own_counts.lifetimes != 0 {
808 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
809 (_, 0) => ("type", "types", Some("u32")),
810 // We don't specify an example value, because we can't generate
811 // a valid value for any type.
812 (0, _) => ("const", "consts", None),
813 _ => ("type or const", "types or consts", None),
819 "foreign items may not have {kinds} parameters",
821 .span_label(item.span, &format!("can't have {kinds} parameters"))
823 // FIXME: once we start storing spans for type arguments, turn this
824 // into a suggestion.
826 "replace the {} parameters with concrete {}{}",
829 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
835 let item = tcx.hir().foreign_item(item.id);
837 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
838 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
840 hir::ForeignItemKind::Static(..) => {
841 check_static_inhabited(tcx, def_id, item.span);
848 _ => { /* nothing to do */ }
852 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
853 // an error would be reported if this fails.
854 let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
857 pub(super) fn check_specialization_validity<'tcx>(
859 trait_def: &ty::TraitDef,
860 trait_item: &ty::AssocItem,
862 impl_item: &hir::ImplItemRef,
864 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
865 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
866 if parent.is_from_trait() {
869 Some((parent, parent.item(tcx, trait_item.def_id)))
873 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
875 // Parent impl exists, and contains the parent item we're trying to specialize, but
876 // doesn't mark it `default`.
877 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
878 Some(Err(parent_impl.def_id()))
881 // Parent impl contains item and makes it specializable.
882 Some(_) => Some(Ok(())),
884 // Parent impl doesn't mention the item. This means it's inherited from the
885 // grandparent. In that case, if parent is a `default impl`, inherited items use the
886 // "defaultness" from the grandparent, else they are final.
888 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
891 Some(Err(parent_impl.def_id()))
897 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
898 // item. This is allowed, the item isn't actually getting specialized here.
899 let result = opt_result.unwrap_or(Ok(()));
901 if let Err(parent_impl) = result {
902 report_forbidden_specialization(tcx, impl_item, parent_impl);
906 fn check_impl_items_against_trait<'tcx>(
908 full_impl_span: Span,
910 impl_trait_ref: ty::TraitRef<'tcx>,
911 impl_item_refs: &[hir::ImplItemRef],
913 // If the trait reference itself is erroneous (so the compilation is going
914 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
915 // isn't populated for such impls.
916 if impl_trait_ref.references_error() {
920 // Negative impls are not expected to have any items
921 match tcx.impl_polarity(impl_id) {
922 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
923 ty::ImplPolarity::Negative => {
924 if let [first_item_ref, ..] = impl_item_refs {
925 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
930 "negative impls cannot have any items"
938 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
940 for impl_item in impl_item_refs {
941 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
942 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
943 tcx.associated_item(trait_item_id)
945 // Checked in `associated_item`.
946 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
949 let impl_item_full = tcx.hir().impl_item(impl_item.id);
950 match impl_item_full.kind {
951 hir::ImplItemKind::Const(..) => {
952 // Find associated const definition.
961 hir::ImplItemKind::Fn(..) => {
962 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
972 hir::ImplItemKind::TyAlias(impl_ty) => {
973 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
985 check_specialization_validity(
994 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
995 // Check for missing items from trait
996 let mut missing_items = Vec::new();
998 let mut must_implement_one_of: Option<&[Ident]> =
999 trait_def.must_implement_one_of.as_deref();
1001 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1002 let is_implemented = ancestors
1003 .leaf_def(tcx, trait_item_id)
1004 .map_or(false, |node_item| node_item.item.defaultness.has_value());
1006 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1007 missing_items.push(tcx.associated_item(trait_item_id));
1010 if let Some(required_items) = &must_implement_one_of {
1011 // true if this item is specifically implemented in this impl
1012 let is_implemented_here = ancestors
1013 .leaf_def(tcx, trait_item_id)
1014 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1016 if is_implemented_here {
1017 let trait_item = tcx.associated_item(trait_item_id);
1018 if required_items.contains(&trait_item.ident(tcx)) {
1019 must_implement_one_of = None;
1025 if !missing_items.is_empty() {
1026 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1027 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1030 if let Some(missing_items) = must_implement_one_of {
1031 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1033 .get_attrs(impl_trait_ref.def_id)
1035 .find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1036 .map(|attr| attr.span);
1038 missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1043 /// Checks whether a type can be represented in memory. In particular, it
1044 /// identifies types that contain themselves without indirection through a
1045 /// pointer, which would mean their size is unbounded.
1046 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1047 let rty = tcx.type_of(item_def_id);
1049 // Check that it is possible to represent this type. This call identifies
1050 // (1) types that contain themselves and (2) types that contain a different
1051 // recursive type. It is only necessary to throw an error on those that
1052 // contain themselves. For case 2, there must be an inner type that will be
1053 // caught by case 1.
1054 match representability::ty_is_representable(tcx, rty, sp, None) {
1055 Representability::SelfRecursive(spans) => {
1056 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1059 Representability::Representable | Representability::ContainsRecursive => (),
1064 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1065 let t = tcx.type_of(def_id);
1066 if let ty::Adt(def, substs) = t.kind()
1069 let fields = &def.non_enum_variant().fields;
1070 if fields.is_empty() {
1071 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1074 let e = fields[0].ty(tcx, substs);
1075 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1076 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1077 .span_label(sp, "SIMD elements must have the same type")
1082 let len = if let ty::Array(_ty, c) = e.kind() {
1083 c.try_eval_usize(tcx, tcx.param_env(def.did()))
1085 Some(fields.len() as u64)
1087 if let Some(len) = len {
1089 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1091 } else if len > MAX_SIMD_LANES {
1096 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1103 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1104 // These are scalar types which directly match a "machine" type
1105 // Yes: Integers, floats, "thin" pointers
1106 // No: char, "fat" pointers, compound types
1108 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1109 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1110 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1114 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1116 { /* struct([f32; 4]) is ok */ }
1122 "SIMD vector element type should be a \
1123 primitive scalar (integer/float/pointer) type"
1132 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1133 let repr = def.repr();
1135 for attr in tcx.get_attrs(def.did()).iter() {
1136 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1137 if let attr::ReprPacked(pack) = r
1138 && let Some(repr_pack) = repr.pack
1139 && pack as u64 != repr_pack.bytes()
1145 "type has conflicting packed representation hints"
1151 if repr.align.is_some() {
1156 "type has conflicting packed and align representation hints"
1160 if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1161 let mut err = struct_span_err!(
1165 "packed type cannot transitively contain a `#[repr(align)]` type"
1169 tcx.def_span(def_spans[0].0),
1171 "`{}` has a `#[repr(align)]` attribute",
1172 tcx.item_name(def_spans[0].0)
1176 if def_spans.len() > 2 {
1177 let mut first = true;
1178 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1179 let ident = tcx.item_name(*adt_def);
1184 "`{}` contains a field of type `{}`",
1185 tcx.type_of(def.did()),
1189 format!("...which contains a field of type `{ident}`")
1202 pub(super) fn check_packed_inner(
1205 stack: &mut Vec<DefId>,
1206 ) -> Option<Vec<(DefId, Span)>> {
1207 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1208 if def.is_struct() || def.is_union() {
1209 if def.repr().align.is_some() {
1210 return Some(vec![(def.did(), DUMMY_SP)]);
1214 for field in &def.non_enum_variant().fields {
1215 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1216 && !stack.contains(&def.did())
1217 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1219 defs.push((def.did(), field.ident(tcx).span));
1230 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1231 if !adt.repr().transparent() {
1234 let sp = tcx.sess.source_map().guess_head_span(sp);
1236 if adt.is_union() && !tcx.features().transparent_unions {
1238 &tcx.sess.parse_sess,
1239 sym::transparent_unions,
1241 "transparent unions are unstable",
1246 if adt.variants().len() != 1 {
1247 bad_variant_count(tcx, adt, sp, adt.did());
1248 if adt.variants().is_empty() {
1249 // Don't bother checking the fields. No variants (and thus no fields) exist.
1254 // For each field, figure out if it's known to be a ZST and align(1)
1255 let field_infos = adt.all_fields().map(|field| {
1256 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1257 let param_env = tcx.param_env(field.did);
1258 let layout = tcx.layout_of(param_env.and(ty));
1259 // We are currently checking the type this field came from, so it must be local
1260 let span = tcx.hir().span_if_local(field.did).unwrap();
1261 let zst = layout.map_or(false, |layout| layout.is_zst());
1262 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1266 let non_zst_fields =
1267 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1268 let non_zst_count = non_zst_fields.clone().count();
1269 if non_zst_count >= 2 {
1270 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1272 for (span, zst, align1) in field_infos {
1278 "zero-sized field in transparent {} has alignment larger than 1",
1281 .span_label(span, "has alignment larger than 1")
1287 #[allow(trivial_numeric_casts)]
1288 fn check_enum<'tcx>(
1291 vs: &'tcx [hir::Variant<'tcx>],
1294 let def = tcx.adt_def(def_id);
1295 def.destructor(tcx); // force the destructor to be evaluated
1298 let attributes = tcx.get_attrs(def_id.to_def_id());
1299 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1304 "unsupported representation for zero-variant enum"
1306 .span_label(sp, "zero-variant enum")
1311 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1312 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1313 if !tcx.features().repr128 {
1315 &tcx.sess.parse_sess,
1318 "repr with 128-bit type is unstable",
1325 if let Some(ref e) = v.disr_expr {
1326 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1330 if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1331 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1333 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1334 let has_non_units = vs.iter().any(|var| !is_unit(var));
1335 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1336 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1338 if disr_non_unit || (disr_units && has_non_units) {
1340 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1345 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1346 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1347 // Check for duplicate discriminant values
1348 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1349 let variant_did = def.variant(VariantIdx::new(i)).def_id;
1350 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1351 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1352 let i_span = match variant_i.disr_expr {
1353 Some(ref expr) => tcx.hir().span(expr.hir_id),
1354 None => tcx.def_span(variant_did),
1356 let span = match v.disr_expr {
1357 Some(ref expr) => tcx.hir().span(expr.hir_id),
1360 let display_discr = display_discriminant_value(tcx, v, discr.val);
1361 let display_discr_i = display_discriminant_value(tcx, variant_i, disr_vals[i].val);
1366 "discriminant value `{}` already exists",
1369 .span_label(i_span, format!("first use of {display_discr_i}"))
1370 .span_label(span, format!("enum already has {display_discr}"))
1373 disr_vals.push(discr);
1376 check_representable(tcx, sp, def_id);
1377 check_transparent(tcx, sp, def);
1380 /// Format an enum discriminant value for use in a diagnostic message.
1381 fn display_discriminant_value<'tcx>(
1383 variant: &hir::Variant<'_>,
1386 if let Some(expr) = &variant.disr_expr {
1387 let body = &tcx.hir().body(expr.body).value;
1388 if let hir::ExprKind::Lit(lit) = &body.kind
1389 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1390 && evaluated != *lit_value
1392 return format!("`{evaluated}` (overflowed from `{lit_value}`)");
1395 format!("`{}`", evaluated)
1398 pub(super) fn check_type_params_are_used<'tcx>(
1400 generics: &ty::Generics,
1403 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1405 assert_eq!(generics.parent, None);
1407 if generics.own_counts().types == 0 {
1411 let mut params_used = BitSet::new_empty(generics.params.len());
1413 if ty.references_error() {
1414 // If there is already another error, do not emit
1415 // an error for not using a type parameter.
1416 assert!(tcx.sess.has_errors().is_some());
1420 for leaf in ty.walk() {
1421 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1422 && let ty::Param(param) = leaf_ty.kind()
1424 debug!("found use of ty param {:?}", param);
1425 params_used.insert(param.index);
1429 for param in &generics.params {
1430 if !params_used.contains(param.index)
1431 && let ty::GenericParamDefKind::Type { .. } = param.kind
1433 let span = tcx.def_span(param.def_id);
1438 "type parameter `{}` is unused",
1441 .span_label(span, "unused type parameter")
1447 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1448 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1451 pub(super) use wfcheck::check_item_well_formed;
1453 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1455 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1457 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1458 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1459 .span_label(span, "recursive `async fn`")
1460 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1462 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1467 /// Emit an error for recursive opaque types.
1469 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1470 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1473 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1474 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1475 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1476 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1478 let mut label = false;
1479 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1480 let typeck_results = tcx.typeck(def_id);
1484 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1485 .all(|ty| matches!(ty.kind(), ty::Never))
1490 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1491 .map(|expr| expr.span)
1492 .collect::<Vec<Span>>();
1493 let span_len = spans.len();
1495 err.span_label(spans[0], "this returned value is of `!` type");
1497 let mut multispan: MultiSpan = spans.clone().into();
1500 .push_span_label(span, "this returned value is of `!` type".to_string());
1502 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1504 err.help("this error will resolve once the item's body returns a concrete type");
1506 let mut seen = FxHashSet::default();
1508 err.span_label(span, "recursive opaque type");
1510 for (sp, ty) in visitor
1513 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1514 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1516 struct OpaqueTypeCollector(Vec<DefId>);
1517 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1518 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1520 ty::Opaque(def, _) => {
1522 ControlFlow::CONTINUE
1524 _ => t.super_visit_with(self),
1528 let mut visitor = OpaqueTypeCollector(vec![]);
1529 ty.visit_with(&mut visitor);
1530 for def_id in visitor.0 {
1531 let ty_span = tcx.def_span(def_id);
1532 if !seen.contains(&ty_span) {
1533 err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1534 seen.insert(ty_span);
1536 err.span_label(sp, &format!("returning here with type `{ty}`"));
1542 err.span_label(span, "cannot resolve opaque type");