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, ErrorReported};
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_middle::hir::nested_filter;
16 use rustc_middle::ty::fold::TypeFoldable;
17 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
18 use rustc_middle::ty::subst::GenericArgKind;
19 use rustc_middle::ty::util::{Discr, IntTypeExt};
20 use rustc_middle::ty::{self, OpaqueTypeKey, ParamEnv, Ty, TyCtxt};
21 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
22 use rustc_span::symbol::sym;
23 use rustc_span::{self, MultiSpan, Span};
24 use rustc_target::spec::abi::Abi;
25 use rustc_trait_selection::traits;
26 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
27 use rustc_ty_utils::representability::{self, Representability};
30 use std::ops::ControlFlow;
32 pub fn check_wf_new(tcx: TyCtxt<'_>) {
33 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
34 tcx.hir().par_visit_all_item_likes(&visit);
37 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
38 match tcx.sess.target.is_abi_supported(abi) {
45 "`{}` 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 let mut fn_sig = fn_sig;
88 // Create the function context. This is either derived from scratch or,
89 // in the case of closures, based on the outer context.
90 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
91 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
92 fcx.return_type_pre_known = return_type_pre_known;
98 let declared_ret_ty = fn_sig.output();
100 let revealed_ret_ty =
101 fcx.instantiate_opaque_types_from_value(declared_ret_ty, decl.output.span());
102 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
103 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
104 fcx.ret_type_span = Some(decl.output.span());
105 if let ty::Opaque(..) = declared_ret_ty.kind() {
106 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
108 fn_sig = tcx.mk_fn_sig(
109 fn_sig.inputs().iter().cloned(),
116 let span = body.value.span;
118 fn_maybe_err(tcx, span, fn_sig.abi);
120 if fn_sig.abi == Abi::RustCall {
121 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
124 let item = match tcx.hir().get(fn_id) {
125 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
126 Node::ImplItem(hir::ImplItem {
127 kind: hir::ImplItemKind::Fn(header, ..), ..
129 Node::TraitItem(hir::TraitItem {
130 kind: hir::TraitItemKind::Fn(header, ..),
133 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
134 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
135 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
138 if let Some(header) = item {
139 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple")
143 if fn_sig.inputs().len() != expected_args {
146 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
147 // This will probably require wide-scale changes to support a TupleKind obligation
148 // We can't resolve this without knowing the type of the param
149 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
155 if body.generator_kind.is_some() && can_be_generator.is_some() {
157 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
158 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
160 // Resume type defaults to `()` if the generator has no argument.
161 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
163 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
166 GatherLocalsVisitor::new(&fcx).visit_body(body);
168 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
169 // (as it's created inside the body itself, not passed in from outside).
170 let maybe_va_list = if fn_sig.c_variadic {
171 let span = body.params.last().unwrap().span;
172 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
173 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
175 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
180 // Add formal parameters.
181 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
182 let inputs_fn = fn_sig.inputs().iter().copied();
183 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
184 // Check the pattern.
185 let ty_span = try { inputs_hir?.get(idx)?.span };
186 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
188 // Check that argument is Sized.
189 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
190 // for simple cases like `fn foo(x: Trait)`,
191 // where we would error once on the parameter as a whole, and once on the binding `x`.
192 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
193 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
196 fcx.write_ty(param.hir_id, param_ty);
199 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
201 fcx.in_tail_expr = true;
202 if let ty::Dynamic(..) = declared_ret_ty.kind() {
203 // FIXME: We need to verify that the return type is `Sized` after the return expression has
204 // been evaluated so that we have types available for all the nodes being returned, but that
205 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
206 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
207 // while keeping the current ordering we will ignore the tail expression's type because we
208 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
209 // because we will trigger "unreachable expression" lints unconditionally.
210 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
211 // case that a newcomer might make, returning a bare trait, and in that case we populate
212 // the tail expression's type so that the suggestion will be correct, but ignore all other
214 fcx.check_expr(&body.value);
215 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
217 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
218 fcx.check_return_expr(&body.value, false);
220 fcx.in_tail_expr = false;
222 // We insert the deferred_generator_interiors entry after visiting the body.
223 // This ensures that all nested generators appear before the entry of this generator.
224 // resolve_generator_interiors relies on this property.
225 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
227 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
228 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
230 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
231 Some(GeneratorTypes {
235 movability: can_be_generator.unwrap(),
241 // Finalize the return check by taking the LUB of the return types
242 // we saw and assigning it to the expected return type. This isn't
243 // really expected to fail, since the coercions would have failed
244 // earlier when trying to find a LUB.
245 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
246 let mut actual_return_ty = coercion.complete(&fcx);
247 debug!("actual_return_ty = {:?}", actual_return_ty);
248 if let ty::Dynamic(..) = declared_ret_ty.kind() {
249 // We have special-cased the case where the function is declared
250 // `-> dyn Foo` and we don't actually relate it to the
251 // `fcx.ret_coercion`, so just substitute a type variable.
253 fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
254 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
256 fcx.demand_suptype(span, revealed_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 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
261 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
262 if *declared_ret_ty.kind() != ty::Never {
263 sess.span_err(decl.output.span(), "return type should be `!`");
266 let inputs = fn_sig.inputs();
267 let span = hir.span(fn_id);
268 if inputs.len() == 1 {
269 let arg_is_panic_info = match *inputs[0].kind() {
270 ty::Ref(region, ty, mutbl) => match *ty.kind() {
271 ty::Adt(ref adt, _) => {
272 adt.did == panic_info_did
273 && mutbl == hir::Mutability::Not
274 && !region.is_static()
281 if !arg_is_panic_info {
282 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
285 if let Node::Item(item) = hir.get(fn_id) {
286 if let ItemKind::Fn(_, ref generics, _) = item.kind {
287 if !generics.params.is_empty() {
288 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`");
302 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
303 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
304 if 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 if let ItemKind::Fn(_, ref generics, _) = item.kind {
324 if !generics.params.is_empty() {
327 "`#[alloc_error_handler]` function should have no type \
334 let span = sess.source_map().guess_head_span(span);
335 sess.span_err(span, "function should have one argument");
338 sess.err("language item required, but not found: `alloc_layout`");
346 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
347 let def = tcx.adt_def(def_id);
348 def.destructor(tcx); // force the destructor to be evaluated
349 check_representable(tcx, span, def_id);
352 check_simd(tcx, span, def_id);
355 check_transparent(tcx, span, def);
356 check_packed(tcx, span, def);
359 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
360 let def = tcx.adt_def(def_id);
361 def.destructor(tcx); // force the destructor to be evaluated
362 check_representable(tcx, span, def_id);
363 check_transparent(tcx, span, def);
364 check_union_fields(tcx, span, def_id);
365 check_packed(tcx, span, def);
368 /// Check that the fields of the `union` do not need dropping.
369 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
370 let item_type = tcx.type_of(item_def_id);
371 if let ty::Adt(def, substs) = item_type.kind() {
372 assert!(def.is_union());
373 let fields = &def.non_enum_variant().fields;
374 let param_env = tcx.param_env(item_def_id);
375 for field in fields {
376 let field_ty = field.ty(tcx, substs);
377 if field_ty.needs_drop(tcx, param_env) {
378 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
379 // We are currently checking the type this field came from, so it must be local.
380 Some(Node::Field(field)) => (field.span, field.ty.span),
381 _ => unreachable!("mir field has to correspond to hir field"),
387 "unions cannot contain fields that may need dropping"
390 "a type is guaranteed not to need dropping \
391 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
393 .multipart_suggestion_verbose(
394 "when the type does not implement `Copy`, \
395 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
397 (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
398 (ty_span.shrink_to_hi(), ">".into()),
400 Applicability::MaybeIncorrect,
407 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
412 /// Check that a `static` is inhabited.
413 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
414 // Make sure statics are inhabited.
415 // Other parts of the compiler assume that there are no uninhabited places. In principle it
416 // would be enough to check this for `extern` statics, as statics with an initializer will
417 // have UB during initialization if they are uninhabited, but there also seems to be no good
418 // reason to allow any statics to be uninhabited.
419 let ty = tcx.type_of(def_id);
420 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
422 // Foreign statics that overflow their allowed size should emit an error
423 Err(LayoutError::SizeOverflow(_))
425 let node = tcx.hir().get_by_def_id(def_id);
428 hir::Node::ForeignItem(hir::ForeignItem {
429 kind: hir::ForeignItemKind::Static(..),
436 .struct_span_err(span, "extern static is too large for the current architecture")
440 // Generic statics are rejected, but we still reach this case.
442 tcx.sess.delay_span_bug(span, &e.to_string());
446 if layout.abi.is_uninhabited() {
447 tcx.struct_span_lint_hir(
449 tcx.hir().local_def_id_to_hir_id(def_id),
452 lint.build("static of uninhabited type")
453 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
460 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
461 /// projections that would result in "inheriting lifetimes".
462 pub(super) fn check_opaque<'tcx>(
465 substs: SubstsRef<'tcx>,
467 origin: &hir::OpaqueTyOrigin,
469 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
470 if tcx.type_of(def_id).references_error() {
473 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
476 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
479 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
480 /// in "inheriting lifetimes".
481 #[instrument(level = "debug", skip(tcx, span))]
482 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
487 let item = tcx.hir().expect_item(def_id);
488 debug!(?item, ?span);
490 struct FoundParentLifetime;
491 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
492 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
493 type BreakTy = FoundParentLifetime;
495 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
496 debug!("FindParentLifetimeVisitor: r={:?}", r);
497 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
498 if index < self.0.parent_count as u32 {
499 return ControlFlow::Break(FoundParentLifetime);
501 return ControlFlow::CONTINUE;
505 r.super_visit_with(self)
508 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
509 if let ty::ConstKind::Unevaluated(..) = c.val() {
510 // FIXME(#72219) We currently don't detect lifetimes within substs
511 // which would violate this check. Even though the particular substitution is not used
512 // within the const, this should still be fixed.
513 return ControlFlow::CONTINUE;
515 c.super_visit_with(self)
519 struct ProhibitOpaqueVisitor<'tcx> {
521 opaque_identity_ty: Ty<'tcx>,
522 generics: &'tcx ty::Generics,
523 selftys: Vec<(Span, Option<String>)>,
526 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
527 type BreakTy = Ty<'tcx>;
529 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
530 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
531 if t == self.opaque_identity_ty {
532 ControlFlow::CONTINUE
534 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
535 .map_break(|FoundParentLifetime| t)
540 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
541 type NestedFilter = nested_filter::OnlyBodies;
543 fn nested_visit_map(&mut self) -> Self::Map {
547 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
549 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
552 res: Some(Res::SelfTy { trait_: _, alias_to: impl_ref }),
557 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
558 self.selftys.push((path.span, impl_ty_name));
564 hir::intravisit::walk_ty(self, arg);
568 if let ItemKind::OpaqueTy(hir::OpaqueTy {
569 origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
573 let mut visitor = ProhibitOpaqueVisitor {
574 opaque_identity_ty: tcx.mk_opaque(
576 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
578 generics: tcx.generics_of(def_id),
582 let prohibit_opaque = tcx
583 .explicit_item_bounds(def_id)
585 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
587 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
588 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
591 if let Some(ty) = prohibit_opaque.break_value() {
592 visitor.visit_item(&item);
593 let is_async = match item.kind {
594 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
595 matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
600 let mut err = struct_span_err!(
604 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
606 if is_async { "async fn" } else { "impl Trait" },
609 for (span, name) in visitor.selftys {
612 "consider spelling out the type instead",
613 name.unwrap_or_else(|| format!("{:?}", ty)),
614 Applicability::MaybeIncorrect,
622 /// Checks that an opaque type does not contain cycles.
623 pub(super) fn check_opaque_for_cycles<'tcx>(
626 substs: SubstsRef<'tcx>,
628 origin: &hir::OpaqueTyOrigin,
629 ) -> Result<(), ErrorReported> {
630 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
632 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
633 _ => opaque_type_cycle_error(tcx, def_id, span),
641 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
643 /// This is mostly checked at the places that specify the opaque type, but we
644 /// check those cases in the `param_env` of that function, which may have
645 /// bounds not on this opaque type:
647 /// type X<T> = impl Clone
648 /// fn f<T: Clone>(t: T) -> X<T> {
652 /// Without this check the above code is incorrectly accepted: we would ICE if
653 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
654 #[instrument(level = "debug", skip(tcx))]
655 fn check_opaque_meets_bounds<'tcx>(
658 substs: SubstsRef<'tcx>,
660 origin: &hir::OpaqueTyOrigin,
662 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
663 let defining_use_anchor = match *origin {
664 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
665 hir::OpaqueTyOrigin::TyAlias => def_id,
667 let param_env = tcx.param_env(defining_use_anchor);
669 tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
670 let inh = Inherited::new(infcx, def_id);
671 let infcx = &inh.infcx;
672 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
674 let misc_cause = traits::ObligationCause::misc(span, hir_id);
676 let _ = inh.register_infer_ok_obligations(
677 infcx.instantiate_opaque_types(hir_id, param_env, opaque_ty, span),
680 let opaque_type_map = infcx.inner.borrow().opaque_types.clone();
681 for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map {
682 let hidden_type = tcx.type_of(def_id).subst(tcx, substs);
683 trace!(?hidden_type);
684 match infcx.at(&misc_cause, param_env).eq(opaque_defn.concrete_ty, hidden_type) {
685 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
686 Err(ty_err) => tcx.sess.delay_span_bug(
689 "could not check bounds on revealed type `{}`:\n{}",
696 // Check that all obligations are satisfied by the implementation's
698 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
699 if !errors.is_empty() {
700 infcx.report_fulfillment_errors(&errors, None, false);
704 // Checked when type checking the function containing them.
705 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return,
706 // Can have different predicates to their defining use
707 hir::OpaqueTyOrigin::TyAlias => {
708 // Finally, resolve all regions. This catches wily misuses of
709 // lifetime parameters.
710 let fcx = FnCtxt::new(&inh, param_env, hir_id);
711 fcx.regionck_item(hir_id, span, FxHashSet::default());
717 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
719 "check_item_type(it.def_id={:?}, it.name={})",
721 tcx.def_path_str(it.def_id.to_def_id())
723 let _indenter = indenter();
725 // Consts can play a role in type-checking, so they are included here.
726 hir::ItemKind::Static(..) => {
727 tcx.ensure().typeck(it.def_id);
728 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
729 check_static_inhabited(tcx, it.def_id, it.span);
731 hir::ItemKind::Const(..) => {
732 tcx.ensure().typeck(it.def_id);
734 hir::ItemKind::Enum(ref enum_definition, _) => {
735 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
737 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
738 hir::ItemKind::Impl(ref impl_) => {
739 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
740 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
741 check_impl_items_against_trait(
748 let trait_def_id = impl_trait_ref.def_id;
749 check_on_unimplemented(tcx, trait_def_id, it);
752 hir::ItemKind::Trait(_, _, _, _, ref items) => {
753 check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
755 for item in items.iter() {
756 let item = tcx.hir().trait_item(item.id);
758 hir::TraitItemKind::Fn(ref sig, _) => {
759 let abi = sig.header.abi;
760 fn_maybe_err(tcx, item.ident.span, abi);
762 hir::TraitItemKind::Type(.., Some(default)) => {
763 let assoc_item = tcx.associated_item(item.def_id);
765 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
766 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
771 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
778 hir::ItemKind::Struct(..) => {
779 check_struct(tcx, it.def_id, it.span);
781 hir::ItemKind::Union(..) => {
782 check_union(tcx, it.def_id, it.span);
784 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
785 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
786 // `async-std` (and `pub async fn` in general).
787 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
788 // See https://github.com/rust-lang/rust/issues/75100
789 if !tcx.sess.opts.actually_rustdoc {
790 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
791 check_opaque(tcx, it.def_id, substs, it.span, &origin);
794 hir::ItemKind::TyAlias(..) => {
795 let pty_ty = tcx.type_of(it.def_id);
796 let generics = tcx.generics_of(it.def_id);
797 check_type_params_are_used(tcx, &generics, pty_ty);
799 hir::ItemKind::ForeignMod { abi, items } => {
800 check_abi(tcx, it.hir_id(), it.span, abi);
802 if abi == Abi::RustIntrinsic {
804 let item = tcx.hir().foreign_item(item.id);
805 intrinsic::check_intrinsic_type(tcx, item);
807 } else if abi == Abi::PlatformIntrinsic {
809 let item = tcx.hir().foreign_item(item.id);
810 intrinsic::check_platform_intrinsic_type(tcx, item);
814 let def_id = item.id.def_id;
815 let generics = tcx.generics_of(def_id);
816 let own_counts = generics.own_counts();
817 if generics.params.len() - own_counts.lifetimes != 0 {
818 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
819 (_, 0) => ("type", "types", Some("u32")),
820 // We don't specify an example value, because we can't generate
821 // a valid value for any type.
822 (0, _) => ("const", "consts", None),
823 _ => ("type or const", "types or consts", None),
829 "foreign items may not have {} parameters",
832 .span_label(item.span, &format!("can't have {} parameters", kinds))
834 // FIXME: once we start storing spans for type arguments, turn this
835 // into a suggestion.
837 "replace the {} parameters with concrete {}{}",
840 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
846 let item = tcx.hir().foreign_item(item.id);
848 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
849 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
851 hir::ForeignItemKind::Static(..) => {
852 check_static_inhabited(tcx, def_id, item.span);
859 _ => { /* nothing to do */ }
863 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
864 // an error would be reported if this fails.
865 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
868 pub(super) fn check_specialization_validity<'tcx>(
870 trait_def: &ty::TraitDef,
871 trait_item: &ty::AssocItem,
873 impl_item: &hir::ImplItemRef,
875 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
876 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
877 if parent.is_from_trait() {
880 Some((parent, parent.item(tcx, trait_item.def_id)))
884 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
886 // Parent impl exists, and contains the parent item we're trying to specialize, but
887 // doesn't mark it `default`.
888 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
889 Some(Err(parent_impl.def_id()))
892 // Parent impl contains item and makes it specializable.
893 Some(_) => Some(Ok(())),
895 // Parent impl doesn't mention the item. This means it's inherited from the
896 // grandparent. In that case, if parent is a `default impl`, inherited items use the
897 // "defaultness" from the grandparent, else they are final.
899 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
902 Some(Err(parent_impl.def_id()))
908 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
909 // item. This is allowed, the item isn't actually getting specialized here.
910 let result = opt_result.unwrap_or(Ok(()));
912 if let Err(parent_impl) = result {
913 report_forbidden_specialization(tcx, impl_item, parent_impl);
917 fn check_impl_items_against_trait<'tcx>(
919 full_impl_span: Span,
921 impl_trait_ref: ty::TraitRef<'tcx>,
922 impl_item_refs: &[hir::ImplItemRef],
924 // If the trait reference itself is erroneous (so the compilation is going
925 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
926 // isn't populated for such impls.
927 if impl_trait_ref.references_error() {
931 // Negative impls are not expected to have any items
932 match tcx.impl_polarity(impl_id) {
933 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
934 ty::ImplPolarity::Negative => {
935 if let [first_item_ref, ..] = impl_item_refs {
936 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
941 "negative impls cannot have any items"
949 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
951 for impl_item in impl_item_refs {
952 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
953 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
954 tcx.associated_item(trait_item_id)
956 // Checked in `associated_item`.
957 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
960 let impl_item_full = tcx.hir().impl_item(impl_item.id);
961 match impl_item_full.kind {
962 hir::ImplItemKind::Const(..) => {
963 // Find associated const definition.
972 hir::ImplItemKind::Fn(..) => {
973 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
983 hir::ImplItemKind::TyAlias(impl_ty) => {
984 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
996 check_specialization_validity(
1000 impl_id.to_def_id(),
1005 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1006 // Check for missing items from trait
1007 let mut missing_items = Vec::new();
1009 let mut must_implement_one_of: Option<&[Ident]> =
1010 trait_def.must_implement_one_of.as_deref();
1012 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1013 let is_implemented = ancestors
1014 .leaf_def(tcx, trait_item_id)
1015 .map_or(false, |node_item| node_item.item.defaultness.has_value());
1017 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1018 missing_items.push(tcx.associated_item(trait_item_id));
1021 if let Some(required_items) = &must_implement_one_of {
1022 // true if this item is specifically implemented in this impl
1023 let is_implemented_here = ancestors
1024 .leaf_def(tcx, trait_item_id)
1025 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1027 if is_implemented_here {
1028 let trait_item = tcx.associated_item(trait_item_id);
1029 if required_items.contains(&trait_item.ident(tcx)) {
1030 must_implement_one_of = None;
1036 if !missing_items.is_empty() {
1037 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1038 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1041 if let Some(missing_items) = must_implement_one_of {
1042 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1044 .get_attrs(impl_trait_ref.def_id)
1046 .find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1047 .map(|attr| attr.span);
1049 missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1054 /// Checks whether a type can be represented in memory. In particular, it
1055 /// identifies types that contain themselves without indirection through a
1056 /// pointer, which would mean their size is unbounded.
1057 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1058 let rty = tcx.type_of(item_def_id);
1060 // Check that it is possible to represent this type. This call identifies
1061 // (1) types that contain themselves and (2) types that contain a different
1062 // recursive type. It is only necessary to throw an error on those that
1063 // contain themselves. For case 2, there must be an inner type that will be
1064 // caught by case 1.
1065 match representability::ty_is_representable(tcx, rty, sp) {
1066 Representability::SelfRecursive(spans) => {
1067 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1070 Representability::Representable | Representability::ContainsRecursive => (),
1075 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1076 let t = tcx.type_of(def_id);
1077 if let ty::Adt(def, substs) = t.kind() {
1078 if def.is_struct() {
1079 let fields = &def.non_enum_variant().fields;
1080 if fields.is_empty() {
1081 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1084 let e = fields[0].ty(tcx, substs);
1085 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1086 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1087 .span_label(sp, "SIMD elements must have the same type")
1092 let len = if let ty::Array(_ty, c) = e.kind() {
1093 c.try_eval_usize(tcx, tcx.param_env(def.did))
1095 Some(fields.len() as u64)
1097 if let Some(len) = len {
1099 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1101 } else if len > MAX_SIMD_LANES {
1106 "SIMD vector cannot have more than {} elements",
1114 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1115 // These are scalar types which directly match a "machine" type
1116 // Yes: Integers, floats, "thin" pointers
1117 // No: char, "fat" pointers, compound types
1119 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1120 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1121 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1125 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1127 { /* struct([f32; 4]) is ok */ }
1133 "SIMD vector element type should be a \
1134 primitive scalar (integer/float/pointer) type"
1144 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1145 let repr = def.repr;
1147 for attr in tcx.get_attrs(def.did).iter() {
1148 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1149 if let attr::ReprPacked(pack) = r {
1150 if let Some(repr_pack) = repr.pack {
1151 if pack as u64 != repr_pack.bytes() {
1156 "type has conflicting packed representation hints"
1164 if repr.align.is_some() {
1169 "type has conflicting packed and align representation hints"
1173 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1174 let mut err = struct_span_err!(
1178 "packed type cannot transitively contain a `#[repr(align)]` type"
1182 tcx.def_span(def_spans[0].0),
1184 "`{}` has a `#[repr(align)]` attribute",
1185 tcx.item_name(def_spans[0].0)
1189 if def_spans.len() > 2 {
1190 let mut first = true;
1191 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1192 let ident = tcx.item_name(*adt_def);
1197 "`{}` contains a field of type `{}`",
1198 tcx.type_of(def.did),
1202 format!("...which contains a field of type `{}`", ident)
1215 pub(super) fn check_packed_inner(
1218 stack: &mut Vec<DefId>,
1219 ) -> Option<Vec<(DefId, Span)>> {
1220 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1221 if def.is_struct() || def.is_union() {
1222 if def.repr.align.is_some() {
1223 return Some(vec![(def.did, DUMMY_SP)]);
1227 for field in &def.non_enum_variant().fields {
1228 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1229 if !stack.contains(&def.did) {
1230 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1231 defs.push((def.did, field.ident(tcx).span));
1244 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1245 if !adt.repr.transparent() {
1248 let sp = tcx.sess.source_map().guess_head_span(sp);
1250 if adt.is_union() && !tcx.features().transparent_unions {
1252 &tcx.sess.parse_sess,
1253 sym::transparent_unions,
1255 "transparent unions are unstable",
1260 if adt.variants.len() != 1 {
1261 bad_variant_count(tcx, adt, sp, adt.did);
1262 if adt.variants.is_empty() {
1263 // Don't bother checking the fields. No variants (and thus no fields) exist.
1268 // For each field, figure out if it's known to be a ZST and align(1)
1269 let field_infos = adt.all_fields().map(|field| {
1270 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1271 let param_env = tcx.param_env(field.did);
1272 let layout = tcx.layout_of(param_env.and(ty));
1273 // We are currently checking the type this field came from, so it must be local
1274 let span = tcx.hir().span_if_local(field.did).unwrap();
1275 let zst = layout.map_or(false, |layout| layout.is_zst());
1276 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1280 let non_zst_fields =
1281 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1282 let non_zst_count = non_zst_fields.clone().count();
1283 if non_zst_count >= 2 {
1284 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1286 for (span, zst, align1) in field_infos {
1292 "zero-sized field in transparent {} has alignment larger than 1",
1295 .span_label(span, "has alignment larger than 1")
1301 #[allow(trivial_numeric_casts)]
1302 fn check_enum<'tcx>(
1305 vs: &'tcx [hir::Variant<'tcx>],
1308 let def = tcx.adt_def(def_id);
1309 def.destructor(tcx); // force the destructor to be evaluated
1312 let attributes = tcx.get_attrs(def_id.to_def_id());
1313 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1318 "unsupported representation for zero-variant enum"
1320 .span_label(sp, "zero-variant enum")
1325 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1326 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1327 if !tcx.features().repr128 {
1329 &tcx.sess.parse_sess,
1332 "repr with 128-bit type is unstable",
1339 if let Some(ref e) = v.disr_expr {
1340 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1344 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1345 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1347 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1348 let has_non_units = vs.iter().any(|var| !is_unit(var));
1349 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1350 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1352 if disr_non_unit || (disr_units && has_non_units) {
1354 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1359 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1360 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1361 // Check for duplicate discriminant values
1362 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1363 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1364 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1365 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1366 let i_span = match variant_i.disr_expr {
1367 Some(ref expr) => tcx.hir().span(expr.hir_id),
1368 None => tcx.def_span(variant_did),
1370 let span = match v.disr_expr {
1371 Some(ref expr) => tcx.hir().span(expr.hir_id),
1374 let display_discr = display_discriminant_value(tcx, v, discr.val);
1375 let display_discr_i = display_discriminant_value(tcx, variant_i, disr_vals[i].val);
1380 "discriminant value `{}` already exists",
1383 .span_label(i_span, format!("first use of {}", display_discr_i))
1384 .span_label(span, format!("enum already has {}", display_discr))
1387 disr_vals.push(discr);
1390 check_representable(tcx, sp, def_id);
1391 check_transparent(tcx, sp, def);
1394 /// Format an enum discriminant value for use in a diagnostic message.
1395 fn display_discriminant_value<'tcx>(
1397 variant: &hir::Variant<'_>,
1400 if let Some(expr) = &variant.disr_expr {
1401 let body = &tcx.hir().body(expr.body).value;
1402 if let hir::ExprKind::Lit(lit) = &body.kind {
1403 if let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node {
1404 if evaluated != *lit_value {
1405 return format!("`{}` (overflowed from `{}`)", evaluated, lit_value);
1410 format!("`{}`", evaluated)
1413 pub(super) fn check_type_params_are_used<'tcx>(
1415 generics: &ty::Generics,
1418 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1420 assert_eq!(generics.parent, None);
1422 if generics.own_counts().types == 0 {
1426 let mut params_used = BitSet::new_empty(generics.params.len());
1428 if ty.references_error() {
1429 // If there is already another error, do not emit
1430 // an error for not using a type parameter.
1431 assert!(tcx.sess.has_errors());
1435 for leaf in ty.walk() {
1436 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1437 if let ty::Param(param) = leaf_ty.kind() {
1438 debug!("found use of ty param {:?}", param);
1439 params_used.insert(param.index);
1444 for param in &generics.params {
1445 if !params_used.contains(param.index) {
1446 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1447 let span = tcx.def_span(param.def_id);
1452 "type parameter `{}` is unused",
1455 .span_label(span, "unused type parameter")
1462 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1463 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1466 pub(super) use wfcheck::check_item_well_formed;
1468 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1470 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1472 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) {
1473 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1474 .span_label(span, "recursive `async fn`")
1475 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1477 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1482 /// Emit an error for recursive opaque types.
1484 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1485 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1488 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1489 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1490 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
1491 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1493 let mut label = false;
1494 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1495 let typeck_results = tcx.typeck(def_id);
1499 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1500 .all(|ty| matches!(ty.kind(), ty::Never))
1505 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1506 .map(|expr| expr.span)
1507 .collect::<Vec<Span>>();
1508 let span_len = spans.len();
1510 err.span_label(spans[0], "this returned value is of `!` type");
1512 let mut multispan: MultiSpan = spans.clone().into();
1515 .push_span_label(span, "this returned value is of `!` type".to_string());
1517 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1519 err.help("this error will resolve once the item's body returns a concrete type");
1521 let mut seen = FxHashSet::default();
1523 err.span_label(span, "recursive opaque type");
1525 for (sp, ty) in visitor
1528 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1529 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1531 struct OpaqueTypeCollector(Vec<DefId>);
1532 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1533 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1535 ty::Opaque(def, _) => {
1537 ControlFlow::CONTINUE
1539 _ => t.super_visit_with(self),
1543 let mut visitor = OpaqueTypeCollector(vec![]);
1544 ty.visit_with(&mut visitor);
1545 for def_id in visitor.0 {
1546 let ty_span = tcx.def_span(def_id);
1547 if !seen.contains(&ty_span) {
1548 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1549 seen.insert(ty_span);
1551 err.span_label(sp, &format!("returning here with type `{}`", ty));
1557 err.span_label(span, "cannot resolve opaque type");