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, LOCAL_CRATE};
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::ty::fold::TypeFoldable;
16 use rustc_middle::ty::layout::MAX_SIMD_LANES;
17 use rustc_middle::ty::subst::GenericArgKind;
18 use rustc_middle::ty::util::{Discr, IntTypeExt, Representability};
19 use rustc_middle::ty::{self, ParamEnv, RegionKind, ToPredicate, Ty, TyCtxt};
20 use rustc_session::config::EntryFnType;
21 use rustc_session::lint::builtin::UNINHABITED_STATIC;
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::opaque_types::InferCtxtExt as _;
26 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
27 use rustc_trait_selection::traits::{self, ObligationCauseCode};
29 use std::ops::ControlFlow;
31 pub fn check_wf_new(tcx: TyCtxt<'_>) {
32 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
33 tcx.hir().krate().par_visit_all_item_likes(&visit);
36 pub(super) fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) {
37 if !tcx.sess.target.is_abi_supported(abi) {
42 "The ABI `{}` is not supported for the current target",
48 // This ABI is only allowed on function pointers
49 if abi == Abi::CCmseNonSecureCall {
54 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers."
60 /// Helper used for fns and closures. Does the grungy work of checking a function
61 /// body and returns the function context used for that purpose, since in the case of a fn item
62 /// there is still a bit more to do.
65 /// * inherited: other fields inherited from the enclosing fn (if any)
66 pub(super) fn check_fn<'a, 'tcx>(
67 inherited: &'a Inherited<'a, 'tcx>,
68 param_env: ty::ParamEnv<'tcx>,
69 fn_sig: ty::FnSig<'tcx>,
70 decl: &'tcx hir::FnDecl<'tcx>,
72 body: &'tcx hir::Body<'tcx>,
73 can_be_generator: Option<hir::Movability>,
74 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
75 let mut fn_sig = fn_sig;
77 debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env);
79 // Create the function context. This is either derived from scratch or,
80 // in the case of closures, based on the outer context.
81 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
82 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
88 let declared_ret_ty = fn_sig.output();
90 let feature = match tcx.hir().get(fn_id) {
91 // TAIT usage in function return position.
95 // type Foo = impl Debug;
96 // fn bar() -> Foo { 42 }
98 Node::Item(hir::Item { kind: ItemKind::Fn(..), .. }) |
99 // TAIT usage in associated function return position.
101 // Example with a free type alias:
104 // type Foo = impl Debug;
105 // impl SomeTrait for SomeType {
106 // fn bar() -> Foo { 42 }
110 // Example with an associated TAIT:
113 // impl SomeTrait for SomeType {
114 // type Foo = impl Debug;
115 // fn bar() -> Self::Foo { 42 }
118 Node::ImplItem(hir::ImplItem {
119 kind: hir::ImplItemKind::Fn(..), ..
121 // Forbid TAIT in trait declarations for now.
125 // type Foo = impl Debug;
130 // type Bop: PartialEq<Foo>;
133 Node::TraitItem(hir::TraitItem {
134 kind: hir::TraitItemKind::Fn(..),
137 // Forbid TAIT in closure return position for now.
141 // type Foo = impl Debug;
142 // let x = |y| -> Foo { 42 + y };
144 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => Some(sym::type_alias_impl_trait),
145 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
147 let revealed_ret_ty = fcx.instantiate_opaque_types_from_value(
153 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
154 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
155 fcx.ret_type_span = Some(decl.output.span());
156 if let ty::Opaque(..) = declared_ret_ty.kind() {
157 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
159 fn_sig = tcx.mk_fn_sig(
160 fn_sig.inputs().iter().cloned(),
167 let span = body.value.span;
169 fn_maybe_err(tcx, span, fn_sig.abi);
171 if fn_sig.abi == Abi::RustCall {
172 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
175 let item = match tcx.hir().get(fn_id) {
176 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
177 Node::ImplItem(hir::ImplItem {
178 kind: hir::ImplItemKind::Fn(header, ..), ..
180 Node::TraitItem(hir::TraitItem {
181 kind: hir::TraitItemKind::Fn(header, ..),
184 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
185 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
186 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
189 if let Some(header) = item {
190 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple")
194 if fn_sig.inputs().len() != expected_args {
197 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
198 // This will probably require wide-scale changes to support a TupleKind obligation
199 // We can't resolve this without knowing the type of the param
200 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
206 if body.generator_kind.is_some() && can_be_generator.is_some() {
208 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
209 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
211 // Resume type defaults to `()` if the generator has no argument.
212 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
214 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
217 let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id).to_def_id()).expect_local();
218 let outer_hir_id = hir.local_def_id_to_hir_id(outer_def_id);
219 GatherLocalsVisitor::new(&fcx, outer_hir_id).visit_body(body);
221 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
222 // (as it's created inside the body itself, not passed in from outside).
223 let maybe_va_list = if fn_sig.c_variadic {
224 let span = body.params.last().unwrap().span;
225 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
226 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
228 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
233 // Add formal parameters.
234 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
235 let inputs_fn = fn_sig.inputs().iter().copied();
236 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
237 // Check the pattern.
238 let ty_span = try { inputs_hir?.get(idx)?.span };
239 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
241 // Check that argument is Sized.
242 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
243 // for simple cases like `fn foo(x: Trait)`,
244 // where we would error once on the parameter as a whole, and once on the binding `x`.
245 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
246 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
249 fcx.write_ty(param.hir_id, param_ty);
252 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
254 fcx.in_tail_expr = true;
255 if let ty::Dynamic(..) = declared_ret_ty.kind() {
256 // FIXME: We need to verify that the return type is `Sized` after the return expression has
257 // been evaluated so that we have types available for all the nodes being returned, but that
258 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
259 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
260 // while keeping the current ordering we will ignore the tail expression's type because we
261 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
262 // because we will trigger "unreachable expression" lints unconditionally.
263 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
264 // case that a newcomer might make, returning a bare trait, and in that case we populate
265 // the tail expression's type so that the suggestion will be correct, but ignore all other
267 fcx.check_expr(&body.value);
268 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
270 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
271 fcx.check_return_expr(&body.value);
273 fcx.in_tail_expr = false;
275 // We insert the deferred_generator_interiors entry after visiting the body.
276 // This ensures that all nested generators appear before the entry of this generator.
277 // resolve_generator_interiors relies on this property.
278 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
280 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
281 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
283 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
284 Some(GeneratorTypes {
288 movability: can_be_generator.unwrap(),
294 // Finalize the return check by taking the LUB of the return types
295 // we saw and assigning it to the expected return type. This isn't
296 // really expected to fail, since the coercions would have failed
297 // earlier when trying to find a LUB.
299 // However, the behavior around `!` is sort of complex. In the
300 // event that the `actual_return_ty` comes back as `!`, that
301 // indicates that the fn either does not return or "returns" only
302 // values of type `!`. In this case, if there is an expected
303 // return type that is *not* `!`, that should be ok. But if the
304 // return type is being inferred, we want to "fallback" to `!`:
306 // let x = move || panic!();
308 // To allow for that, I am creating a type variable with diverging
309 // fallback. This was deemed ever so slightly better than unifying
310 // the return value with `!` because it allows for the caller to
311 // make more assumptions about the return type (e.g., they could do
313 // let y: Option<u32> = Some(x());
315 // which would then cause this return type to become `u32`, not
317 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
318 let mut actual_return_ty = coercion.complete(&fcx);
319 if actual_return_ty.is_never() {
320 actual_return_ty = fcx.next_diverging_ty_var(TypeVariableOrigin {
321 kind: TypeVariableOriginKind::DivergingFn,
325 fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty);
327 // Check that the main return type implements the termination trait.
328 if let Some(term_id) = tcx.lang_items().termination() {
329 if let Some((def_id, EntryFnType::Main)) = tcx.entry_fn(LOCAL_CRATE) {
330 let main_id = hir.local_def_id_to_hir_id(def_id);
331 if main_id == fn_id {
332 let substs = tcx.mk_substs_trait(declared_ret_ty, &[]);
333 let trait_ref = ty::TraitRef::new(term_id, substs);
334 let return_ty_span = decl.output.span();
335 let cause = traits::ObligationCause::new(
338 ObligationCauseCode::MainFunctionType,
341 inherited.register_predicate(traits::Obligation::new(
344 trait_ref.without_const().to_predicate(tcx),
350 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
351 if let Some(panic_impl_did) = tcx.lang_items().panic_impl() {
352 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
353 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
354 if *declared_ret_ty.kind() != ty::Never {
355 sess.span_err(decl.output.span(), "return type should be `!`");
358 let inputs = fn_sig.inputs();
359 let span = hir.span(fn_id);
360 if inputs.len() == 1 {
361 let arg_is_panic_info = match *inputs[0].kind() {
362 ty::Ref(region, ty, mutbl) => match *ty.kind() {
363 ty::Adt(ref adt, _) => {
364 adt.did == panic_info_did
365 && mutbl == hir::Mutability::Not
366 && *region != RegionKind::ReStatic
373 if !arg_is_panic_info {
374 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
377 if let Node::Item(item) = hir.get(fn_id) {
378 if let ItemKind::Fn(_, ref generics, _) = item.kind {
379 if !generics.params.is_empty() {
380 sess.span_err(span, "should have no type parameters");
385 let span = sess.source_map().guess_head_span(span);
386 sess.span_err(span, "function should have one argument");
389 sess.err("language item required, but not found: `panic_info`");
394 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
395 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
396 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
397 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
398 if *declared_ret_ty.kind() != ty::Never {
399 sess.span_err(decl.output.span(), "return type should be `!`");
402 let inputs = fn_sig.inputs();
403 let span = hir.span(fn_id);
404 if inputs.len() == 1 {
405 let arg_is_alloc_layout = match inputs[0].kind() {
406 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
410 if !arg_is_alloc_layout {
411 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
414 if let Node::Item(item) = hir.get(fn_id) {
415 if let ItemKind::Fn(_, ref generics, _) = item.kind {
416 if !generics.params.is_empty() {
419 "`#[alloc_error_handler]` function should have no type \
426 let span = sess.source_map().guess_head_span(span);
427 sess.span_err(span, "function should have one argument");
430 sess.err("language item required, but not found: `alloc_layout`");
438 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
439 let def = tcx.adt_def(def_id);
440 def.destructor(tcx); // force the destructor to be evaluated
441 check_representable(tcx, span, def_id);
444 check_simd(tcx, span, def_id);
447 check_transparent(tcx, span, def);
448 check_packed(tcx, span, def);
451 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
452 let def = tcx.adt_def(def_id);
453 def.destructor(tcx); // force the destructor to be evaluated
454 check_representable(tcx, span, def_id);
455 check_transparent(tcx, span, def);
456 check_union_fields(tcx, span, def_id);
457 check_packed(tcx, span, def);
460 /// Check that the fields of the `union` do not need dropping.
461 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
462 let item_type = tcx.type_of(item_def_id);
463 if let ty::Adt(def, substs) = item_type.kind() {
464 assert!(def.is_union());
465 let fields = &def.non_enum_variant().fields;
466 let param_env = tcx.param_env(item_def_id);
467 for field in fields {
468 let field_ty = field.ty(tcx, substs);
469 // We are currently checking the type this field came from, so it must be local.
470 let field_span = tcx.hir().span_if_local(field.did).unwrap();
471 if field_ty.needs_drop(tcx, param_env) {
476 "unions may not contain fields that need dropping"
478 .span_note(field_span, "`std::mem::ManuallyDrop` can be used to wrap the type")
484 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
489 /// Check that a `static` is inhabited.
490 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
491 // Make sure statics are inhabited.
492 // Other parts of the compiler assume that there are no uninhabited places. In principle it
493 // would be enough to check this for `extern` statics, as statics with an initializer will
494 // have UB during initialization if they are uninhabited, but there also seems to be no good
495 // reason to allow any statics to be uninhabited.
496 let ty = tcx.type_of(def_id);
497 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
500 // Generic statics are rejected, but we still reach this case.
501 tcx.sess.delay_span_bug(span, "generic static must be rejected");
505 if layout.abi.is_uninhabited() {
506 tcx.struct_span_lint_hir(
508 tcx.hir().local_def_id_to_hir_id(def_id),
511 lint.build("static of uninhabited type")
512 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
519 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
520 /// projections that would result in "inheriting lifetimes".
521 pub(super) fn check_opaque<'tcx>(
524 substs: SubstsRef<'tcx>,
526 origin: &hir::OpaqueTyOrigin,
528 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
529 if tcx.type_of(def_id).references_error() {
532 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
535 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
538 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
539 /// in "inheriting lifetimes".
540 #[instrument(level = "debug", skip(tcx, span))]
541 pub(super) fn check_opaque_for_inheriting_lifetimes(
546 let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(def_id));
547 debug!(?item, ?span);
549 struct FoundParentLifetime;
550 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
551 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
552 type BreakTy = FoundParentLifetime;
554 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
555 debug!("FindParentLifetimeVisitor: r={:?}", r);
556 if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r {
557 if *index < self.0.parent_count as u32 {
558 return ControlFlow::Break(FoundParentLifetime);
560 return ControlFlow::CONTINUE;
564 r.super_visit_with(self)
567 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
568 if let ty::ConstKind::Unevaluated(..) = c.val {
569 // FIXME(#72219) We currently don't detect lifetimes within substs
570 // which would violate this check. Even though the particular substitution is not used
571 // within the const, this should still be fixed.
572 return ControlFlow::CONTINUE;
574 c.super_visit_with(self)
578 struct ProhibitOpaqueVisitor<'tcx> {
579 opaque_identity_ty: Ty<'tcx>,
580 generics: &'tcx ty::Generics,
582 selftys: Vec<(Span, Option<String>)>,
585 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
586 type BreakTy = Ty<'tcx>;
588 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
589 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
590 if t == self.opaque_identity_ty {
591 ControlFlow::CONTINUE
593 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
594 .map_break(|FoundParentLifetime| t)
599 impl Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
600 type Map = rustc_middle::hir::map::Map<'tcx>;
602 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
603 hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
606 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
608 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
609 [PathSegment { res: Some(Res::SelfTy(_, impl_ref)), .. }] => {
611 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
612 self.selftys.push((path.span, impl_ty_name));
618 hir::intravisit::walk_ty(self, arg);
622 if let ItemKind::OpaqueTy(hir::OpaqueTy {
623 origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
627 let mut visitor = ProhibitOpaqueVisitor {
628 opaque_identity_ty: tcx.mk_opaque(
630 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
632 generics: tcx.generics_of(def_id),
636 let prohibit_opaque = tcx
637 .explicit_item_bounds(def_id)
639 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
641 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
642 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
645 if let Some(ty) = prohibit_opaque.break_value() {
646 visitor.visit_item(&item);
647 let is_async = match item.kind {
648 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
649 matches!(origin, hir::OpaqueTyOrigin::AsyncFn)
654 let mut err = struct_span_err!(
658 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
660 if is_async { "async fn" } else { "impl Trait" },
663 for (span, name) in visitor.selftys {
666 "consider spelling out the type instead",
667 name.unwrap_or_else(|| format!("{:?}", ty)),
668 Applicability::MaybeIncorrect,
676 /// Checks that an opaque type does not contain cycles.
677 pub(super) fn check_opaque_for_cycles<'tcx>(
680 substs: SubstsRef<'tcx>,
682 origin: &hir::OpaqueTyOrigin,
683 ) -> Result<(), ErrorReported> {
684 if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
687 hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
688 hir::OpaqueTyOrigin::Binding => {
689 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
691 _ => opaque_type_cycle_error(tcx, def_id, span),
699 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
701 /// This is mostly checked at the places that specify the opaque type, but we
702 /// check those cases in the `param_env` of that function, which may have
703 /// bounds not on this opaque type:
705 /// type X<T> = impl Clone
706 /// fn f<T: Clone>(t: T) -> X<T> {
710 /// Without this check the above code is incorrectly accepted: we would ICE if
711 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
712 fn check_opaque_meets_bounds<'tcx>(
715 substs: SubstsRef<'tcx>,
717 origin: &hir::OpaqueTyOrigin,
720 // Checked when type checking the function containing them.
721 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => return,
722 // Can have different predicates to their defining use
723 hir::OpaqueTyOrigin::Binding | hir::OpaqueTyOrigin::Misc | hir::OpaqueTyOrigin::TyAlias => {
727 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
728 let param_env = tcx.param_env(def_id);
730 tcx.infer_ctxt().enter(move |infcx| {
731 let inh = Inherited::new(infcx, def_id);
732 let infcx = &inh.infcx;
733 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
735 let misc_cause = traits::ObligationCause::misc(span, hir_id);
737 let (_, opaque_type_map) = inh.register_infer_ok_obligations(
738 infcx.instantiate_opaque_types(def_id, hir_id, param_env, opaque_ty, span),
741 for (def_id, opaque_defn) in opaque_type_map {
743 .at(&misc_cause, param_env)
744 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, opaque_defn.substs))
746 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
747 Err(ty_err) => tcx.sess.delay_span_bug(
748 opaque_defn.definition_span,
750 "could not unify `{}` with revealed type:\n{}",
751 opaque_defn.concrete_ty, ty_err,
757 // Check that all obligations are satisfied by the implementation's
759 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
760 infcx.report_fulfillment_errors(errors, None, false);
763 // Finally, resolve all regions. This catches wily misuses of
764 // lifetime parameters.
765 let fcx = FnCtxt::new(&inh, param_env, hir_id);
766 fcx.regionck_item(hir_id, span, &[]);
770 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
772 "check_item_type(it.def_id={:?}, it.name={})",
774 tcx.def_path_str(it.def_id.to_def_id())
776 let _indenter = indenter();
778 // Consts can play a role in type-checking, so they are included here.
779 hir::ItemKind::Static(..) => {
780 tcx.ensure().typeck(it.def_id);
781 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
782 check_static_inhabited(tcx, it.def_id, it.span);
784 hir::ItemKind::Const(..) => {
785 tcx.ensure().typeck(it.def_id);
787 hir::ItemKind::Enum(ref enum_definition, _) => {
788 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
790 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
791 hir::ItemKind::Impl(ref impl_) => {
792 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
793 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
794 check_impl_items_against_trait(
801 let trait_def_id = impl_trait_ref.def_id;
802 check_on_unimplemented(tcx, trait_def_id, it);
805 hir::ItemKind::Trait(_, _, _, _, ref items) => {
806 check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
808 for item in items.iter() {
809 let item = tcx.hir().trait_item(item.id);
811 hir::TraitItemKind::Fn(ref sig, _) => {
812 let abi = sig.header.abi;
813 fn_maybe_err(tcx, item.ident.span, abi);
815 hir::TraitItemKind::Type(.., Some(_default)) => {
816 let assoc_item = tcx.associated_item(item.def_id);
818 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
819 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
824 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
831 hir::ItemKind::Struct(..) => {
832 check_struct(tcx, it.def_id, it.span);
834 hir::ItemKind::Union(..) => {
835 check_union(tcx, it.def_id, it.span);
837 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
838 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
839 // `async-std` (and `pub async fn` in general).
840 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
841 // See https://github.com/rust-lang/rust/issues/75100
842 if !tcx.sess.opts.actually_rustdoc {
843 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
844 check_opaque(tcx, it.def_id, substs, it.span, &origin);
847 hir::ItemKind::TyAlias(..) => {
848 let pty_ty = tcx.type_of(it.def_id);
849 let generics = tcx.generics_of(it.def_id);
850 check_type_params_are_used(tcx, &generics, pty_ty);
852 hir::ItemKind::ForeignMod { abi, items } => {
853 check_abi(tcx, it.span, abi);
855 if abi == Abi::RustIntrinsic {
857 let item = tcx.hir().foreign_item(item.id);
858 intrinsic::check_intrinsic_type(tcx, item);
860 } else if abi == Abi::PlatformIntrinsic {
862 let item = tcx.hir().foreign_item(item.id);
863 intrinsic::check_platform_intrinsic_type(tcx, item);
867 let def_id = item.id.def_id;
868 let generics = tcx.generics_of(def_id);
869 let own_counts = generics.own_counts();
870 if generics.params.len() - own_counts.lifetimes != 0 {
871 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
872 (_, 0) => ("type", "types", Some("u32")),
873 // We don't specify an example value, because we can't generate
874 // a valid value for any type.
875 (0, _) => ("const", "consts", None),
876 _ => ("type or const", "types or consts", None),
882 "foreign items may not have {} parameters",
885 .span_label(item.span, &format!("can't have {} parameters", kinds))
887 // FIXME: once we start storing spans for type arguments, turn this
888 // into a suggestion.
890 "replace the {} parameters with concrete {}{}",
893 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
899 let item = tcx.hir().foreign_item(item.id);
901 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
902 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
904 hir::ForeignItemKind::Static(..) => {
905 check_static_inhabited(tcx, def_id, item.span);
912 _ => { /* nothing to do */ }
916 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
917 // an error would be reported if this fails.
918 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
921 pub(super) fn check_specialization_validity<'tcx>(
923 trait_def: &ty::TraitDef,
924 trait_item: &ty::AssocItem,
926 impl_item: &hir::ImplItem<'_>,
928 let kind = match impl_item.kind {
929 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
930 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
931 hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
934 let ancestors = match trait_def.ancestors(tcx, impl_id) {
935 Ok(ancestors) => ancestors,
938 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
939 if parent.is_from_trait() {
942 Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
946 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
948 // Parent impl exists, and contains the parent item we're trying to specialize, but
949 // doesn't mark it `default`.
950 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
951 Some(Err(parent_impl.def_id()))
954 // Parent impl contains item and makes it specializable.
955 Some(_) => Some(Ok(())),
957 // Parent impl doesn't mention the item. This means it's inherited from the
958 // grandparent. In that case, if parent is a `default impl`, inherited items use the
959 // "defaultness" from the grandparent, else they are final.
961 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
964 Some(Err(parent_impl.def_id()))
970 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
971 // item. This is allowed, the item isn't actually getting specialized here.
972 let result = opt_result.unwrap_or(Ok(()));
974 if let Err(parent_impl) = result {
975 report_forbidden_specialization(tcx, impl_item, parent_impl);
979 pub(super) fn check_impl_items_against_trait<'tcx>(
981 full_impl_span: Span,
983 impl_trait_ref: ty::TraitRef<'tcx>,
984 impl_item_refs: &[hir::ImplItemRef<'_>],
986 // If the trait reference itself is erroneous (so the compilation is going
987 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
988 // isn't populated for such impls.
989 if impl_trait_ref.references_error() {
993 // Negative impls are not expected to have any items
994 match tcx.impl_polarity(impl_id) {
995 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
996 ty::ImplPolarity::Negative => {
997 if let [first_item_ref, ..] = impl_item_refs {
998 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
1003 "negative impls cannot have any items"
1011 // Locate trait definition and items
1012 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1013 let impl_items = impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
1014 let associated_items = tcx.associated_items(impl_trait_ref.def_id);
1016 // Check existing impl methods to see if they are both present in trait
1017 // and compatible with trait signature
1018 for impl_item in impl_items {
1019 let ty_impl_item = tcx.associated_item(impl_item.def_id);
1022 associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id);
1024 let (compatible_kind, ty_trait_item) = if let Some(ty_trait_item) = items.next() {
1025 let is_compatible = |ty: &&ty::AssocItem| match (ty.kind, &impl_item.kind) {
1026 (ty::AssocKind::Const, hir::ImplItemKind::Const(..)) => true,
1027 (ty::AssocKind::Fn, hir::ImplItemKind::Fn(..)) => true,
1028 (ty::AssocKind::Type, hir::ImplItemKind::TyAlias(..)) => true,
1032 // If we don't have a compatible item, we'll use the first one whose name matches
1033 // to report an error.
1034 let mut compatible_kind = is_compatible(&ty_trait_item);
1035 let mut trait_item = ty_trait_item;
1037 if !compatible_kind {
1038 if let Some(ty_trait_item) = items.find(is_compatible) {
1039 compatible_kind = true;
1040 trait_item = ty_trait_item;
1044 (compatible_kind, trait_item)
1049 if compatible_kind {
1050 match impl_item.kind {
1051 hir::ImplItemKind::Const(..) => {
1052 // Find associated const definition.
1061 hir::ImplItemKind::Fn(..) => {
1062 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1063 compare_impl_method(
1072 hir::ImplItemKind::TyAlias(_) => {
1073 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1085 check_specialization_validity(
1089 impl_id.to_def_id(),
1093 report_mismatch_error(
1095 ty_trait_item.def_id,
1103 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1104 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1106 // Check for missing items from trait
1107 let mut missing_items = Vec::new();
1108 for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
1109 let is_implemented = ancestors
1110 .leaf_def(tcx, trait_item.ident, trait_item.kind)
1111 .map(|node_item| !node_item.defining_node.is_from_trait())
1114 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1115 if !trait_item.defaultness.has_value() {
1116 missing_items.push(*trait_item);
1121 if !missing_items.is_empty() {
1122 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1129 fn report_mismatch_error<'tcx>(
1131 trait_item_def_id: DefId,
1132 impl_trait_ref: ty::TraitRef<'tcx>,
1133 impl_item: &hir::ImplItem<'_>,
1134 ty_impl_item: &ty::AssocItem,
1136 let mut err = match impl_item.kind {
1137 hir::ImplItemKind::Const(..) => {
1138 // Find associated const definition.
1143 "item `{}` is an associated const, which doesn't match its trait `{}`",
1145 impl_trait_ref.print_only_trait_path()
1149 hir::ImplItemKind::Fn(..) => {
1154 "item `{}` is an associated method, which doesn't match its trait `{}`",
1156 impl_trait_ref.print_only_trait_path()
1160 hir::ImplItemKind::TyAlias(_) => {
1165 "item `{}` is an associated type, which doesn't match its trait `{}`",
1167 impl_trait_ref.print_only_trait_path()
1172 err.span_label(impl_item.span, "does not match trait");
1173 if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) {
1174 err.span_label(trait_span, "item in trait");
1179 /// Checks whether a type can be represented in memory. In particular, it
1180 /// identifies types that contain themselves without indirection through a
1181 /// pointer, which would mean their size is unbounded.
1182 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1183 let rty = tcx.type_of(item_def_id);
1185 // Check that it is possible to represent this type. This call identifies
1186 // (1) types that contain themselves and (2) types that contain a different
1187 // recursive type. It is only necessary to throw an error on those that
1188 // contain themselves. For case 2, there must be an inner type that will be
1189 // caught by case 1.
1190 match rty.is_representable(tcx, sp) {
1191 Representability::SelfRecursive(spans) => {
1192 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1195 Representability::Representable | Representability::ContainsRecursive => (),
1200 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1201 let t = tcx.type_of(def_id);
1202 if let ty::Adt(def, substs) = t.kind() {
1203 if def.is_struct() {
1204 let fields = &def.non_enum_variant().fields;
1205 if fields.is_empty() {
1206 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1209 let e = fields[0].ty(tcx, substs);
1210 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1211 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1212 .span_label(sp, "SIMD elements must have the same type")
1217 let len = if let ty::Array(_ty, c) = e.kind() {
1218 c.try_eval_usize(tcx, tcx.param_env(def.did))
1220 Some(fields.len() as u64)
1222 if let Some(len) = len {
1224 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1226 } else if len > MAX_SIMD_LANES {
1231 "SIMD vector cannot have more than {} elements",
1240 ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ }
1241 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1242 ty::Array(ty, _c) if ty.is_machine() => { /* struct([f32; 4]) */ }
1248 "SIMD vector element type should be a \
1249 primitive scalar (integer/float/pointer) type"
1259 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1260 let repr = def.repr;
1262 for attr in tcx.get_attrs(def.did).iter() {
1263 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1264 if let attr::ReprPacked(pack) = r {
1265 if let Some(repr_pack) = repr.pack {
1266 if pack as u64 != repr_pack.bytes() {
1271 "type has conflicting packed representation hints"
1279 if repr.align.is_some() {
1284 "type has conflicting packed and align representation hints"
1288 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1289 let mut err = struct_span_err!(
1293 "packed type cannot transitively contain a `#[repr(align)]` type"
1297 tcx.def_span(def_spans[0].0),
1299 "`{}` has a `#[repr(align)]` attribute",
1300 tcx.item_name(def_spans[0].0)
1304 if def_spans.len() > 2 {
1305 let mut first = true;
1306 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1307 let ident = tcx.item_name(*adt_def);
1312 "`{}` contains a field of type `{}`",
1313 tcx.type_of(def.did),
1317 format!("...which contains a field of type `{}`", ident)
1330 pub(super) fn check_packed_inner(
1333 stack: &mut Vec<DefId>,
1334 ) -> Option<Vec<(DefId, Span)>> {
1335 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1336 if def.is_struct() || def.is_union() {
1337 if def.repr.align.is_some() {
1338 return Some(vec![(def.did, DUMMY_SP)]);
1342 for field in &def.non_enum_variant().fields {
1343 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1344 if !stack.contains(&def.did) {
1345 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1346 defs.push((def.did, field.ident.span));
1359 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1360 if !adt.repr.transparent() {
1363 let sp = tcx.sess.source_map().guess_head_span(sp);
1365 if adt.is_union() && !tcx.features().transparent_unions {
1367 &tcx.sess.parse_sess,
1368 sym::transparent_unions,
1370 "transparent unions are unstable",
1375 if adt.variants.len() != 1 {
1376 bad_variant_count(tcx, adt, sp, adt.did);
1377 if adt.variants.is_empty() {
1378 // Don't bother checking the fields. No variants (and thus no fields) exist.
1383 // For each field, figure out if it's known to be a ZST and align(1)
1384 let field_infos = adt.all_fields().map(|field| {
1385 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1386 let param_env = tcx.param_env(field.did);
1387 let layout = tcx.layout_of(param_env.and(ty));
1388 // We are currently checking the type this field came from, so it must be local
1389 let span = tcx.hir().span_if_local(field.did).unwrap();
1390 let zst = layout.map_or(false, |layout| layout.is_zst());
1391 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1395 let non_zst_fields =
1396 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1397 let non_zst_count = non_zst_fields.clone().count();
1398 if non_zst_count != 1 {
1399 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1401 for (span, zst, align1) in field_infos {
1407 "zero-sized field in transparent {} has alignment larger than 1",
1410 .span_label(span, "has alignment larger than 1")
1416 #[allow(trivial_numeric_casts)]
1417 fn check_enum<'tcx>(
1420 vs: &'tcx [hir::Variant<'tcx>],
1423 let def = tcx.adt_def(def_id);
1424 def.destructor(tcx); // force the destructor to be evaluated
1427 let attributes = tcx.get_attrs(def_id.to_def_id());
1428 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1433 "unsupported representation for zero-variant enum"
1435 .span_label(sp, "zero-variant enum")
1440 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1441 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1442 if !tcx.features().repr128 {
1444 &tcx.sess.parse_sess,
1447 "repr with 128-bit type is unstable",
1454 if let Some(ref e) = v.disr_expr {
1455 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1459 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1460 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1462 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1463 let has_non_units = vs.iter().any(|var| !is_unit(var));
1464 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1465 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1467 if disr_non_unit || (disr_units && has_non_units) {
1469 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1474 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1475 for ((_, discr), v) in def.discriminants(tcx).zip(vs) {
1476 // Check for duplicate discriminant values
1477 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1478 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1479 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1480 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1481 let i_span = match variant_i.disr_expr {
1482 Some(ref expr) => tcx.hir().span(expr.hir_id),
1483 None => tcx.hir().span(variant_i_hir_id),
1485 let span = match v.disr_expr {
1486 Some(ref expr) => tcx.hir().span(expr.hir_id),
1493 "discriminant value `{}` already exists",
1496 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1497 .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1500 disr_vals.push(discr);
1503 check_representable(tcx, sp, def_id);
1504 check_transparent(tcx, sp, def);
1507 pub(super) fn check_type_params_are_used<'tcx>(
1509 generics: &ty::Generics,
1512 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1514 assert_eq!(generics.parent, None);
1516 if generics.own_counts().types == 0 {
1520 let mut params_used = BitSet::new_empty(generics.params.len());
1522 if ty.references_error() {
1523 // If there is already another error, do not emit
1524 // an error for not using a type parameter.
1525 assert!(tcx.sess.has_errors());
1529 for leaf in ty.walk() {
1530 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1531 if let ty::Param(param) = leaf_ty.kind() {
1532 debug!("found use of ty param {:?}", param);
1533 params_used.insert(param.index);
1538 for param in &generics.params {
1539 if !params_used.contains(param.index) {
1540 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1541 let span = tcx.def_span(param.def_id);
1546 "type parameter `{}` is unused",
1549 .span_label(span, "unused type parameter")
1556 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1557 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1560 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1561 wfcheck::check_item_well_formed(tcx, def_id);
1564 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1565 wfcheck::check_trait_item(tcx, def_id);
1568 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1569 wfcheck::check_impl_item(tcx, def_id);
1572 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1573 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1574 .span_label(span, "recursive `async fn`")
1575 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1577 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1582 /// Emit an error for recursive opaque types.
1584 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1585 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1588 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1589 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1590 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1591 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1593 let mut label = false;
1594 if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1595 let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1599 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1600 .all(|ty| matches!(ty.kind(), ty::Never))
1605 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1606 .map(|expr| expr.span)
1607 .collect::<Vec<Span>>();
1608 let span_len = spans.len();
1610 err.span_label(spans[0], "this returned value is of `!` type");
1612 let mut multispan: MultiSpan = spans.clone().into();
1615 .push_span_label(span, "this returned value is of `!` type".to_string());
1617 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1619 err.help("this error will resolve once the item's body returns a concrete type");
1621 let mut seen = FxHashSet::default();
1623 err.span_label(span, "recursive opaque type");
1625 for (sp, ty) in visitor
1628 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1629 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1631 struct VisitTypes(Vec<DefId>);
1632 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1633 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1635 ty::Opaque(def, _) => {
1637 ControlFlow::CONTINUE
1639 _ => t.super_visit_with(self),
1643 let mut visitor = VisitTypes(vec![]);
1644 ty.visit_with(&mut visitor);
1645 for def_id in visitor.0 {
1646 let ty_span = tcx.def_span(def_id);
1647 if !seen.contains(&ty_span) {
1648 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1649 seen.insert(ty_span);
1651 err.span_label(sp, &format!("returning here with type `{}`", ty));
1657 err.span_label(span, "cannot resolve opaque type");