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 && let ItemKind::Fn(_, ref generics, _) = item.kind
287 && !generics.params.is_empty()
289 sess.span_err(span, "should have no type parameters");
292 let span = sess.source_map().guess_head_span(span);
293 sess.span_err(span, "function should have one argument");
296 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 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
304 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
305 if *declared_ret_ty.kind() != ty::Never {
306 sess.span_err(decl.output.span(), "return type should be `!`");
309 let inputs = fn_sig.inputs();
310 let span = hir.span(fn_id);
311 if inputs.len() == 1 {
312 let arg_is_alloc_layout = match inputs[0].kind() {
313 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
317 if !arg_is_alloc_layout {
318 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
321 if let Node::Item(item) = hir.get(fn_id)
322 && let ItemKind::Fn(_, ref generics, _) = item.kind
323 && !generics.params.is_empty()
327 "`#[alloc_error_handler]` function should have no type parameters",
331 let span = sess.source_map().guess_head_span(span);
332 sess.span_err(span, "function should have one argument");
335 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);
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<(), ErrorReported> {
627 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
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 hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
660 let defining_use_anchor = match *origin {
661 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
662 hir::OpaqueTyOrigin::TyAlias => def_id,
664 let param_env = tcx.param_env(defining_use_anchor);
666 tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
667 let inh = Inherited::new(infcx, def_id);
668 let infcx = &inh.infcx;
669 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
671 let misc_cause = traits::ObligationCause::misc(span, hir_id);
673 let _ = inh.register_infer_ok_obligations(
674 infcx.instantiate_opaque_types(hir_id, param_env, opaque_ty, span),
677 let opaque_type_map = infcx.inner.borrow().opaque_types.clone();
678 for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map {
679 let hidden_type = tcx.type_of(def_id).subst(tcx, substs);
680 trace!(?hidden_type);
681 match infcx.at(&misc_cause, param_env).eq(opaque_defn.concrete_ty, hidden_type) {
682 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
683 Err(ty_err) => tcx.sess.delay_span_bug(
686 "could not check bounds on revealed type `{}`:\n{}",
693 // Check that all obligations are satisfied by the implementation's
695 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
696 if !errors.is_empty() {
697 infcx.report_fulfillment_errors(&errors, None, false);
701 // Checked when type checking the function containing them.
702 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return,
703 // Can have different predicates to their defining use
704 hir::OpaqueTyOrigin::TyAlias => {
705 // Finally, resolve all regions. This catches wily misuses of
706 // lifetime parameters.
707 let fcx = FnCtxt::new(&inh, param_env, hir_id);
708 fcx.regionck_item(hir_id, span, FxHashSet::default());
714 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
716 "check_item_type(it.def_id={:?}, it.name={})",
718 tcx.def_path_str(it.def_id.to_def_id())
720 let _indenter = indenter();
722 // Consts can play a role in type-checking, so they are included here.
723 hir::ItemKind::Static(..) => {
724 tcx.ensure().typeck(it.def_id);
725 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
726 check_static_inhabited(tcx, it.def_id, it.span);
728 hir::ItemKind::Const(..) => {
729 tcx.ensure().typeck(it.def_id);
731 hir::ItemKind::Enum(ref enum_definition, _) => {
732 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
734 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
735 hir::ItemKind::Impl(ref impl_) => {
736 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
737 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
738 check_impl_items_against_trait(
745 let trait_def_id = impl_trait_ref.def_id;
746 check_on_unimplemented(tcx, trait_def_id, it);
749 hir::ItemKind::Trait(_, _, _, _, ref items) => {
750 check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
752 for item in items.iter() {
753 let item = tcx.hir().trait_item(item.id);
755 hir::TraitItemKind::Fn(ref sig, _) => {
756 let abi = sig.header.abi;
757 fn_maybe_err(tcx, item.ident.span, abi);
759 hir::TraitItemKind::Type(.., Some(default)) => {
760 let assoc_item = tcx.associated_item(item.def_id);
762 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
763 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
768 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
775 hir::ItemKind::Struct(..) => {
776 check_struct(tcx, it.def_id, it.span);
778 hir::ItemKind::Union(..) => {
779 check_union(tcx, it.def_id, it.span);
781 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
782 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
783 // `async-std` (and `pub async fn` in general).
784 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
785 // See https://github.com/rust-lang/rust/issues/75100
786 if !tcx.sess.opts.actually_rustdoc {
787 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
788 check_opaque(tcx, it.def_id, substs, it.span, &origin);
791 hir::ItemKind::TyAlias(..) => {
792 let pty_ty = tcx.type_of(it.def_id);
793 let generics = tcx.generics_of(it.def_id);
794 check_type_params_are_used(tcx, &generics, pty_ty);
796 hir::ItemKind::ForeignMod { abi, items } => {
797 check_abi(tcx, it.hir_id(), it.span, abi);
799 if abi == Abi::RustIntrinsic {
801 let item = tcx.hir().foreign_item(item.id);
802 intrinsic::check_intrinsic_type(tcx, item);
804 } else if abi == Abi::PlatformIntrinsic {
806 let item = tcx.hir().foreign_item(item.id);
807 intrinsic::check_platform_intrinsic_type(tcx, item);
811 let def_id = item.id.def_id;
812 let generics = tcx.generics_of(def_id);
813 let own_counts = generics.own_counts();
814 if generics.params.len() - own_counts.lifetimes != 0 {
815 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
816 (_, 0) => ("type", "types", Some("u32")),
817 // We don't specify an example value, because we can't generate
818 // a valid value for any type.
819 (0, _) => ("const", "consts", None),
820 _ => ("type or const", "types or consts", None),
826 "foreign items may not have {} parameters",
829 .span_label(item.span, &format!("can't have {} parameters", kinds))
831 // FIXME: once we start storing spans for type arguments, turn this
832 // into a suggestion.
834 "replace the {} parameters with concrete {}{}",
837 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
843 let item = tcx.hir().foreign_item(item.id);
845 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
846 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
848 hir::ForeignItemKind::Static(..) => {
849 check_static_inhabited(tcx, def_id, item.span);
856 _ => { /* nothing to do */ }
860 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
861 // an error would be reported if this fails.
862 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
865 pub(super) fn check_specialization_validity<'tcx>(
867 trait_def: &ty::TraitDef,
868 trait_item: &ty::AssocItem,
870 impl_item: &hir::ImplItemRef,
872 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
873 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
874 if parent.is_from_trait() {
877 Some((parent, parent.item(tcx, trait_item.def_id)))
881 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
883 // Parent impl exists, and contains the parent item we're trying to specialize, but
884 // doesn't mark it `default`.
885 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
886 Some(Err(parent_impl.def_id()))
889 // Parent impl contains item and makes it specializable.
890 Some(_) => Some(Ok(())),
892 // Parent impl doesn't mention the item. This means it's inherited from the
893 // grandparent. In that case, if parent is a `default impl`, inherited items use the
894 // "defaultness" from the grandparent, else they are final.
896 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
899 Some(Err(parent_impl.def_id()))
905 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
906 // item. This is allowed, the item isn't actually getting specialized here.
907 let result = opt_result.unwrap_or(Ok(()));
909 if let Err(parent_impl) = result {
910 report_forbidden_specialization(tcx, impl_item, parent_impl);
914 fn check_impl_items_against_trait<'tcx>(
916 full_impl_span: Span,
918 impl_trait_ref: ty::TraitRef<'tcx>,
919 impl_item_refs: &[hir::ImplItemRef],
921 // If the trait reference itself is erroneous (so the compilation is going
922 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
923 // isn't populated for such impls.
924 if impl_trait_ref.references_error() {
928 // Negative impls are not expected to have any items
929 match tcx.impl_polarity(impl_id) {
930 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
931 ty::ImplPolarity::Negative => {
932 if let [first_item_ref, ..] = impl_item_refs {
933 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
938 "negative impls cannot have any items"
946 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
948 for impl_item in impl_item_refs {
949 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
950 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
951 tcx.associated_item(trait_item_id)
953 // Checked in `associated_item`.
954 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
957 let impl_item_full = tcx.hir().impl_item(impl_item.id);
958 match impl_item_full.kind {
959 hir::ImplItemKind::Const(..) => {
960 // Find associated const definition.
969 hir::ImplItemKind::Fn(..) => {
970 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
980 hir::ImplItemKind::TyAlias(impl_ty) => {
981 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
993 check_specialization_validity(
1002 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1003 // Check for missing items from trait
1004 let mut missing_items = Vec::new();
1006 let mut must_implement_one_of: Option<&[Ident]> =
1007 trait_def.must_implement_one_of.as_deref();
1009 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1010 let is_implemented = ancestors
1011 .leaf_def(tcx, trait_item_id)
1012 .map_or(false, |node_item| node_item.item.defaultness.has_value());
1014 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1015 missing_items.push(tcx.associated_item(trait_item_id));
1018 if let Some(required_items) = &must_implement_one_of {
1019 // true if this item is specifically implemented in this impl
1020 let is_implemented_here = ancestors
1021 .leaf_def(tcx, trait_item_id)
1022 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1024 if is_implemented_here {
1025 let trait_item = tcx.associated_item(trait_item_id);
1026 if required_items.contains(&trait_item.ident(tcx)) {
1027 must_implement_one_of = None;
1033 if !missing_items.is_empty() {
1034 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1035 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1038 if let Some(missing_items) = must_implement_one_of {
1039 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1041 .get_attrs(impl_trait_ref.def_id)
1043 .find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1044 .map(|attr| attr.span);
1046 missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1051 /// Checks whether a type can be represented in memory. In particular, it
1052 /// identifies types that contain themselves without indirection through a
1053 /// pointer, which would mean their size is unbounded.
1054 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1055 let rty = tcx.type_of(item_def_id);
1057 // Check that it is possible to represent this type. This call identifies
1058 // (1) types that contain themselves and (2) types that contain a different
1059 // recursive type. It is only necessary to throw an error on those that
1060 // contain themselves. For case 2, there must be an inner type that will be
1061 // caught by case 1.
1062 match representability::ty_is_representable(tcx, rty, sp) {
1063 Representability::SelfRecursive(spans) => {
1064 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1067 Representability::Representable | Representability::ContainsRecursive => (),
1072 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1073 let t = tcx.type_of(def_id);
1074 if let ty::Adt(def, substs) = t.kind() {
1075 if def.is_struct() {
1076 let fields = &def.non_enum_variant().fields;
1077 if fields.is_empty() {
1078 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1081 let e = fields[0].ty(tcx, substs);
1082 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1083 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1084 .span_label(sp, "SIMD elements must have the same type")
1089 let len = if let ty::Array(_ty, c) = e.kind() {
1090 c.try_eval_usize(tcx, tcx.param_env(def.did))
1092 Some(fields.len() as u64)
1094 if let Some(len) = len {
1096 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1098 } else if len > MAX_SIMD_LANES {
1103 "SIMD vector cannot have more than {} elements",
1111 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1112 // These are scalar types which directly match a "machine" type
1113 // Yes: Integers, floats, "thin" pointers
1114 // No: char, "fat" pointers, compound types
1116 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1117 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1118 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1122 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1124 { /* struct([f32; 4]) is ok */ }
1130 "SIMD vector element type should be a \
1131 primitive scalar (integer/float/pointer) type"
1141 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1142 let repr = def.repr;
1144 for attr in tcx.get_attrs(def.did).iter() {
1145 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1146 if let attr::ReprPacked(pack) = r
1147 && let Some(repr_pack) = repr.pack
1148 && pack as u64 != repr_pack.bytes()
1154 "type has conflicting packed representation hints"
1160 if repr.align.is_some() {
1165 "type has conflicting packed and align representation hints"
1169 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1170 let mut err = struct_span_err!(
1174 "packed type cannot transitively contain a `#[repr(align)]` type"
1178 tcx.def_span(def_spans[0].0),
1180 "`{}` has a `#[repr(align)]` attribute",
1181 tcx.item_name(def_spans[0].0)
1185 if def_spans.len() > 2 {
1186 let mut first = true;
1187 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1188 let ident = tcx.item_name(*adt_def);
1193 "`{}` contains a field of type `{}`",
1194 tcx.type_of(def.did),
1198 format!("...which contains a field of type `{}`", ident)
1211 pub(super) fn check_packed_inner(
1214 stack: &mut Vec<DefId>,
1215 ) -> Option<Vec<(DefId, Span)>> {
1216 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1217 if def.is_struct() || def.is_union() {
1218 if def.repr.align.is_some() {
1219 return Some(vec![(def.did, DUMMY_SP)]);
1223 for field in &def.non_enum_variant().fields {
1224 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1225 if !stack.contains(&def.did) {
1226 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1227 defs.push((def.did, field.ident(tcx).span));
1240 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1241 if !adt.repr.transparent() {
1244 let sp = tcx.sess.source_map().guess_head_span(sp);
1246 if adt.is_union() && !tcx.features().transparent_unions {
1248 &tcx.sess.parse_sess,
1249 sym::transparent_unions,
1251 "transparent unions are unstable",
1256 if adt.variants.len() != 1 {
1257 bad_variant_count(tcx, adt, sp, adt.did);
1258 if adt.variants.is_empty() {
1259 // Don't bother checking the fields. No variants (and thus no fields) exist.
1264 // For each field, figure out if it's known to be a ZST and align(1)
1265 let field_infos = adt.all_fields().map(|field| {
1266 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1267 let param_env = tcx.param_env(field.did);
1268 let layout = tcx.layout_of(param_env.and(ty));
1269 // We are currently checking the type this field came from, so it must be local
1270 let span = tcx.hir().span_if_local(field.did).unwrap();
1271 let zst = layout.map_or(false, |layout| layout.is_zst());
1272 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1276 let non_zst_fields =
1277 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1278 let non_zst_count = non_zst_fields.clone().count();
1279 if non_zst_count >= 2 {
1280 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1282 for (span, zst, align1) in field_infos {
1288 "zero-sized field in transparent {} has alignment larger than 1",
1291 .span_label(span, "has alignment larger than 1")
1297 #[allow(trivial_numeric_casts)]
1298 fn check_enum<'tcx>(
1301 vs: &'tcx [hir::Variant<'tcx>],
1304 let def = tcx.adt_def(def_id);
1305 def.destructor(tcx); // force the destructor to be evaluated
1308 let attributes = tcx.get_attrs(def_id.to_def_id());
1309 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1314 "unsupported representation for zero-variant enum"
1316 .span_label(sp, "zero-variant enum")
1321 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1322 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1323 if !tcx.features().repr128 {
1325 &tcx.sess.parse_sess,
1328 "repr with 128-bit type is unstable",
1335 if let Some(ref e) = v.disr_expr {
1336 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1340 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1341 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1343 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1344 let has_non_units = vs.iter().any(|var| !is_unit(var));
1345 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1346 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1348 if disr_non_unit || (disr_units && has_non_units) {
1350 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1355 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1356 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1357 // Check for duplicate discriminant values
1358 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1359 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1360 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1361 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1362 let i_span = match variant_i.disr_expr {
1363 Some(ref expr) => tcx.hir().span(expr.hir_id),
1364 None => tcx.def_span(variant_did),
1366 let span = match v.disr_expr {
1367 Some(ref expr) => tcx.hir().span(expr.hir_id),
1370 let display_discr = display_discriminant_value(tcx, v, discr.val);
1371 let display_discr_i = display_discriminant_value(tcx, variant_i, disr_vals[i].val);
1376 "discriminant value `{}` already exists",
1379 .span_label(i_span, format!("first use of {}", display_discr_i))
1380 .span_label(span, format!("enum already has {}", display_discr))
1383 disr_vals.push(discr);
1386 check_representable(tcx, sp, def_id);
1387 check_transparent(tcx, sp, def);
1390 /// Format an enum discriminant value for use in a diagnostic message.
1391 fn display_discriminant_value<'tcx>(
1393 variant: &hir::Variant<'_>,
1396 if let Some(expr) = &variant.disr_expr {
1397 let body = &tcx.hir().body(expr.body).value;
1398 if let hir::ExprKind::Lit(lit) = &body.kind
1399 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1400 && evaluated != *lit_value
1402 return format!("`{}` (overflowed from `{}`)", evaluated, lit_value);
1405 format!("`{}`", evaluated)
1408 pub(super) fn check_type_params_are_used<'tcx>(
1410 generics: &ty::Generics,
1413 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1415 assert_eq!(generics.parent, None);
1417 if generics.own_counts().types == 0 {
1421 let mut params_used = BitSet::new_empty(generics.params.len());
1423 if ty.references_error() {
1424 // If there is already another error, do not emit
1425 // an error for not using a type parameter.
1426 assert!(tcx.sess.has_errors());
1430 for leaf in ty.walk() {
1431 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1432 if let ty::Param(param) = leaf_ty.kind() {
1433 debug!("found use of ty param {:?}", param);
1434 params_used.insert(param.index);
1439 for param in &generics.params {
1440 if !params_used.contains(param.index) {
1441 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1442 let span = tcx.def_span(param.def_id);
1447 "type parameter `{}` is unused",
1450 .span_label(span, "unused type parameter")
1457 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1458 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1461 pub(super) use wfcheck::check_item_well_formed;
1463 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1465 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1467 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) {
1468 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1469 .span_label(span, "recursive `async fn`")
1470 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1472 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1477 /// Emit an error for recursive opaque types.
1479 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1480 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1483 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1484 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1485 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
1486 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1488 let mut label = false;
1489 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1490 let typeck_results = tcx.typeck(def_id);
1494 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1495 .all(|ty| matches!(ty.kind(), ty::Never))
1500 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1501 .map(|expr| expr.span)
1502 .collect::<Vec<Span>>();
1503 let span_len = spans.len();
1505 err.span_label(spans[0], "this returned value is of `!` type");
1507 let mut multispan: MultiSpan = spans.clone().into();
1510 .push_span_label(span, "this returned value is of `!` type".to_string());
1512 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1514 err.help("this error will resolve once the item's body returns a concrete type");
1516 let mut seen = FxHashSet::default();
1518 err.span_label(span, "recursive opaque type");
1520 for (sp, ty) in visitor
1523 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1524 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1526 struct OpaqueTypeCollector(Vec<DefId>);
1527 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1528 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1530 ty::Opaque(def, _) => {
1532 ControlFlow::CONTINUE
1534 _ => t.super_visit_with(self),
1538 let mut visitor = OpaqueTypeCollector(vec![]);
1539 ty.visit_with(&mut visitor);
1540 for def_id in visitor.0 {
1541 let ty_span = tcx.def_span(def_id);
1542 if !seen.contains(&ty_span) {
1543 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1544 seen.insert(ty_span);
1546 err.span_label(sp, &format!("returning here with type `{}`", ty));
1552 err.span_label(span, "cannot resolve opaque type");