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::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};
19 use rustc_middle::ty::{self, OpaqueTypeKey, ParamEnv, RegionKind, Ty, TyCtxt};
20 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
21 use rustc_span::symbol::sym;
22 use rustc_span::{self, MultiSpan, Span};
23 use rustc_target::spec::abi::Abi;
24 use rustc_trait_selection::opaque_types::InferCtxtExt as _;
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().krate().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) {
40 Some(false) => struct_span_err!(
44 "`{}` is not a supported ABI for the current target",
49 tcx.struct_span_lint_hir(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
50 lint.build("use of calling convention not supported on this target").emit()
55 // This ABI is only allowed on function pointers
56 if abi == Abi::CCmseNonSecureCall {
61 "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers."
67 /// Helper used for fns and closures. Does the grungy work of checking a function
68 /// body and returns the function context used for that purpose, since in the case of a fn item
69 /// there is still a bit more to do.
72 /// * inherited: other fields inherited from the enclosing fn (if any)
73 pub(super) fn check_fn<'a, 'tcx>(
74 inherited: &'a Inherited<'a, 'tcx>,
75 param_env: ty::ParamEnv<'tcx>,
76 fn_sig: ty::FnSig<'tcx>,
77 decl: &'tcx hir::FnDecl<'tcx>,
79 body: &'tcx hir::Body<'tcx>,
80 can_be_generator: Option<hir::Movability>,
81 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
82 let mut fn_sig = fn_sig;
84 debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env);
86 // Create the function context. This is either derived from scratch or,
87 // in the case of closures, based on the outer context.
88 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
89 fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
95 let declared_ret_ty = fn_sig.output();
97 let feature = match tcx.hir().get(fn_id) {
98 // TAIT usage in function return position.
102 // type Foo = impl Debug;
103 // fn bar() -> Foo { 42 }
105 Node::Item(hir::Item { kind: ItemKind::Fn(..), .. }) |
106 // TAIT usage in associated function return position.
108 // Example with a free type alias:
111 // type Foo = impl Debug;
112 // impl SomeTrait for SomeType {
113 // fn bar() -> Foo { 42 }
117 // Example with an associated TAIT:
120 // impl SomeTrait for SomeType {
121 // type Foo = impl Debug;
122 // fn bar() -> Self::Foo { 42 }
125 Node::ImplItem(hir::ImplItem {
126 kind: hir::ImplItemKind::Fn(..), ..
128 // Forbid TAIT in trait declarations for now.
132 // type Foo = impl Debug;
137 // type Bop: PartialEq<Foo>;
140 Node::TraitItem(hir::TraitItem {
141 kind: hir::TraitItemKind::Fn(..),
144 // Forbid TAIT in closure return position for now.
148 // type Foo = impl Debug;
149 // let x = |y| -> Foo { 42 + y };
151 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => Some(sym::type_alias_impl_trait),
152 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
154 let revealed_ret_ty = fcx.instantiate_opaque_types_from_value(
160 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
161 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
162 fcx.ret_type_span = Some(decl.output.span());
163 if let ty::Opaque(..) = declared_ret_ty.kind() {
164 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
166 fn_sig = tcx.mk_fn_sig(
167 fn_sig.inputs().iter().cloned(),
174 let span = body.value.span;
176 fn_maybe_err(tcx, span, fn_sig.abi);
178 if fn_sig.abi == Abi::RustCall {
179 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
182 let item = match tcx.hir().get(fn_id) {
183 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
184 Node::ImplItem(hir::ImplItem {
185 kind: hir::ImplItemKind::Fn(header, ..), ..
187 Node::TraitItem(hir::TraitItem {
188 kind: hir::TraitItemKind::Fn(header, ..),
191 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
192 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
193 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
196 if let Some(header) = item {
197 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple")
201 if fn_sig.inputs().len() != expected_args {
204 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
205 // This will probably require wide-scale changes to support a TupleKind obligation
206 // We can't resolve this without knowing the type of the param
207 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
213 if body.generator_kind.is_some() && can_be_generator.is_some() {
215 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
216 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
218 // Resume type defaults to `()` if the generator has no argument.
219 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
221 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
224 let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id).to_def_id()).expect_local();
225 let outer_hir_id = hir.local_def_id_to_hir_id(outer_def_id);
226 GatherLocalsVisitor::new(&fcx, outer_hir_id).visit_body(body);
228 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
229 // (as it's created inside the body itself, not passed in from outside).
230 let maybe_va_list = if fn_sig.c_variadic {
231 let span = body.params.last().unwrap().span;
232 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
233 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
235 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
240 // Add formal parameters.
241 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
242 let inputs_fn = fn_sig.inputs().iter().copied();
243 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
244 // Check the pattern.
245 let ty_span = try { inputs_hir?.get(idx)?.span };
246 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
248 // Check that argument is Sized.
249 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
250 // for simple cases like `fn foo(x: Trait)`,
251 // where we would error once on the parameter as a whole, and once on the binding `x`.
252 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
253 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
256 fcx.write_ty(param.hir_id, param_ty);
259 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
261 fcx.in_tail_expr = true;
262 if let ty::Dynamic(..) = declared_ret_ty.kind() {
263 // FIXME: We need to verify that the return type is `Sized` after the return expression has
264 // been evaluated so that we have types available for all the nodes being returned, but that
265 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
266 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
267 // while keeping the current ordering we will ignore the tail expression's type because we
268 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
269 // because we will trigger "unreachable expression" lints unconditionally.
270 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
271 // case that a newcomer might make, returning a bare trait, and in that case we populate
272 // the tail expression's type so that the suggestion will be correct, but ignore all other
274 fcx.check_expr(&body.value);
275 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
277 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
278 fcx.check_return_expr(&body.value);
280 fcx.in_tail_expr = false;
282 // We insert the deferred_generator_interiors entry after visiting the body.
283 // This ensures that all nested generators appear before the entry of this generator.
284 // resolve_generator_interiors relies on this property.
285 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
287 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
288 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
290 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
291 Some(GeneratorTypes {
295 movability: can_be_generator.unwrap(),
301 // Finalize the return check by taking the LUB of the return types
302 // we saw and assigning it to the expected return type. This isn't
303 // really expected to fail, since the coercions would have failed
304 // earlier when trying to find a LUB.
306 // However, the behavior around `!` is sort of complex. In the
307 // event that the `actual_return_ty` comes back as `!`, that
308 // indicates that the fn either does not return or "returns" only
309 // values of type `!`. In this case, if there is an expected
310 // return type that is *not* `!`, that should be ok. But if the
311 // return type is being inferred, we want to "fallback" to `!`:
313 // let x = move || panic!();
315 // To allow for that, I am creating a type variable with diverging
316 // fallback. This was deemed ever so slightly better than unifying
317 // the return value with `!` because it allows for the caller to
318 // make more assumptions about the return type (e.g., they could do
320 // let y: Option<u32> = Some(x());
322 // which would then cause this return type to become `u32`, not
324 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
325 let mut actual_return_ty = coercion.complete(&fcx);
326 if actual_return_ty.is_never() {
327 actual_return_ty = fcx.next_diverging_ty_var(TypeVariableOrigin {
328 kind: TypeVariableOriginKind::DivergingFn,
332 fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty);
334 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
335 if let Some(panic_impl_did) = tcx.lang_items().panic_impl() {
336 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
337 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
338 if *declared_ret_ty.kind() != ty::Never {
339 sess.span_err(decl.output.span(), "return type should be `!`");
342 let inputs = fn_sig.inputs();
343 let span = hir.span(fn_id);
344 if inputs.len() == 1 {
345 let arg_is_panic_info = match *inputs[0].kind() {
346 ty::Ref(region, ty, mutbl) => match *ty.kind() {
347 ty::Adt(ref adt, _) => {
348 adt.did == panic_info_did
349 && mutbl == hir::Mutability::Not
350 && *region != RegionKind::ReStatic
357 if !arg_is_panic_info {
358 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
361 if let Node::Item(item) = hir.get(fn_id) {
362 if let ItemKind::Fn(_, ref generics, _) = item.kind {
363 if !generics.params.is_empty() {
364 sess.span_err(span, "should have no type parameters");
369 let span = sess.source_map().guess_head_span(span);
370 sess.span_err(span, "function should have one argument");
373 sess.err("language item required, but not found: `panic_info`");
378 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
379 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
380 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
381 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
382 if *declared_ret_ty.kind() != ty::Never {
383 sess.span_err(decl.output.span(), "return type should be `!`");
386 let inputs = fn_sig.inputs();
387 let span = hir.span(fn_id);
388 if inputs.len() == 1 {
389 let arg_is_alloc_layout = match inputs[0].kind() {
390 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
394 if !arg_is_alloc_layout {
395 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
398 if let Node::Item(item) = hir.get(fn_id) {
399 if let ItemKind::Fn(_, ref generics, _) = item.kind {
400 if !generics.params.is_empty() {
403 "`#[alloc_error_handler]` function should have no type \
410 let span = sess.source_map().guess_head_span(span);
411 sess.span_err(span, "function should have one argument");
414 sess.err("language item required, but not found: `alloc_layout`");
422 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
423 let def = tcx.adt_def(def_id);
424 def.destructor(tcx); // force the destructor to be evaluated
425 check_representable(tcx, span, def_id);
428 check_simd(tcx, span, def_id);
431 check_transparent(tcx, span, def);
432 check_packed(tcx, span, def);
435 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
436 let def = tcx.adt_def(def_id);
437 def.destructor(tcx); // force the destructor to be evaluated
438 check_representable(tcx, span, def_id);
439 check_transparent(tcx, span, def);
440 check_union_fields(tcx, span, def_id);
441 check_packed(tcx, span, def);
444 /// Check that the fields of the `union` do not need dropping.
445 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
446 let item_type = tcx.type_of(item_def_id);
447 if let ty::Adt(def, substs) = item_type.kind() {
448 assert!(def.is_union());
449 let fields = &def.non_enum_variant().fields;
450 let param_env = tcx.param_env(item_def_id);
451 for field in fields {
452 let field_ty = field.ty(tcx, substs);
453 // We are currently checking the type this field came from, so it must be local.
454 let field_span = tcx.hir().span_if_local(field.did).unwrap();
455 if field_ty.needs_drop(tcx, param_env) {
460 "unions may not contain fields that need dropping"
462 .span_note(field_span, "`std::mem::ManuallyDrop` can be used to wrap the type")
468 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
473 /// Check that a `static` is inhabited.
474 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
475 // Make sure statics are inhabited.
476 // Other parts of the compiler assume that there are no uninhabited places. In principle it
477 // would be enough to check this for `extern` statics, as statics with an initializer will
478 // have UB during initialization if they are uninhabited, but there also seems to be no good
479 // reason to allow any statics to be uninhabited.
480 let ty = tcx.type_of(def_id);
481 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
484 // Generic statics are rejected, but we still reach this case.
485 tcx.sess.delay_span_bug(span, "generic static must be rejected");
489 if layout.abi.is_uninhabited() {
490 tcx.struct_span_lint_hir(
492 tcx.hir().local_def_id_to_hir_id(def_id),
495 lint.build("static of uninhabited type")
496 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
503 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
504 /// projections that would result in "inheriting lifetimes".
505 pub(super) fn check_opaque<'tcx>(
508 substs: SubstsRef<'tcx>,
510 origin: &hir::OpaqueTyOrigin,
512 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
513 if tcx.type_of(def_id).references_error() {
516 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
519 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
522 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
523 /// in "inheriting lifetimes".
524 #[instrument(level = "debug", skip(tcx, span))]
525 pub(super) fn check_opaque_for_inheriting_lifetimes(
530 let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(def_id));
531 debug!(?item, ?span);
533 struct FoundParentLifetime;
534 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
535 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
536 type BreakTy = FoundParentLifetime;
538 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
539 debug!("FindParentLifetimeVisitor: r={:?}", r);
540 if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r {
541 if *index < self.0.parent_count as u32 {
542 return ControlFlow::Break(FoundParentLifetime);
544 return ControlFlow::CONTINUE;
548 r.super_visit_with(self)
551 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
552 if let ty::ConstKind::Unevaluated(..) = c.val {
553 // FIXME(#72219) We currently don't detect lifetimes within substs
554 // which would violate this check. Even though the particular substitution is not used
555 // within the const, this should still be fixed.
556 return ControlFlow::CONTINUE;
558 c.super_visit_with(self)
562 struct ProhibitOpaqueVisitor<'tcx> {
563 opaque_identity_ty: Ty<'tcx>,
564 generics: &'tcx ty::Generics,
566 selftys: Vec<(Span, Option<String>)>,
569 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
570 type BreakTy = Ty<'tcx>;
572 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
573 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
574 if t == self.opaque_identity_ty {
575 ControlFlow::CONTINUE
577 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
578 .map_break(|FoundParentLifetime| t)
583 impl Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
584 type Map = rustc_middle::hir::map::Map<'tcx>;
586 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
587 hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
590 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
592 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
593 [PathSegment { res: Some(Res::SelfTy(_, impl_ref)), .. }] => {
595 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
596 self.selftys.push((path.span, impl_ty_name));
602 hir::intravisit::walk_ty(self, arg);
606 if let ItemKind::OpaqueTy(hir::OpaqueTy {
607 origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
611 let mut visitor = ProhibitOpaqueVisitor {
612 opaque_identity_ty: tcx.mk_opaque(
614 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
616 generics: tcx.generics_of(def_id),
620 let prohibit_opaque = tcx
621 .explicit_item_bounds(def_id)
623 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
625 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
626 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
629 if let Some(ty) = prohibit_opaque.break_value() {
630 visitor.visit_item(&item);
631 let is_async = match item.kind {
632 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
633 matches!(origin, hir::OpaqueTyOrigin::AsyncFn)
638 let mut err = struct_span_err!(
642 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
644 if is_async { "async fn" } else { "impl Trait" },
647 for (span, name) in visitor.selftys {
650 "consider spelling out the type instead",
651 name.unwrap_or_else(|| format!("{:?}", ty)),
652 Applicability::MaybeIncorrect,
660 /// Checks that an opaque type does not contain cycles.
661 pub(super) fn check_opaque_for_cycles<'tcx>(
664 substs: SubstsRef<'tcx>,
666 origin: &hir::OpaqueTyOrigin,
667 ) -> Result<(), ErrorReported> {
668 if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
671 hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
672 hir::OpaqueTyOrigin::Binding => {
673 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
675 _ => opaque_type_cycle_error(tcx, def_id, span),
683 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
685 /// This is mostly checked at the places that specify the opaque type, but we
686 /// check those cases in the `param_env` of that function, which may have
687 /// bounds not on this opaque type:
689 /// type X<T> = impl Clone
690 /// fn f<T: Clone>(t: T) -> X<T> {
694 /// Without this check the above code is incorrectly accepted: we would ICE if
695 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
696 fn check_opaque_meets_bounds<'tcx>(
699 substs: SubstsRef<'tcx>,
701 origin: &hir::OpaqueTyOrigin,
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::Binding | hir::OpaqueTyOrigin::Misc | hir::OpaqueTyOrigin::TyAlias => {
711 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
712 let param_env = tcx.param_env(def_id);
714 tcx.infer_ctxt().enter(move |infcx| {
715 let inh = Inherited::new(infcx, def_id);
716 let infcx = &inh.infcx;
717 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
719 let misc_cause = traits::ObligationCause::misc(span, hir_id);
721 let (_, opaque_type_map) = inh.register_infer_ok_obligations(
722 infcx.instantiate_opaque_types(def_id, hir_id, param_env, opaque_ty, span),
725 for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map {
727 .at(&misc_cause, param_env)
728 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, substs))
730 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
731 Err(ty_err) => tcx.sess.delay_span_bug(
732 opaque_defn.definition_span,
734 "could not unify `{}` with revealed type:\n{}",
735 opaque_defn.concrete_ty, ty_err,
741 // Check that all obligations are satisfied by the implementation's
743 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
744 infcx.report_fulfillment_errors(errors, None, false);
747 // Finally, resolve all regions. This catches wily misuses of
748 // lifetime parameters.
749 let fcx = FnCtxt::new(&inh, param_env, hir_id);
750 fcx.regionck_item(hir_id, span, &[]);
754 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
756 "check_item_type(it.def_id={:?}, it.name={})",
758 tcx.def_path_str(it.def_id.to_def_id())
760 let _indenter = indenter();
762 // Consts can play a role in type-checking, so they are included here.
763 hir::ItemKind::Static(..) => {
764 tcx.ensure().typeck(it.def_id);
765 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
766 check_static_inhabited(tcx, it.def_id, it.span);
768 hir::ItemKind::Const(..) => {
769 tcx.ensure().typeck(it.def_id);
771 hir::ItemKind::Enum(ref enum_definition, _) => {
772 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
774 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
775 hir::ItemKind::Impl(ref impl_) => {
776 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
777 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
778 check_impl_items_against_trait(
785 let trait_def_id = impl_trait_ref.def_id;
786 check_on_unimplemented(tcx, trait_def_id, it);
789 hir::ItemKind::Trait(_, _, _, _, ref items) => {
790 check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
792 for item in items.iter() {
793 let item = tcx.hir().trait_item(item.id);
795 hir::TraitItemKind::Fn(ref sig, _) => {
796 let abi = sig.header.abi;
797 fn_maybe_err(tcx, item.ident.span, abi);
799 hir::TraitItemKind::Type(.., Some(_default)) => {
800 let assoc_item = tcx.associated_item(item.def_id);
802 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
803 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
808 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
815 hir::ItemKind::Struct(..) => {
816 check_struct(tcx, it.def_id, it.span);
818 hir::ItemKind::Union(..) => {
819 check_union(tcx, it.def_id, it.span);
821 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
822 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
823 // `async-std` (and `pub async fn` in general).
824 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
825 // See https://github.com/rust-lang/rust/issues/75100
826 if !tcx.sess.opts.actually_rustdoc {
827 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
828 check_opaque(tcx, it.def_id, substs, it.span, &origin);
831 hir::ItemKind::TyAlias(..) => {
832 let pty_ty = tcx.type_of(it.def_id);
833 let generics = tcx.generics_of(it.def_id);
834 check_type_params_are_used(tcx, &generics, pty_ty);
836 hir::ItemKind::ForeignMod { abi, items } => {
837 check_abi(tcx, it.hir_id(), it.span, abi);
839 if abi == Abi::RustIntrinsic {
841 let item = tcx.hir().foreign_item(item.id);
842 intrinsic::check_intrinsic_type(tcx, item);
844 } else if abi == Abi::PlatformIntrinsic {
846 let item = tcx.hir().foreign_item(item.id);
847 intrinsic::check_platform_intrinsic_type(tcx, item);
851 let def_id = item.id.def_id;
852 let generics = tcx.generics_of(def_id);
853 let own_counts = generics.own_counts();
854 if generics.params.len() - own_counts.lifetimes != 0 {
855 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
856 (_, 0) => ("type", "types", Some("u32")),
857 // We don't specify an example value, because we can't generate
858 // a valid value for any type.
859 (0, _) => ("const", "consts", None),
860 _ => ("type or const", "types or consts", None),
866 "foreign items may not have {} parameters",
869 .span_label(item.span, &format!("can't have {} parameters", kinds))
871 // FIXME: once we start storing spans for type arguments, turn this
872 // into a suggestion.
874 "replace the {} parameters with concrete {}{}",
877 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
883 let item = tcx.hir().foreign_item(item.id);
885 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
886 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
888 hir::ForeignItemKind::Static(..) => {
889 check_static_inhabited(tcx, def_id, item.span);
896 _ => { /* nothing to do */ }
900 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
901 // an error would be reported if this fails.
902 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
905 pub(super) fn check_specialization_validity<'tcx>(
907 trait_def: &ty::TraitDef,
908 trait_item: &ty::AssocItem,
910 impl_item: &hir::ImplItem<'_>,
912 let kind = match impl_item.kind {
913 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
914 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
915 hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
918 let ancestors = match trait_def.ancestors(tcx, impl_id) {
919 Ok(ancestors) => ancestors,
922 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
923 if parent.is_from_trait() {
926 Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
930 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
932 // Parent impl exists, and contains the parent item we're trying to specialize, but
933 // doesn't mark it `default`.
934 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
935 Some(Err(parent_impl.def_id()))
938 // Parent impl contains item and makes it specializable.
939 Some(_) => Some(Ok(())),
941 // Parent impl doesn't mention the item. This means it's inherited from the
942 // grandparent. In that case, if parent is a `default impl`, inherited items use the
943 // "defaultness" from the grandparent, else they are final.
945 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
948 Some(Err(parent_impl.def_id()))
954 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
955 // item. This is allowed, the item isn't actually getting specialized here.
956 let result = opt_result.unwrap_or(Ok(()));
958 if let Err(parent_impl) = result {
959 report_forbidden_specialization(tcx, impl_item, parent_impl);
963 pub(super) fn check_impl_items_against_trait<'tcx>(
965 full_impl_span: Span,
967 impl_trait_ref: ty::TraitRef<'tcx>,
968 impl_item_refs: &[hir::ImplItemRef<'_>],
970 // If the trait reference itself is erroneous (so the compilation is going
971 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
972 // isn't populated for such impls.
973 if impl_trait_ref.references_error() {
977 // Negative impls are not expected to have any items
978 match tcx.impl_polarity(impl_id) {
979 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
980 ty::ImplPolarity::Negative => {
981 if let [first_item_ref, ..] = impl_item_refs {
982 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
987 "negative impls cannot have any items"
995 // Locate trait definition and items
996 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
997 let impl_items = impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
998 let associated_items = tcx.associated_items(impl_trait_ref.def_id);
1000 // Check existing impl methods to see if they are both present in trait
1001 // and compatible with trait signature
1002 for impl_item in impl_items {
1003 let ty_impl_item = tcx.associated_item(impl_item.def_id);
1006 associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id);
1008 let (compatible_kind, ty_trait_item) = if let Some(ty_trait_item) = items.next() {
1009 let is_compatible = |ty: &&ty::AssocItem| match (ty.kind, &impl_item.kind) {
1010 (ty::AssocKind::Const, hir::ImplItemKind::Const(..)) => true,
1011 (ty::AssocKind::Fn, hir::ImplItemKind::Fn(..)) => true,
1012 (ty::AssocKind::Type, hir::ImplItemKind::TyAlias(..)) => true,
1016 // If we don't have a compatible item, we'll use the first one whose name matches
1017 // to report an error.
1018 let mut compatible_kind = is_compatible(&ty_trait_item);
1019 let mut trait_item = ty_trait_item;
1021 if !compatible_kind {
1022 if let Some(ty_trait_item) = items.find(is_compatible) {
1023 compatible_kind = true;
1024 trait_item = ty_trait_item;
1028 (compatible_kind, trait_item)
1033 if compatible_kind {
1034 match impl_item.kind {
1035 hir::ImplItemKind::Const(..) => {
1036 // Find associated const definition.
1045 hir::ImplItemKind::Fn(..) => {
1046 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1047 compare_impl_method(
1056 hir::ImplItemKind::TyAlias(_) => {
1057 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1069 check_specialization_validity(
1073 impl_id.to_def_id(),
1077 report_mismatch_error(
1079 ty_trait_item.def_id,
1087 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1088 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1090 // Check for missing items from trait
1091 let mut missing_items = Vec::new();
1092 for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
1093 let is_implemented = ancestors
1094 .leaf_def(tcx, trait_item.ident, trait_item.kind)
1095 .map(|node_item| !node_item.defining_node.is_from_trait())
1098 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1099 if !trait_item.defaultness.has_value() {
1100 missing_items.push(*trait_item);
1105 if !missing_items.is_empty() {
1106 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1113 fn report_mismatch_error<'tcx>(
1115 trait_item_def_id: DefId,
1116 impl_trait_ref: ty::TraitRef<'tcx>,
1117 impl_item: &hir::ImplItem<'_>,
1118 ty_impl_item: &ty::AssocItem,
1120 let mut err = match impl_item.kind {
1121 hir::ImplItemKind::Const(..) => {
1122 // Find associated const definition.
1127 "item `{}` is an associated const, which doesn't match its trait `{}`",
1129 impl_trait_ref.print_only_trait_path()
1133 hir::ImplItemKind::Fn(..) => {
1138 "item `{}` is an associated method, which doesn't match its trait `{}`",
1140 impl_trait_ref.print_only_trait_path()
1144 hir::ImplItemKind::TyAlias(_) => {
1149 "item `{}` is an associated type, which doesn't match its trait `{}`",
1151 impl_trait_ref.print_only_trait_path()
1156 err.span_label(impl_item.span, "does not match trait");
1157 if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) {
1158 err.span_label(trait_span, "item in trait");
1163 /// Checks whether a type can be represented in memory. In particular, it
1164 /// identifies types that contain themselves without indirection through a
1165 /// pointer, which would mean their size is unbounded.
1166 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1167 let rty = tcx.type_of(item_def_id);
1169 // Check that it is possible to represent this type. This call identifies
1170 // (1) types that contain themselves and (2) types that contain a different
1171 // recursive type. It is only necessary to throw an error on those that
1172 // contain themselves. For case 2, there must be an inner type that will be
1173 // caught by case 1.
1174 match representability::ty_is_representable(tcx, rty, sp) {
1175 Representability::SelfRecursive(spans) => {
1176 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1179 Representability::Representable | Representability::ContainsRecursive => (),
1184 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1185 let t = tcx.type_of(def_id);
1186 if let ty::Adt(def, substs) = t.kind() {
1187 if def.is_struct() {
1188 let fields = &def.non_enum_variant().fields;
1189 if fields.is_empty() {
1190 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1193 let e = fields[0].ty(tcx, substs);
1194 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1195 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1196 .span_label(sp, "SIMD elements must have the same type")
1201 let len = if let ty::Array(_ty, c) = e.kind() {
1202 c.try_eval_usize(tcx, tcx.param_env(def.did))
1204 Some(fields.len() as u64)
1206 if let Some(len) = len {
1208 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1210 } else if len > MAX_SIMD_LANES {
1215 "SIMD vector cannot have more than {} elements",
1223 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1224 // These are scalar types which directly match a "machine" type
1225 // Yes: Integers, floats, "thin" pointers
1226 // No: char, "fat" pointers, compound types
1228 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1229 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1233 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1235 { /* struct([f32; 4]) is ok */ }
1241 "SIMD vector element type should be a \
1242 primitive scalar (integer/float/pointer) type"
1252 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1253 let repr = def.repr;
1255 for attr in tcx.get_attrs(def.did).iter() {
1256 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1257 if let attr::ReprPacked(pack) = r {
1258 if let Some(repr_pack) = repr.pack {
1259 if pack as u64 != repr_pack.bytes() {
1264 "type has conflicting packed representation hints"
1272 if repr.align.is_some() {
1277 "type has conflicting packed and align representation hints"
1281 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1282 let mut err = struct_span_err!(
1286 "packed type cannot transitively contain a `#[repr(align)]` type"
1290 tcx.def_span(def_spans[0].0),
1292 "`{}` has a `#[repr(align)]` attribute",
1293 tcx.item_name(def_spans[0].0)
1297 if def_spans.len() > 2 {
1298 let mut first = true;
1299 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1300 let ident = tcx.item_name(*adt_def);
1305 "`{}` contains a field of type `{}`",
1306 tcx.type_of(def.did),
1310 format!("...which contains a field of type `{}`", ident)
1323 pub(super) fn check_packed_inner(
1326 stack: &mut Vec<DefId>,
1327 ) -> Option<Vec<(DefId, Span)>> {
1328 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1329 if def.is_struct() || def.is_union() {
1330 if def.repr.align.is_some() {
1331 return Some(vec![(def.did, DUMMY_SP)]);
1335 for field in &def.non_enum_variant().fields {
1336 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1337 if !stack.contains(&def.did) {
1338 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1339 defs.push((def.did, field.ident.span));
1352 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1353 if !adt.repr.transparent() {
1356 let sp = tcx.sess.source_map().guess_head_span(sp);
1358 if adt.is_union() && !tcx.features().transparent_unions {
1360 &tcx.sess.parse_sess,
1361 sym::transparent_unions,
1363 "transparent unions are unstable",
1368 if adt.variants.len() != 1 {
1369 bad_variant_count(tcx, adt, sp, adt.did);
1370 if adt.variants.is_empty() {
1371 // Don't bother checking the fields. No variants (and thus no fields) exist.
1376 // For each field, figure out if it's known to be a ZST and align(1)
1377 let field_infos = adt.all_fields().map(|field| {
1378 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1379 let param_env = tcx.param_env(field.did);
1380 let layout = tcx.layout_of(param_env.and(ty));
1381 // We are currently checking the type this field came from, so it must be local
1382 let span = tcx.hir().span_if_local(field.did).unwrap();
1383 let zst = layout.map_or(false, |layout| layout.is_zst());
1384 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1388 let non_zst_fields =
1389 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1390 let non_zst_count = non_zst_fields.clone().count();
1391 if non_zst_count >= 2 {
1392 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1394 for (span, zst, align1) in field_infos {
1400 "zero-sized field in transparent {} has alignment larger than 1",
1403 .span_label(span, "has alignment larger than 1")
1409 #[allow(trivial_numeric_casts)]
1410 fn check_enum<'tcx>(
1413 vs: &'tcx [hir::Variant<'tcx>],
1416 let def = tcx.adt_def(def_id);
1417 def.destructor(tcx); // force the destructor to be evaluated
1420 let attributes = tcx.get_attrs(def_id.to_def_id());
1421 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1426 "unsupported representation for zero-variant enum"
1428 .span_label(sp, "zero-variant enum")
1433 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1434 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1435 if !tcx.features().repr128 {
1437 &tcx.sess.parse_sess,
1440 "repr with 128-bit type is unstable",
1447 if let Some(ref e) = v.disr_expr {
1448 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1452 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1453 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1455 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1456 let has_non_units = vs.iter().any(|var| !is_unit(var));
1457 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1458 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1460 if disr_non_unit || (disr_units && has_non_units) {
1462 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1467 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1468 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1469 // Check for duplicate discriminant values
1470 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1471 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1472 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1473 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1474 let i_span = match variant_i.disr_expr {
1475 Some(ref expr) => tcx.hir().span(expr.hir_id),
1476 None => tcx.hir().span(variant_i_hir_id),
1478 let span = match v.disr_expr {
1479 Some(ref expr) => tcx.hir().span(expr.hir_id),
1486 "discriminant value `{}` already exists",
1489 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1490 .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1493 disr_vals.push(discr);
1496 check_representable(tcx, sp, def_id);
1497 check_transparent(tcx, sp, def);
1500 pub(super) fn check_type_params_are_used<'tcx>(
1502 generics: &ty::Generics,
1505 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1507 assert_eq!(generics.parent, None);
1509 if generics.own_counts().types == 0 {
1513 let mut params_used = BitSet::new_empty(generics.params.len());
1515 if ty.references_error() {
1516 // If there is already another error, do not emit
1517 // an error for not using a type parameter.
1518 assert!(tcx.sess.has_errors());
1522 for leaf in ty.walk() {
1523 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1524 if let ty::Param(param) = leaf_ty.kind() {
1525 debug!("found use of ty param {:?}", param);
1526 params_used.insert(param.index);
1531 for param in &generics.params {
1532 if !params_used.contains(param.index) {
1533 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1534 let span = tcx.def_span(param.def_id);
1539 "type parameter `{}` is unused",
1542 .span_label(span, "unused type parameter")
1549 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1550 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1553 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1554 wfcheck::check_item_well_formed(tcx, def_id);
1557 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1558 wfcheck::check_trait_item(tcx, def_id);
1561 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1562 wfcheck::check_impl_item(tcx, def_id);
1565 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1566 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1567 .span_label(span, "recursive `async fn`")
1568 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1570 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1575 /// Emit an error for recursive opaque types.
1577 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1578 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1581 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1582 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1583 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1584 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1586 let mut label = false;
1587 if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1588 let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1592 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1593 .all(|ty| matches!(ty.kind(), ty::Never))
1598 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1599 .map(|expr| expr.span)
1600 .collect::<Vec<Span>>();
1601 let span_len = spans.len();
1603 err.span_label(spans[0], "this returned value is of `!` type");
1605 let mut multispan: MultiSpan = spans.clone().into();
1608 .push_span_label(span, "this returned value is of `!` type".to_string());
1610 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1612 err.help("this error will resolve once the item's body returns a concrete type");
1614 let mut seen = FxHashSet::default();
1616 err.span_label(span, "recursive opaque type");
1618 for (sp, ty) in visitor
1621 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1622 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1624 struct VisitTypes(Vec<DefId>);
1625 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1626 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1628 ty::Opaque(def, _) => {
1630 ControlFlow::CONTINUE
1632 _ => t.super_visit_with(self),
1636 let mut visitor = VisitTypes(vec![]);
1637 ty.visit_with(&mut visitor);
1638 for def_id in visitor.0 {
1639 let ty_span = tcx.def_span(def_id);
1640 if !seen.contains(&ty_span) {
1641 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1642 seen.insert(ty_span);
1644 err.span_label(sp, &format!("returning here with type `{}`", ty));
1650 err.span_label(span, "cannot resolve opaque type");