1 use crate::check::wfcheck::for_item;
3 use super::coercion::CoerceMany;
4 use super::compare_method::check_type_bounds;
5 use super::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl};
8 use rustc_attr as attr;
9 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_hir::{def::Res, ItemKind, Node, PathSegment};
15 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
16 use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
17 use rustc_infer::traits::Obligation;
18 use rustc_middle::hir::nested_filter;
19 use rustc_middle::ty::fold::TypeFoldable;
20 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
21 use rustc_middle::ty::subst::GenericArgKind;
22 use rustc_middle::ty::util::{Discr, IntTypeExt};
23 use rustc_middle::ty::{self, ParamEnv, ToPredicate, Ty, TyCtxt};
24 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
25 use rustc_span::symbol::sym;
26 use rustc_span::{self, Span};
27 use rustc_target::spec::abi::Abi;
28 use rustc_trait_selection::traits;
29 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
30 use rustc_ty_utils::representability::{self, Representability};
32 use rustc_hir::def::DefKind;
34 use std::ops::ControlFlow;
36 pub fn check_wf_new(tcx: TyCtxt<'_>) {
37 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
38 tcx.hir().par_visit_all_item_likes(&visit);
41 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
42 match tcx.sess.target.is_abi_supported(abi) {
49 "`{abi}` is not a supported ABI for the current target",
54 tcx.struct_span_lint_hir(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
55 lint.build("use of calling convention not supported on this target").emit();
60 // This ABI is only allowed on function pointers
61 if abi == Abi::CCmseNonSecureCall {
66 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
72 /// Helper used for fns and closures. Does the grungy work of checking a function
73 /// body and returns the function context used for that purpose, since in the case of a fn item
74 /// there is still a bit more to do.
77 /// * inherited: other fields inherited from the enclosing fn (if any)
78 #[instrument(skip(inherited, body), level = "debug")]
79 pub(super) fn check_fn<'a, 'tcx>(
80 inherited: &'a Inherited<'a, 'tcx>,
81 param_env: ty::ParamEnv<'tcx>,
82 fn_sig: ty::FnSig<'tcx>,
83 decl: &'tcx hir::FnDecl<'tcx>,
85 body: &'tcx hir::Body<'tcx>,
86 can_be_generator: Option<hir::Movability>,
87 return_type_pre_known: bool,
88 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
89 // Create the function context. This is either derived from scratch or,
90 // in the case of closures, based on the outer context.
91 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
92 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
93 fcx.return_type_pre_known = return_type_pre_known;
99 let declared_ret_ty = fn_sig.output();
102 fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
108 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
109 fcx.ret_type_span = Some(decl.output.span());
111 let span = body.value.span;
113 fn_maybe_err(tcx, span, fn_sig.abi);
115 if fn_sig.abi == Abi::RustCall {
116 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
119 let item = match tcx.hir().get(fn_id) {
120 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
121 Node::ImplItem(hir::ImplItem {
122 kind: hir::ImplItemKind::Fn(header, ..), ..
124 Node::TraitItem(hir::TraitItem {
125 kind: hir::TraitItemKind::Fn(header, ..),
128 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
129 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
130 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
133 if let Some(header) = item {
134 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple");
138 if fn_sig.inputs().len() != expected_args {
141 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
142 // This will probably require wide-scale changes to support a TupleKind obligation
143 // We can't resolve this without knowing the type of the param
144 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
150 if body.generator_kind.is_some() && can_be_generator.is_some() {
152 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
153 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
155 // Resume type defaults to `()` if the generator has no argument.
156 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
158 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
161 GatherLocalsVisitor::new(&fcx).visit_body(body);
163 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
164 // (as it's created inside the body itself, not passed in from outside).
165 let maybe_va_list = if fn_sig.c_variadic {
166 let span = body.params.last().unwrap().span;
167 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
168 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
170 Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
175 // Add formal parameters.
176 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
177 let inputs_fn = fn_sig.inputs().iter().copied();
178 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
179 // Check the pattern.
180 let ty_span = try { inputs_hir?.get(idx)?.span };
181 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
183 // Check that argument is Sized.
184 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
185 // for simple cases like `fn foo(x: Trait)`,
186 // where we would error once on the parameter as a whole, and once on the binding `x`.
187 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
188 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
191 fcx.write_ty(param.hir_id, param_ty);
194 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
196 fcx.in_tail_expr = true;
197 if let ty::Dynamic(..) = declared_ret_ty.kind() {
198 // FIXME: We need to verify that the return type is `Sized` after the return expression has
199 // been evaluated so that we have types available for all the nodes being returned, but that
200 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
201 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
202 // while keeping the current ordering we will ignore the tail expression's type because we
203 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
204 // because we will trigger "unreachable expression" lints unconditionally.
205 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
206 // case that a newcomer might make, returning a bare trait, and in that case we populate
207 // the tail expression's type so that the suggestion will be correct, but ignore all other
209 fcx.check_expr(&body.value);
210 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
212 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
213 fcx.check_return_expr(&body.value, false);
215 fcx.in_tail_expr = false;
217 // We insert the deferred_generator_interiors entry after visiting the body.
218 // This ensures that all nested generators appear before the entry of this generator.
219 // resolve_generator_interiors relies on this property.
220 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
222 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
223 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
225 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
226 Some(GeneratorTypes {
230 movability: can_be_generator.unwrap(),
236 // Finalize the return check by taking the LUB of the return types
237 // we saw and assigning it to the expected return type. This isn't
238 // really expected to fail, since the coercions would have failed
239 // earlier when trying to find a LUB.
240 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
241 let mut actual_return_ty = coercion.complete(&fcx);
242 debug!("actual_return_ty = {:?}", actual_return_ty);
243 if let ty::Dynamic(..) = declared_ret_ty.kind() {
244 // We have special-cased the case where the function is declared
245 // `-> dyn Foo` and we don't actually relate it to the
246 // `fcx.ret_coercion`, so just substitute a type variable.
248 fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
249 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
252 // HACK(oli-obk, compiler-errors): We should be comparing this against
253 // `declared_ret_ty`, but then anything uninferred would be inferred to
254 // the opaque type itself. That again would cause writeback to assume
255 // we have a recursive call site and do the sadly stabilized fallback to `()`.
256 fcx.demand_suptype(span, ret_ty, actual_return_ty);
258 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
259 if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
260 && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
262 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
263 if *declared_ret_ty.kind() != ty::Never {
264 sess.span_err(decl.output.span(), "return type should be `!`");
267 let inputs = fn_sig.inputs();
268 let span = hir.span(fn_id);
269 if inputs.len() == 1 {
270 let arg_is_panic_info = match *inputs[0].kind() {
271 ty::Ref(region, ty, mutbl) => match *ty.kind() {
272 ty::Adt(ref adt, _) => {
273 adt.did() == panic_info_did
274 && mutbl == hir::Mutability::Not
275 && !region.is_static()
282 if !arg_is_panic_info {
283 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
286 if let Node::Item(item) = hir.get(fn_id)
287 && let ItemKind::Fn(_, ref generics, _) = item.kind
288 && !generics.params.is_empty()
290 sess.span_err(span, "should have no type parameters");
293 let span = sess.source_map().guess_head_span(span);
294 sess.span_err(span, "function should have one argument");
297 sess.err("language item required, but not found: `panic_info`");
301 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
302 if let Some(alloc_error_handler_did) = tcx.lang_items().oom()
303 && alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id()
305 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
306 if *declared_ret_ty.kind() != ty::Never {
307 sess.span_err(decl.output.span(), "return type should be `!`");
310 let inputs = fn_sig.inputs();
311 let span = hir.span(fn_id);
312 if inputs.len() == 1 {
313 let arg_is_alloc_layout = match inputs[0].kind() {
314 ty::Adt(ref adt, _) => adt.did() == alloc_layout_did,
318 if !arg_is_alloc_layout {
319 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
322 if let Node::Item(item) = hir.get(fn_id)
323 && let ItemKind::Fn(_, ref generics, _) = item.kind
324 && !generics.params.is_empty()
328 "`#[alloc_error_handler]` function should have no type parameters",
332 let span = sess.source_map().guess_head_span(span);
333 sess.span_err(span, "function should have one argument");
336 sess.err("language item required, but not found: `alloc_layout`");
343 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
344 let def = tcx.adt_def(def_id);
345 def.destructor(tcx); // force the destructor to be evaluated
346 check_representable(tcx, span, def_id);
348 if def.repr().simd() {
349 check_simd(tcx, span, def_id);
352 check_transparent(tcx, span, def);
353 check_packed(tcx, span, def);
356 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
357 let def = tcx.adt_def(def_id);
358 def.destructor(tcx); // force the destructor to be evaluated
359 check_representable(tcx, span, def_id);
360 check_transparent(tcx, span, def);
361 check_union_fields(tcx, span, def_id);
362 check_packed(tcx, span, def);
365 /// Check that the fields of the `union` do not need dropping.
366 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
367 let item_type = tcx.type_of(item_def_id);
368 if let ty::Adt(def, substs) = item_type.kind() {
369 assert!(def.is_union());
370 let fields = &def.non_enum_variant().fields;
371 let param_env = tcx.param_env(item_def_id);
372 for field in fields {
373 let field_ty = field.ty(tcx, substs);
374 if field_ty.needs_drop(tcx, param_env) {
375 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
376 // We are currently checking the type this field came from, so it must be local.
377 Some(Node::Field(field)) => (field.span, field.ty.span),
378 _ => unreachable!("mir field has to correspond to hir field"),
384 "unions cannot contain fields that may need dropping"
387 "a type is guaranteed not to need dropping \
388 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
390 .multipart_suggestion_verbose(
391 "when the type does not implement `Copy`, \
392 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
394 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
395 (ty_span.shrink_to_hi(), ">".into()),
397 Applicability::MaybeIncorrect,
404 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
409 /// Check that a `static` is inhabited.
410 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
411 // Make sure statics are inhabited.
412 // Other parts of the compiler assume that there are no uninhabited places. In principle it
413 // would be enough to check this for `extern` statics, as statics with an initializer will
414 // have UB during initialization if they are uninhabited, but there also seems to be no good
415 // reason to allow any statics to be uninhabited.
416 let ty = tcx.type_of(def_id);
417 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
419 // Foreign statics that overflow their allowed size should emit an error
420 Err(LayoutError::SizeOverflow(_))
422 let node = tcx.hir().get_by_def_id(def_id);
425 hir::Node::ForeignItem(hir::ForeignItem {
426 kind: hir::ForeignItemKind::Static(..),
433 .struct_span_err(span, "extern static is too large for the current architecture")
437 // Generic statics are rejected, but we still reach this case.
439 tcx.sess.delay_span_bug(span, &e.to_string());
443 if layout.abi.is_uninhabited() {
444 tcx.struct_span_lint_hir(
446 tcx.hir().local_def_id_to_hir_id(def_id),
449 lint.build("static of uninhabited type")
450 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
457 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
458 /// projections that would result in "inheriting lifetimes".
459 pub(super) fn check_opaque<'tcx>(
462 substs: SubstsRef<'tcx>,
464 origin: &hir::OpaqueTyOrigin,
466 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
467 if tcx.type_of(def_id).references_error() {
470 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
473 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
476 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
477 /// in "inheriting lifetimes".
478 #[instrument(level = "debug", skip(tcx, span))]
479 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
484 let item = tcx.hir().expect_item(def_id);
485 debug!(?item, ?span);
487 struct FoundParentLifetime;
488 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
489 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
490 type BreakTy = FoundParentLifetime;
492 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
493 debug!("FindParentLifetimeVisitor: r={:?}", r);
494 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
495 if index < self.0.parent_count as u32 {
496 return ControlFlow::Break(FoundParentLifetime);
498 return ControlFlow::CONTINUE;
502 r.super_visit_with(self)
505 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
506 if let ty::ConstKind::Unevaluated(..) = c.val() {
507 // FIXME(#72219) We currently don't detect lifetimes within substs
508 // which would violate this check. Even though the particular substitution is not used
509 // within the const, this should still be fixed.
510 return ControlFlow::CONTINUE;
512 c.super_visit_with(self)
516 struct ProhibitOpaqueVisitor<'tcx> {
518 opaque_identity_ty: Ty<'tcx>,
519 generics: &'tcx ty::Generics,
520 selftys: Vec<(Span, Option<String>)>,
523 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
524 type BreakTy = Ty<'tcx>;
526 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
527 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
528 if t == self.opaque_identity_ty {
529 ControlFlow::CONTINUE
531 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
532 .map_break(|FoundParentLifetime| t)
537 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
538 type NestedFilter = nested_filter::OnlyBodies;
540 fn nested_visit_map(&mut self) -> Self::Map {
544 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
546 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
549 res: Some(Res::SelfTy { trait_: _, alias_to: impl_ref }),
554 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
555 self.selftys.push((path.span, impl_ty_name));
561 hir::intravisit::walk_ty(self, arg);
565 if let ItemKind::OpaqueTy(hir::OpaqueTy {
566 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
570 let mut visitor = ProhibitOpaqueVisitor {
571 opaque_identity_ty: tcx.mk_opaque(
573 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
575 generics: tcx.generics_of(def_id),
579 let prohibit_opaque = tcx
580 .explicit_item_bounds(def_id)
582 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
584 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
585 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
588 if let Some(ty) = prohibit_opaque.break_value() {
589 visitor.visit_item(&item);
590 let is_async = match item.kind {
591 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
592 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
597 let mut err = struct_span_err!(
601 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
603 if is_async { "async fn" } else { "impl Trait" },
606 for (span, name) in visitor.selftys {
609 "consider spelling out the type instead",
610 name.unwrap_or_else(|| format!("{:?}", ty)),
611 Applicability::MaybeIncorrect,
619 /// Checks that an opaque type does not contain cycles.
620 pub(super) fn check_opaque_for_cycles<'tcx>(
623 substs: SubstsRef<'tcx>,
625 origin: &hir::OpaqueTyOrigin,
626 ) -> Result<(), ErrorGuaranteed> {
627 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
628 let reported = match origin {
629 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
630 _ => opaque_type_cycle_error(tcx, def_id, span),
638 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
640 /// This is mostly checked at the places that specify the opaque type, but we
641 /// check those cases in the `param_env` of that function, which may have
642 /// bounds not on this opaque type:
644 /// type X<T> = impl Clone
645 /// fn f<T: Clone>(t: T) -> X<T> {
649 /// Without this check the above code is incorrectly accepted: we would ICE if
650 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
651 #[instrument(level = "debug", skip(tcx))]
652 fn check_opaque_meets_bounds<'tcx>(
655 substs: SubstsRef<'tcx>,
657 origin: &hir::OpaqueTyOrigin,
659 let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
661 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
662 let defining_use_anchor = match *origin {
663 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
664 hir::OpaqueTyOrigin::TyAlias => def_id,
666 let param_env = tcx.param_env(defining_use_anchor);
668 tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
669 let inh = Inherited::new(infcx, def_id);
670 let infcx = &inh.infcx;
671 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
673 let misc_cause = traits::ObligationCause::misc(span, hir_id);
675 match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) {
676 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
678 tcx.sess.delay_span_bug(
680 &format!("could not unify `{hidden_type}` with revealed type:\n{ty_err}"),
685 // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
686 // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
687 // hidden type is well formed even without those bounds.
689 ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx);
690 inh.register_predicate(Obligation::new(misc_cause, param_env, predicate));
692 // Check that all obligations are satisfied by the implementation's
694 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
695 if !errors.is_empty() {
696 infcx.report_fulfillment_errors(&errors, None, false);
700 // Checked when type checking the function containing them.
701 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
702 // Can have different predicates to their defining use
703 hir::OpaqueTyOrigin::TyAlias => {
704 // Finally, resolve all regions. This catches wily misuses of
705 // lifetime parameters.
706 let fcx = FnCtxt::new(&inh, param_env, hir_id);
707 fcx.regionck_item(hir_id, span, FxHashSet::default());
711 // Clean up after ourselves
712 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
716 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
718 "check_item_type(it.def_id={:?}, it.name={})",
720 tcx.def_path_str(id.def_id.to_def_id())
722 let _indenter = indenter();
723 match tcx.def_kind(id.def_id) {
724 DefKind::Static(..) => {
725 tcx.ensure().typeck(id.def_id);
726 maybe_check_static_with_link_section(tcx, id.def_id, tcx.def_span(id.def_id));
727 check_static_inhabited(tcx, id.def_id, tcx.def_span(id.def_id));
730 tcx.ensure().typeck(id.def_id);
733 let item = tcx.hir().item(id);
734 let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else {
737 check_enum(tcx, item.span, &enum_definition.variants, item.def_id);
739 DefKind::Fn => {} // entirely within check_item_body
741 let it = tcx.hir().item(id);
742 let hir::ItemKind::Impl(ref impl_) = it.kind else {
745 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
746 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
747 check_impl_items_against_trait(
754 check_on_unimplemented(tcx, it);
758 let it = tcx.hir().item(id);
759 let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
762 check_on_unimplemented(tcx, it);
764 for item in items.iter() {
765 let item = tcx.hir().trait_item(item.id);
767 hir::TraitItemKind::Fn(ref sig, _) => {
768 let abi = sig.header.abi;
769 fn_maybe_err(tcx, item.ident.span, abi);
771 hir::TraitItemKind::Type(.., Some(default)) => {
772 let assoc_item = tcx.associated_item(item.def_id);
774 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
775 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
780 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
788 check_struct(tcx, id.def_id, tcx.def_span(id.def_id));
791 check_union(tcx, id.def_id, tcx.def_span(id.def_id));
793 DefKind::OpaqueTy => {
794 let item = tcx.hir().item(id);
795 let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
798 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
799 // `async-std` (and `pub async fn` in general).
800 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
801 // See https://github.com/rust-lang/rust/issues/75100
802 if !tcx.sess.opts.actually_rustdoc {
803 let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id());
804 check_opaque(tcx, item.def_id, substs, item.span, &origin);
807 DefKind::TyAlias => {
808 let pty_ty = tcx.type_of(id.def_id);
809 let generics = tcx.generics_of(id.def_id);
810 check_type_params_are_used(tcx, &generics, pty_ty);
812 DefKind::ForeignMod => {
813 let it = tcx.hir().item(id);
814 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
817 check_abi(tcx, it.hir_id(), it.span, abi);
819 if abi == Abi::RustIntrinsic {
821 let item = tcx.hir().foreign_item(item.id);
822 intrinsic::check_intrinsic_type(tcx, item);
824 } else if abi == Abi::PlatformIntrinsic {
826 let item = tcx.hir().foreign_item(item.id);
827 intrinsic::check_platform_intrinsic_type(tcx, item);
831 let def_id = item.id.def_id;
832 let generics = tcx.generics_of(def_id);
833 let own_counts = generics.own_counts();
834 if generics.params.len() - own_counts.lifetimes != 0 {
835 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
836 (_, 0) => ("type", "types", Some("u32")),
837 // We don't specify an example value, because we can't generate
838 // a valid value for any type.
839 (0, _) => ("const", "consts", None),
840 _ => ("type or const", "types or consts", None),
846 "foreign items may not have {kinds} parameters",
848 .span_label(item.span, &format!("can't have {kinds} parameters"))
850 // FIXME: once we start storing spans for type arguments, turn this
851 // into a suggestion.
853 "replace the {} parameters with concrete {}{}",
856 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
862 let item = tcx.hir().foreign_item(item.id);
864 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
865 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
867 hir::ForeignItemKind::Static(..) => {
868 check_static_inhabited(tcx, def_id, item.span);
875 DefKind::GlobalAsm => {
876 let it = tcx.hir().item(id);
877 let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
878 for_item(tcx, it).with_fcx(|fcx| {
879 fcx.check_asm(asm, it.hir_id());
887 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
888 // an error would be reported if this fails.
889 let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
892 pub(super) fn check_specialization_validity<'tcx>(
894 trait_def: &ty::TraitDef,
895 trait_item: &ty::AssocItem,
897 impl_item: &hir::ImplItemRef,
899 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
900 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
901 if parent.is_from_trait() {
904 Some((parent, parent.item(tcx, trait_item.def_id)))
908 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
910 // Parent impl exists, and contains the parent item we're trying to specialize, but
911 // doesn't mark it `default`.
912 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
913 Some(Err(parent_impl.def_id()))
916 // Parent impl contains item and makes it specializable.
917 Some(_) => Some(Ok(())),
919 // Parent impl doesn't mention the item. This means it's inherited from the
920 // grandparent. In that case, if parent is a `default impl`, inherited items use the
921 // "defaultness" from the grandparent, else they are final.
923 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
926 Some(Err(parent_impl.def_id()))
932 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
933 // item. This is allowed, the item isn't actually getting specialized here.
934 let result = opt_result.unwrap_or(Ok(()));
936 if let Err(parent_impl) = result {
937 report_forbidden_specialization(tcx, impl_item, parent_impl);
941 fn check_impl_items_against_trait<'tcx>(
943 full_impl_span: Span,
945 impl_trait_ref: ty::TraitRef<'tcx>,
946 impl_item_refs: &[hir::ImplItemRef],
948 // If the trait reference itself is erroneous (so the compilation is going
949 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
950 // isn't populated for such impls.
951 if impl_trait_ref.references_error() {
955 // Negative impls are not expected to have any items
956 match tcx.impl_polarity(impl_id) {
957 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
958 ty::ImplPolarity::Negative => {
959 if let [first_item_ref, ..] = impl_item_refs {
960 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
965 "negative impls cannot have any items"
973 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
975 for impl_item in impl_item_refs {
976 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
977 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
978 tcx.associated_item(trait_item_id)
980 // Checked in `associated_item`.
981 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
984 let impl_item_full = tcx.hir().impl_item(impl_item.id);
985 match impl_item_full.kind {
986 hir::ImplItemKind::Const(..) => {
987 // Find associated const definition.
996 hir::ImplItemKind::Fn(..) => {
997 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1007 hir::ImplItemKind::TyAlias(impl_ty) => {
1008 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1020 check_specialization_validity(
1024 impl_id.to_def_id(),
1029 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1030 // Check for missing items from trait
1031 let mut missing_items = Vec::new();
1033 let mut must_implement_one_of: Option<&[Ident]> =
1034 trait_def.must_implement_one_of.as_deref();
1036 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1037 let is_implemented = ancestors
1038 .leaf_def(tcx, trait_item_id)
1039 .map_or(false, |node_item| node_item.item.defaultness.has_value());
1041 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1042 missing_items.push(tcx.associated_item(trait_item_id));
1045 if let Some(required_items) = &must_implement_one_of {
1046 // true if this item is specifically implemented in this impl
1047 let is_implemented_here = ancestors
1048 .leaf_def(tcx, trait_item_id)
1049 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1051 if is_implemented_here {
1052 let trait_item = tcx.associated_item(trait_item_id);
1053 if required_items.contains(&trait_item.ident(tcx)) {
1054 must_implement_one_of = None;
1060 if !missing_items.is_empty() {
1061 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1062 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1065 if let Some(missing_items) = must_implement_one_of {
1066 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1068 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
1069 .map(|attr| attr.span);
1071 missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1076 /// Checks whether a type can be represented in memory. In particular, it
1077 /// identifies types that contain themselves without indirection through a
1078 /// pointer, which would mean their size is unbounded.
1079 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1080 let rty = tcx.type_of(item_def_id);
1082 // Check that it is possible to represent this type. This call identifies
1083 // (1) types that contain themselves and (2) types that contain a different
1084 // recursive type. It is only necessary to throw an error on those that
1085 // contain themselves. For case 2, there must be an inner type that will be
1086 // caught by case 1.
1087 match representability::ty_is_representable(tcx, rty, sp, None) {
1088 Representability::SelfRecursive(spans) => {
1089 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1092 Representability::Representable | Representability::ContainsRecursive => (),
1097 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1098 let t = tcx.type_of(def_id);
1099 if let ty::Adt(def, substs) = t.kind()
1102 let fields = &def.non_enum_variant().fields;
1103 if fields.is_empty() {
1104 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1107 let e = fields[0].ty(tcx, substs);
1108 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1109 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1110 .span_label(sp, "SIMD elements must have the same type")
1115 let len = if let ty::Array(_ty, c) = e.kind() {
1116 c.try_eval_usize(tcx, tcx.param_env(def.did()))
1118 Some(fields.len() as u64)
1120 if let Some(len) = len {
1122 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1124 } else if len > MAX_SIMD_LANES {
1129 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1136 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1137 // These are scalar types which directly match a "machine" type
1138 // Yes: Integers, floats, "thin" pointers
1139 // No: char, "fat" pointers, compound types
1141 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1142 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1143 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1147 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1149 { /* struct([f32; 4]) is ok */ }
1155 "SIMD vector element type should be a \
1156 primitive scalar (integer/float/pointer) type"
1165 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1166 let repr = def.repr();
1168 for attr in tcx.get_attrs(def.did(), sym::repr) {
1169 for r in attr::parse_repr_attr(&tcx.sess, attr) {
1170 if let attr::ReprPacked(pack) = r
1171 && let Some(repr_pack) = repr.pack
1172 && pack as u64 != repr_pack.bytes()
1178 "type has conflicting packed representation hints"
1184 if repr.align.is_some() {
1189 "type has conflicting packed and align representation hints"
1193 if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1194 let mut err = struct_span_err!(
1198 "packed type cannot transitively contain a `#[repr(align)]` type"
1202 tcx.def_span(def_spans[0].0),
1204 "`{}` has a `#[repr(align)]` attribute",
1205 tcx.item_name(def_spans[0].0)
1209 if def_spans.len() > 2 {
1210 let mut first = true;
1211 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1212 let ident = tcx.item_name(*adt_def);
1217 "`{}` contains a field of type `{}`",
1218 tcx.type_of(def.did()),
1222 format!("...which contains a field of type `{ident}`")
1235 pub(super) fn check_packed_inner(
1238 stack: &mut Vec<DefId>,
1239 ) -> Option<Vec<(DefId, Span)>> {
1240 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1241 if def.is_struct() || def.is_union() {
1242 if def.repr().align.is_some() {
1243 return Some(vec![(def.did(), DUMMY_SP)]);
1247 for field in &def.non_enum_variant().fields {
1248 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1249 && !stack.contains(&def.did())
1250 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1252 defs.push((def.did(), field.ident(tcx).span));
1263 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1264 if !adt.repr().transparent() {
1267 let sp = tcx.sess.source_map().guess_head_span(sp);
1269 if adt.is_union() && !tcx.features().transparent_unions {
1271 &tcx.sess.parse_sess,
1272 sym::transparent_unions,
1274 "transparent unions are unstable",
1279 if adt.variants().len() != 1 {
1280 bad_variant_count(tcx, adt, sp, adt.did());
1281 if adt.variants().is_empty() {
1282 // Don't bother checking the fields. No variants (and thus no fields) exist.
1287 // For each field, figure out if it's known to be a ZST and align(1)
1288 let field_infos = adt.all_fields().map(|field| {
1289 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1290 let param_env = tcx.param_env(field.did);
1291 let layout = tcx.layout_of(param_env.and(ty));
1292 // We are currently checking the type this field came from, so it must be local
1293 let span = tcx.hir().span_if_local(field.did).unwrap();
1294 let zst = layout.map_or(false, |layout| layout.is_zst());
1295 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1299 let non_zst_fields =
1300 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1301 let non_zst_count = non_zst_fields.clone().count();
1302 if non_zst_count >= 2 {
1303 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1305 for (span, zst, align1) in field_infos {
1311 "zero-sized field in transparent {} has alignment larger than 1",
1314 .span_label(span, "has alignment larger than 1")
1320 #[allow(trivial_numeric_casts)]
1321 fn check_enum<'tcx>(
1324 vs: &'tcx [hir::Variant<'tcx>],
1327 let def = tcx.adt_def(def_id);
1328 def.destructor(tcx); // force the destructor to be evaluated
1331 if let Some(attr) = tcx.get_attr(def_id.to_def_id(), sym::repr) {
1336 "unsupported representation for zero-variant enum"
1338 .span_label(sp, "zero-variant enum")
1343 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1344 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1345 if !tcx.features().repr128 {
1347 &tcx.sess.parse_sess,
1350 "repr with 128-bit type is unstable",
1357 if let Some(ref e) = v.disr_expr {
1358 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1362 if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1363 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1365 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1366 let has_non_units = vs.iter().any(|var| !is_unit(var));
1367 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1368 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1370 if disr_non_unit || (disr_units && has_non_units) {
1372 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1377 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1378 // This tracks the previous variant span (in the loop) incase we need it for diagnostics
1379 let mut prev_variant_span: Span = DUMMY_SP;
1380 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1381 // Check for duplicate discriminant values
1382 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1383 let variant_did = def.variant(VariantIdx::new(i)).def_id;
1384 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1385 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1386 let i_span = match variant_i.disr_expr {
1387 Some(ref expr) => tcx.hir().span(expr.hir_id),
1388 None => tcx.def_span(variant_did),
1390 let span = match v.disr_expr {
1391 Some(ref expr) => tcx.hir().span(expr.hir_id),
1394 let display_discr = format_discriminant_overflow(tcx, v, discr);
1395 let display_discr_i = format_discriminant_overflow(tcx, variant_i, disr_vals[i]);
1396 let no_disr = v.disr_expr.is_none();
1397 let mut err = struct_span_err!(
1401 "discriminant value `{}` assigned more than once",
1405 err.span_label(i_span, format!("first assignment of {display_discr_i}"));
1406 err.span_label(span, format!("second assignment of {display_discr}"));
1412 "assigned discriminant for `{}` was incremented from this discriminant",
1420 disr_vals.push(discr);
1421 prev_variant_span = v.span;
1424 check_representable(tcx, sp, def_id);
1425 check_transparent(tcx, sp, def);
1428 /// In the case that a discriminant is both a duplicate and an overflowing literal,
1429 /// we insert both the assigned discriminant and the literal it overflowed from into the formatted
1430 /// output. Otherwise we format the discriminant normally.
1431 fn format_discriminant_overflow<'tcx>(
1433 variant: &hir::Variant<'_>,
1436 if let Some(expr) = &variant.disr_expr {
1437 let body = &tcx.hir().body(expr.body).value;
1438 if let hir::ExprKind::Lit(lit) = &body.kind
1439 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1440 && dis.val != *lit_value
1442 return format!("`{dis}` (overflowed from `{lit_value}`)");
1449 pub(super) fn check_type_params_are_used<'tcx>(
1451 generics: &ty::Generics,
1454 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1456 assert_eq!(generics.parent, None);
1458 if generics.own_counts().types == 0 {
1462 let mut params_used = BitSet::new_empty(generics.params.len());
1464 if ty.references_error() {
1465 // If there is already another error, do not emit
1466 // an error for not using a type parameter.
1467 assert!(tcx.sess.has_errors().is_some());
1471 for leaf in ty.walk() {
1472 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1473 && let ty::Param(param) = leaf_ty.kind()
1475 debug!("found use of ty param {:?}", param);
1476 params_used.insert(param.index);
1480 for param in &generics.params {
1481 if !params_used.contains(param.index)
1482 && let ty::GenericParamDefKind::Type { .. } = param.kind
1484 let span = tcx.def_span(param.def_id);
1489 "type parameter `{}` is unused",
1492 .span_label(span, "unused type parameter")
1498 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1499 let module = tcx.hir_module_items(module_def_id);
1500 for id in module.items() {
1501 check_item_type(tcx, id);
1505 pub(super) use wfcheck::check_item_well_formed;
1507 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1509 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1511 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1512 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1513 .span_label(span, "recursive `async fn`")
1514 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1516 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1521 /// Emit an error for recursive opaque types.
1523 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1524 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1527 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1528 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1529 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1530 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1532 let mut label = false;
1533 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1534 let typeck_results = tcx.typeck(def_id);
1538 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1539 .all(|ty| matches!(ty.kind(), ty::Never))
1544 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1545 .map(|expr| expr.span)
1546 .collect::<Vec<Span>>();
1547 let span_len = spans.len();
1549 err.span_label(spans[0], "this returned value is of `!` type");
1551 let mut multispan: MultiSpan = spans.clone().into();
1554 .push_span_label(span, "this returned value is of `!` type".to_string());
1556 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1558 err.help("this error will resolve once the item's body returns a concrete type");
1560 let mut seen = FxHashSet::default();
1562 err.span_label(span, "recursive opaque type");
1564 for (sp, ty) in visitor
1567 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1568 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1570 struct OpaqueTypeCollector(Vec<DefId>);
1571 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1572 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1574 ty::Opaque(def, _) => {
1576 ControlFlow::CONTINUE
1578 _ => t.super_visit_with(self),
1582 let mut visitor = OpaqueTypeCollector(vec![]);
1583 ty.visit_with(&mut visitor);
1584 for def_id in visitor.0 {
1585 let ty_span = tcx.def_span(def_id);
1586 if !seen.contains(&ty_span) {
1587 err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1588 seen.insert(ty_span);
1590 err.span_label(sp, &format!("returning here with type `{ty}`"));
1596 err.span_label(span, "cannot resolve opaque type");