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();
91 fcx.instantiate_opaque_types_from_value(fn_id, declared_ret_ty, decl.output.span());
92 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
93 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
94 fcx.ret_type_span = Some(decl.output.span());
95 if let ty::Opaque(..) = declared_ret_ty.kind() {
96 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
98 fn_sig = tcx.mk_fn_sig(
99 fn_sig.inputs().iter().cloned(),
106 let span = body.value.span;
108 fn_maybe_err(tcx, span, fn_sig.abi);
110 if fn_sig.abi == Abi::RustCall {
111 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
114 let item = match tcx.hir().get(fn_id) {
115 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
116 Node::ImplItem(hir::ImplItem {
117 kind: hir::ImplItemKind::Fn(header, ..), ..
119 Node::TraitItem(hir::TraitItem {
120 kind: hir::TraitItemKind::Fn(header, ..),
123 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
124 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
125 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
128 if let Some(header) = item {
129 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple")
133 if fn_sig.inputs().len() != expected_args {
136 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
137 // This will probably require wide-scale changes to support a TupleKind obligation
138 // We can't resolve this without knowing the type of the param
139 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
145 if body.generator_kind.is_some() && can_be_generator.is_some() {
147 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
148 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
150 // Resume type defaults to `()` if the generator has no argument.
151 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
153 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
156 let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id).to_def_id()).expect_local();
157 let outer_hir_id = hir.local_def_id_to_hir_id(outer_def_id);
158 GatherLocalsVisitor::new(&fcx, outer_hir_id).visit_body(body);
160 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
161 // (as it's created inside the body itself, not passed in from outside).
162 let maybe_va_list = if fn_sig.c_variadic {
163 let span = body.params.last().unwrap().span;
164 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
165 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
167 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
172 // Add formal parameters.
173 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
174 let inputs_fn = fn_sig.inputs().iter().copied();
175 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
176 // Check the pattern.
177 let ty_span = try { inputs_hir?.get(idx)?.span };
178 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
180 // Check that argument is Sized.
181 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
182 // for simple cases like `fn foo(x: Trait)`,
183 // where we would error once on the parameter as a whole, and once on the binding `x`.
184 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
185 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
188 fcx.write_ty(param.hir_id, param_ty);
191 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
193 fcx.in_tail_expr = true;
194 if let ty::Dynamic(..) = declared_ret_ty.kind() {
195 // FIXME: We need to verify that the return type is `Sized` after the return expression has
196 // been evaluated so that we have types available for all the nodes being returned, but that
197 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
198 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
199 // while keeping the current ordering we will ignore the tail expression's type because we
200 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
201 // because we will trigger "unreachable expression" lints unconditionally.
202 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
203 // case that a newcomer might make, returning a bare trait, and in that case we populate
204 // the tail expression's type so that the suggestion will be correct, but ignore all other
206 fcx.check_expr(&body.value);
207 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
209 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
210 fcx.check_return_expr(&body.value);
212 fcx.in_tail_expr = false;
214 // We insert the deferred_generator_interiors entry after visiting the body.
215 // This ensures that all nested generators appear before the entry of this generator.
216 // resolve_generator_interiors relies on this property.
217 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
219 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
220 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
222 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
223 Some(GeneratorTypes {
227 movability: can_be_generator.unwrap(),
233 // Finalize the return check by taking the LUB of the return types
234 // we saw and assigning it to the expected return type. This isn't
235 // really expected to fail, since the coercions would have failed
236 // earlier when trying to find a LUB.
238 // However, the behavior around `!` is sort of complex. In the
239 // event that the `actual_return_ty` comes back as `!`, that
240 // indicates that the fn either does not return or "returns" only
241 // values of type `!`. In this case, if there is an expected
242 // return type that is *not* `!`, that should be ok. But if the
243 // return type is being inferred, we want to "fallback" to `!`:
245 // let x = move || panic!();
247 // To allow for that, I am creating a type variable with diverging
248 // fallback. This was deemed ever so slightly better than unifying
249 // the return value with `!` because it allows for the caller to
250 // make more assumptions about the return type (e.g., they could do
252 // let y: Option<u32> = Some(x());
254 // which would then cause this return type to become `u32`, not
256 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
257 let mut actual_return_ty = coercion.complete(&fcx);
258 if actual_return_ty.is_never() {
259 actual_return_ty = fcx.next_diverging_ty_var(TypeVariableOrigin {
260 kind: TypeVariableOriginKind::DivergingFn,
264 fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty);
266 // Check that the main return type implements the termination trait.
267 if let Some(term_id) = tcx.lang_items().termination() {
268 if let Some((def_id, EntryFnType::Main)) = tcx.entry_fn(LOCAL_CRATE) {
269 let main_id = hir.local_def_id_to_hir_id(def_id);
270 if main_id == fn_id {
271 let substs = tcx.mk_substs_trait(declared_ret_ty, &[]);
272 let trait_ref = ty::TraitRef::new(term_id, substs);
273 let return_ty_span = decl.output.span();
274 let cause = traits::ObligationCause::new(
277 ObligationCauseCode::MainFunctionType,
280 inherited.register_predicate(traits::Obligation::new(
283 trait_ref.without_const().to_predicate(tcx),
289 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
290 if let Some(panic_impl_did) = tcx.lang_items().panic_impl() {
291 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
292 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
293 if *declared_ret_ty.kind() != ty::Never {
294 sess.span_err(decl.output.span(), "return type should be `!`");
297 let inputs = fn_sig.inputs();
298 let span = hir.span(fn_id);
299 if inputs.len() == 1 {
300 let arg_is_panic_info = match *inputs[0].kind() {
301 ty::Ref(region, ty, mutbl) => match *ty.kind() {
302 ty::Adt(ref adt, _) => {
303 adt.did == panic_info_did
304 && mutbl == hir::Mutability::Not
305 && *region != RegionKind::ReStatic
312 if !arg_is_panic_info {
313 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
316 if let Node::Item(item) = hir.get(fn_id) {
317 if let ItemKind::Fn(_, ref generics, _) = item.kind {
318 if !generics.params.is_empty() {
319 sess.span_err(span, "should have no type parameters");
324 let span = sess.source_map().guess_head_span(span);
325 sess.span_err(span, "function should have one argument");
328 sess.err("language item required, but not found: `panic_info`");
333 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
334 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
335 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
336 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
337 if *declared_ret_ty.kind() != ty::Never {
338 sess.span_err(decl.output.span(), "return type should be `!`");
341 let inputs = fn_sig.inputs();
342 let span = hir.span(fn_id);
343 if inputs.len() == 1 {
344 let arg_is_alloc_layout = match inputs[0].kind() {
345 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
349 if !arg_is_alloc_layout {
350 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
353 if let Node::Item(item) = hir.get(fn_id) {
354 if let ItemKind::Fn(_, ref generics, _) = item.kind {
355 if !generics.params.is_empty() {
358 "`#[alloc_error_handler]` function should have no type \
365 let span = sess.source_map().guess_head_span(span);
366 sess.span_err(span, "function should have one argument");
369 sess.err("language item required, but not found: `alloc_layout`");
377 pub(super) fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) {
378 let def_id = tcx.hir().local_def_id(id);
379 let def = tcx.adt_def(def_id);
380 def.destructor(tcx); // force the destructor to be evaluated
381 check_representable(tcx, span, def_id);
384 check_simd(tcx, span, def_id);
387 check_transparent(tcx, span, def);
388 check_packed(tcx, span, def);
391 fn check_union(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) {
392 let def_id = tcx.hir().local_def_id(id);
393 let def = tcx.adt_def(def_id);
394 def.destructor(tcx); // force the destructor to be evaluated
395 check_representable(tcx, span, def_id);
396 check_transparent(tcx, span, def);
397 check_union_fields(tcx, span, def_id);
398 check_packed(tcx, span, def);
401 /// Check that the fields of the `union` do not need dropping.
402 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
403 let item_type = tcx.type_of(item_def_id);
404 if let ty::Adt(def, substs) = item_type.kind() {
405 assert!(def.is_union());
406 let fields = &def.non_enum_variant().fields;
407 let param_env = tcx.param_env(item_def_id);
408 for field in fields {
409 let field_ty = field.ty(tcx, substs);
410 // We are currently checking the type this field came from, so it must be local.
411 let field_span = tcx.hir().span_if_local(field.did).unwrap();
412 if field_ty.needs_drop(tcx, param_env) {
417 "unions may not contain fields that need dropping"
419 .span_note(field_span, "`std::mem::ManuallyDrop` can be used to wrap the type")
425 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
430 /// Check that a `static` is inhabited.
431 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
432 // Make sure statics are inhabited.
433 // Other parts of the compiler assume that there are no uninhabited places. In principle it
434 // would be enough to check this for `extern` statics, as statics with an initializer will
435 // have UB during initialization if they are uninhabited, but there also seems to be no good
436 // reason to allow any statics to be uninhabited.
437 let ty = tcx.type_of(def_id);
438 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
441 // Generic statics are rejected, but we still reach this case.
442 tcx.sess.delay_span_bug(span, "generic static must be rejected");
446 if layout.abi.is_uninhabited() {
447 tcx.struct_span_lint_hir(
449 tcx.hir().local_def_id_to_hir_id(def_id),
452 lint.build("static of uninhabited type")
453 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
460 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
461 /// projections that would result in "inheriting lifetimes".
462 pub(super) fn check_opaque<'tcx>(
465 substs: SubstsRef<'tcx>,
467 origin: &hir::OpaqueTyOrigin,
469 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
470 if tcx.type_of(def_id).references_error() {
473 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
476 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
479 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
480 /// in "inheriting lifetimes".
481 #[instrument(level = "debug", skip(tcx, span))]
482 pub(super) fn check_opaque_for_inheriting_lifetimes(
487 let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(def_id));
488 debug!(?item, ?span);
490 struct FoundParentLifetime;
491 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
492 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
493 type BreakTy = FoundParentLifetime;
495 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
496 debug!("FindParentLifetimeVisitor: r={:?}", r);
497 if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r {
498 if *index < self.0.parent_count as u32 {
499 return ControlFlow::Break(FoundParentLifetime);
501 return ControlFlow::CONTINUE;
505 r.super_visit_with(self)
508 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
509 if let ty::ConstKind::Unevaluated(..) = c.val {
510 // FIXME(#72219) We currently don't detect lifetimes within substs
511 // which would violate this check. Even though the particular substitution is not used
512 // within the const, this should still be fixed.
513 return ControlFlow::CONTINUE;
515 c.super_visit_with(self)
519 struct ProhibitOpaqueVisitor<'tcx> {
520 opaque_identity_ty: Ty<'tcx>,
521 generics: &'tcx ty::Generics,
523 selftys: Vec<(Span, Option<String>)>,
526 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
527 type BreakTy = Ty<'tcx>;
529 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
530 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
531 if t == self.opaque_identity_ty {
532 ControlFlow::CONTINUE
534 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
535 .map_break(|FoundParentLifetime| t)
540 impl Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
541 type Map = rustc_middle::hir::map::Map<'tcx>;
543 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
544 hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
547 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
549 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
550 [PathSegment { res: Some(Res::SelfTy(_, impl_ref)), .. }] => {
552 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
553 self.selftys.push((path.span, impl_ty_name));
559 hir::intravisit::walk_ty(self, arg);
563 if let ItemKind::OpaqueTy(hir::OpaqueTy {
564 origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
568 let mut visitor = ProhibitOpaqueVisitor {
569 opaque_identity_ty: tcx.mk_opaque(
571 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
573 generics: tcx.generics_of(def_id),
577 let prohibit_opaque = tcx
578 .explicit_item_bounds(def_id)
580 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
582 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
583 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
586 if let Some(ty) = prohibit_opaque.break_value() {
587 visitor.visit_item(&item);
588 let is_async = match item.kind {
589 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
590 matches!(origin, hir::OpaqueTyOrigin::AsyncFn)
595 let mut err = struct_span_err!(
599 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
601 if is_async { "async fn" } else { "impl Trait" },
604 for (span, name) in visitor.selftys {
607 "consider spelling out the type instead",
608 name.unwrap_or_else(|| format!("{:?}", ty)),
609 Applicability::MaybeIncorrect,
617 /// Checks that an opaque type does not contain cycles.
618 pub(super) fn check_opaque_for_cycles<'tcx>(
621 substs: SubstsRef<'tcx>,
623 origin: &hir::OpaqueTyOrigin,
624 ) -> Result<(), ErrorReported> {
625 if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
628 hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
629 hir::OpaqueTyOrigin::Binding => {
630 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
632 _ => opaque_type_cycle_error(tcx, def_id, span),
640 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
642 /// This is mostly checked at the places that specify the opaque type, but we
643 /// check those cases in the `param_env` of that function, which may have
644 /// bounds not on this opaque type:
646 /// type X<T> = impl Clone
647 /// fn f<T: Clone>(t: T) -> X<T> {
651 /// Without this check the above code is incorrectly accepted: we would ICE if
652 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
653 fn check_opaque_meets_bounds<'tcx>(
656 substs: SubstsRef<'tcx>,
658 origin: &hir::OpaqueTyOrigin,
661 // Checked when type checking the function containing them.
662 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => return,
663 // Can have different predicates to their defining use
664 hir::OpaqueTyOrigin::Binding | hir::OpaqueTyOrigin::Misc => {}
667 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
668 let param_env = tcx.param_env(def_id);
670 tcx.infer_ctxt().enter(move |infcx| {
671 let inh = Inherited::new(infcx, def_id);
672 let infcx = &inh.infcx;
673 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
675 let misc_cause = traits::ObligationCause::misc(span, hir_id);
677 let (_, opaque_type_map) = inh.register_infer_ok_obligations(
678 infcx.instantiate_opaque_types(def_id, hir_id, param_env, opaque_ty, span),
681 for (def_id, opaque_defn) in opaque_type_map {
683 .at(&misc_cause, param_env)
684 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, opaque_defn.substs))
686 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
687 Err(ty_err) => tcx.sess.delay_span_bug(
688 opaque_defn.definition_span,
690 "could not unify `{}` with revealed type:\n{}",
691 opaque_defn.concrete_ty, ty_err,
697 // Check that all obligations are satisfied by the implementation's
699 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
700 infcx.report_fulfillment_errors(errors, None, false);
703 // Finally, resolve all regions. This catches wily misuses of
704 // lifetime parameters.
705 let fcx = FnCtxt::new(&inh, param_env, hir_id);
706 fcx.regionck_item(hir_id, span, &[]);
710 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
712 "check_item_type(it.hir_id={}, it.name={})",
714 tcx.def_path_str(tcx.hir().local_def_id(it.hir_id).to_def_id())
716 let _indenter = indenter();
718 // Consts can play a role in type-checking, so they are included here.
719 hir::ItemKind::Static(..) => {
720 let def_id = tcx.hir().local_def_id(it.hir_id);
721 tcx.ensure().typeck(def_id);
722 maybe_check_static_with_link_section(tcx, def_id, it.span);
723 check_static_inhabited(tcx, def_id, it.span);
725 hir::ItemKind::Const(..) => {
726 tcx.ensure().typeck(tcx.hir().local_def_id(it.hir_id));
728 hir::ItemKind::Enum(ref enum_definition, _) => {
729 check_enum(tcx, it.span, &enum_definition.variants, it.hir_id);
731 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
732 hir::ItemKind::Impl(ref impl_) => {
733 debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id);
734 let impl_def_id = tcx.hir().local_def_id(it.hir_id);
735 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
736 check_impl_items_against_trait(
743 let trait_def_id = impl_trait_ref.def_id;
744 check_on_unimplemented(tcx, trait_def_id, it);
747 hir::ItemKind::Trait(_, _, _, _, ref items) => {
748 let def_id = tcx.hir().local_def_id(it.hir_id);
749 check_on_unimplemented(tcx, def_id.to_def_id(), it);
751 for item in items.iter() {
752 let item = tcx.hir().trait_item(item.id);
754 hir::TraitItemKind::Fn(ref sig, _) => {
755 let abi = sig.header.abi;
756 fn_maybe_err(tcx, item.ident.span, abi);
758 hir::TraitItemKind::Type(.., Some(_default)) => {
759 let item_def_id = tcx.hir().local_def_id(item.hir_id).to_def_id();
760 let assoc_item = tcx.associated_item(item_def_id);
762 InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
763 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
768 ty::TraitRef { def_id: def_id.to_def_id(), substs: trait_substs },
775 hir::ItemKind::Struct(..) => {
776 check_struct(tcx, it.hir_id, it.span);
778 hir::ItemKind::Union(..) => {
779 check_union(tcx, it.hir_id, it.span);
781 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
782 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
783 // `async-std` (and `pub async fn` in general).
784 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
785 // See https://github.com/rust-lang/rust/issues/75100
786 if !tcx.sess.opts.actually_rustdoc {
787 let def_id = tcx.hir().local_def_id(it.hir_id);
789 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
790 check_opaque(tcx, def_id, substs, it.span, &origin);
793 hir::ItemKind::TyAlias(..) => {
794 let def_id = tcx.hir().local_def_id(it.hir_id);
795 let pty_ty = tcx.type_of(def_id);
796 let generics = tcx.generics_of(def_id);
797 check_type_params_are_used(tcx, &generics, pty_ty);
799 hir::ItemKind::ForeignMod { abi, items } => {
800 check_abi(tcx, it.span, abi);
802 if abi == Abi::RustIntrinsic {
804 let item = tcx.hir().foreign_item(item.id);
805 intrinsic::check_intrinsic_type(tcx, item);
807 } else if abi == Abi::PlatformIntrinsic {
809 let item = tcx.hir().foreign_item(item.id);
810 intrinsic::check_platform_intrinsic_type(tcx, item);
814 let def_id = tcx.hir().local_def_id(item.id.hir_id);
815 let generics = tcx.generics_of(def_id);
816 let own_counts = generics.own_counts();
817 if generics.params.len() - own_counts.lifetimes != 0 {
818 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
819 (_, 0) => ("type", "types", Some("u32")),
820 // We don't specify an example value, because we can't generate
821 // a valid value for any type.
822 (0, _) => ("const", "consts", None),
823 _ => ("type or const", "types or consts", None),
829 "foreign items may not have {} parameters",
832 .span_label(item.span, &format!("can't have {} parameters", kinds))
834 // FIXME: once we start storing spans for type arguments, turn this
835 // into a suggestion.
837 "replace the {} parameters with concrete {}{}",
840 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
846 let item = tcx.hir().foreign_item(item.id);
848 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
849 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
851 hir::ForeignItemKind::Static(..) => {
852 check_static_inhabited(tcx, def_id, item.span);
859 _ => { /* nothing to do */ }
863 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
864 let item_def_id = tcx.hir().local_def_id(item.hir_id);
865 // an error would be reported if this fails.
866 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id.to_def_id());
869 pub(super) fn check_specialization_validity<'tcx>(
871 trait_def: &ty::TraitDef,
872 trait_item: &ty::AssocItem,
874 impl_item: &hir::ImplItem<'_>,
876 let kind = match impl_item.kind {
877 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
878 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
879 hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
882 let ancestors = match trait_def.ancestors(tcx, impl_id) {
883 Ok(ancestors) => ancestors,
886 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
887 if parent.is_from_trait() {
890 Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
894 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
896 // Parent impl exists, and contains the parent item we're trying to specialize, but
897 // doesn't mark it `default`.
898 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
899 Some(Err(parent_impl.def_id()))
902 // Parent impl contains item and makes it specializable.
903 Some(_) => Some(Ok(())),
905 // Parent impl doesn't mention the item. This means it's inherited from the
906 // grandparent. In that case, if parent is a `default impl`, inherited items use the
907 // "defaultness" from the grandparent, else they are final.
909 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
912 Some(Err(parent_impl.def_id()))
918 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
919 // item. This is allowed, the item isn't actually getting specialized here.
920 let result = opt_result.unwrap_or(Ok(()));
922 if let Err(parent_impl) = result {
923 report_forbidden_specialization(tcx, impl_item, parent_impl);
927 pub(super) fn check_impl_items_against_trait<'tcx>(
929 full_impl_span: Span,
931 impl_trait_ref: ty::TraitRef<'tcx>,
932 impl_item_refs: &[hir::ImplItemRef<'_>],
934 // If the trait reference itself is erroneous (so the compilation is going
935 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
936 // isn't populated for such impls.
937 if impl_trait_ref.references_error() {
941 // Negative impls are not expected to have any items
942 match tcx.impl_polarity(impl_id) {
943 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
944 ty::ImplPolarity::Negative => {
945 if let [first_item_ref, ..] = impl_item_refs {
946 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
951 "negative impls cannot have any items"
959 // Locate trait definition and items
960 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
961 let impl_items = impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
962 let associated_items = tcx.associated_items(impl_trait_ref.def_id);
964 // Check existing impl methods to see if they are both present in trait
965 // and compatible with trait signature
966 for impl_item in impl_items {
967 let ty_impl_item = tcx.associated_item(tcx.hir().local_def_id(impl_item.hir_id));
970 associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id);
972 let (compatible_kind, ty_trait_item) = if let Some(ty_trait_item) = items.next() {
973 let is_compatible = |ty: &&ty::AssocItem| match (ty.kind, &impl_item.kind) {
974 (ty::AssocKind::Const, hir::ImplItemKind::Const(..)) => true,
975 (ty::AssocKind::Fn, hir::ImplItemKind::Fn(..)) => true,
976 (ty::AssocKind::Type, hir::ImplItemKind::TyAlias(..)) => true,
980 // If we don't have a compatible item, we'll use the first one whose name matches
981 // to report an error.
982 let mut compatible_kind = is_compatible(&ty_trait_item);
983 let mut trait_item = ty_trait_item;
985 if !compatible_kind {
986 if let Some(ty_trait_item) = items.find(is_compatible) {
987 compatible_kind = true;
988 trait_item = ty_trait_item;
992 (compatible_kind, trait_item)
998 match impl_item.kind {
999 hir::ImplItemKind::Const(..) => {
1000 // Find associated const definition.
1009 hir::ImplItemKind::Fn(..) => {
1010 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1011 compare_impl_method(
1020 hir::ImplItemKind::TyAlias(_) => {
1021 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1033 check_specialization_validity(
1037 impl_id.to_def_id(),
1041 report_mismatch_error(
1043 ty_trait_item.def_id,
1051 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1052 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1054 // Check for missing items from trait
1055 let mut missing_items = Vec::new();
1056 for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
1057 let is_implemented = ancestors
1058 .leaf_def(tcx, trait_item.ident, trait_item.kind)
1059 .map(|node_item| !node_item.defining_node.is_from_trait())
1062 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1063 if !trait_item.defaultness.has_value() {
1064 missing_items.push(*trait_item);
1069 if !missing_items.is_empty() {
1070 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1077 fn report_mismatch_error<'tcx>(
1079 trait_item_def_id: DefId,
1080 impl_trait_ref: ty::TraitRef<'tcx>,
1081 impl_item: &hir::ImplItem<'_>,
1082 ty_impl_item: &ty::AssocItem,
1084 let mut err = match impl_item.kind {
1085 hir::ImplItemKind::Const(..) => {
1086 // Find associated const definition.
1091 "item `{}` is an associated const, which doesn't match its trait `{}`",
1093 impl_trait_ref.print_only_trait_path()
1097 hir::ImplItemKind::Fn(..) => {
1102 "item `{}` is an associated method, which doesn't match its trait `{}`",
1104 impl_trait_ref.print_only_trait_path()
1108 hir::ImplItemKind::TyAlias(_) => {
1113 "item `{}` is an associated type, which doesn't match its trait `{}`",
1115 impl_trait_ref.print_only_trait_path()
1120 err.span_label(impl_item.span, "does not match trait");
1121 if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) {
1122 err.span_label(trait_span, "item in trait");
1127 /// Checks whether a type can be represented in memory. In particular, it
1128 /// identifies types that contain themselves without indirection through a
1129 /// pointer, which would mean their size is unbounded.
1130 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1131 let rty = tcx.type_of(item_def_id);
1133 // Check that it is possible to represent this type. This call identifies
1134 // (1) types that contain themselves and (2) types that contain a different
1135 // recursive type. It is only necessary to throw an error on those that
1136 // contain themselves. For case 2, there must be an inner type that will be
1137 // caught by case 1.
1138 match rty.is_representable(tcx, sp) {
1139 Representability::SelfRecursive(spans) => {
1140 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1143 Representability::Representable | Representability::ContainsRecursive => (),
1148 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1149 let t = tcx.type_of(def_id);
1150 if let ty::Adt(def, substs) = t.kind() {
1151 if def.is_struct() {
1152 let fields = &def.non_enum_variant().fields;
1153 if fields.is_empty() {
1154 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1157 let e = fields[0].ty(tcx, substs);
1158 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1159 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1160 .span_label(sp, "SIMD elements must have the same type")
1165 let len = if let ty::Array(_ty, c) = e.kind() {
1166 c.try_eval_usize(tcx, tcx.param_env(def.did))
1168 Some(fields.len() as u64)
1170 if let Some(len) = len {
1172 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1174 } else if !len.is_power_of_two() {
1179 "SIMD vector length must be a power of two"
1183 } else if len > MAX_SIMD_LANES {
1188 "SIMD vector cannot have more than {} elements",
1197 ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ }
1198 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1199 ty::Array(ty, _c) if ty.is_machine() => { /* struct([f32; 4]) */ }
1205 "SIMD vector element type should be a \
1206 primitive scalar (integer/float/pointer) type"
1216 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1217 let repr = def.repr;
1219 for attr in tcx.get_attrs(def.did).iter() {
1220 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1221 if let attr::ReprPacked(pack) = r {
1222 if let Some(repr_pack) = repr.pack {
1223 if pack as u64 != repr_pack.bytes() {
1228 "type has conflicting packed representation hints"
1236 if repr.align.is_some() {
1241 "type has conflicting packed and align representation hints"
1245 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1246 let mut err = struct_span_err!(
1250 "packed type cannot transitively contain a `#[repr(align)]` type"
1254 tcx.def_span(def_spans[0].0),
1256 "`{}` has a `#[repr(align)]` attribute",
1257 tcx.item_name(def_spans[0].0)
1261 if def_spans.len() > 2 {
1262 let mut first = true;
1263 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1264 let ident = tcx.item_name(*adt_def);
1269 "`{}` contains a field of type `{}`",
1270 tcx.type_of(def.did),
1274 format!("...which contains a field of type `{}`", ident)
1287 pub(super) fn check_packed_inner(
1290 stack: &mut Vec<DefId>,
1291 ) -> Option<Vec<(DefId, Span)>> {
1292 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1293 if def.is_struct() || def.is_union() {
1294 if def.repr.align.is_some() {
1295 return Some(vec![(def.did, DUMMY_SP)]);
1299 for field in &def.non_enum_variant().fields {
1300 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1301 if !stack.contains(&def.did) {
1302 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1303 defs.push((def.did, field.ident.span));
1316 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1317 if !adt.repr.transparent() {
1320 let sp = tcx.sess.source_map().guess_head_span(sp);
1322 if adt.is_union() && !tcx.features().transparent_unions {
1324 &tcx.sess.parse_sess,
1325 sym::transparent_unions,
1327 "transparent unions are unstable",
1332 if adt.variants.len() != 1 {
1333 bad_variant_count(tcx, adt, sp, adt.did);
1334 if adt.variants.is_empty() {
1335 // Don't bother checking the fields. No variants (and thus no fields) exist.
1340 // For each field, figure out if it's known to be a ZST and align(1)
1341 let field_infos = adt.all_fields().map(|field| {
1342 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1343 let param_env = tcx.param_env(field.did);
1344 let layout = tcx.layout_of(param_env.and(ty));
1345 // We are currently checking the type this field came from, so it must be local
1346 let span = tcx.hir().span_if_local(field.did).unwrap();
1347 let zst = layout.map_or(false, |layout| layout.is_zst());
1348 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1352 let non_zst_fields =
1353 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1354 let non_zst_count = non_zst_fields.clone().count();
1355 if non_zst_count != 1 {
1356 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1358 for (span, zst, align1) in field_infos {
1364 "zero-sized field in transparent {} has alignment larger than 1",
1367 .span_label(span, "has alignment larger than 1")
1373 #[allow(trivial_numeric_casts)]
1374 pub fn check_enum<'tcx>(
1377 vs: &'tcx [hir::Variant<'tcx>],
1380 let def_id = tcx.hir().local_def_id(id);
1381 let def = tcx.adt_def(def_id);
1382 def.destructor(tcx); // force the destructor to be evaluated
1385 let attributes = tcx.get_attrs(def_id.to_def_id());
1386 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1391 "unsupported representation for zero-variant enum"
1393 .span_label(sp, "zero-variant enum")
1398 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1399 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1400 if !tcx.features().repr128 {
1402 &tcx.sess.parse_sess,
1405 "repr with 128-bit type is unstable",
1412 if let Some(ref e) = v.disr_expr {
1413 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1417 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1418 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1420 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1421 let has_non_units = vs.iter().any(|var| !is_unit(var));
1422 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1423 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1425 if disr_non_unit || (disr_units && has_non_units) {
1427 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1432 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1433 for ((_, discr), v) in def.discriminants(tcx).zip(vs) {
1434 // Check for duplicate discriminant values
1435 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1436 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1437 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1438 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1439 let i_span = match variant_i.disr_expr {
1440 Some(ref expr) => tcx.hir().span(expr.hir_id),
1441 None => tcx.hir().span(variant_i_hir_id),
1443 let span = match v.disr_expr {
1444 Some(ref expr) => tcx.hir().span(expr.hir_id),
1451 "discriminant value `{}` already exists",
1454 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1455 .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1458 disr_vals.push(discr);
1461 check_representable(tcx, sp, def_id);
1462 check_transparent(tcx, sp, def);
1465 pub(super) fn check_type_params_are_used<'tcx>(
1467 generics: &ty::Generics,
1470 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1472 assert_eq!(generics.parent, None);
1474 if generics.own_counts().types == 0 {
1478 let mut params_used = BitSet::new_empty(generics.params.len());
1480 if ty.references_error() {
1481 // If there is already another error, do not emit
1482 // an error for not using a type parameter.
1483 assert!(tcx.sess.has_errors());
1487 for leaf in ty.walk() {
1488 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1489 if let ty::Param(param) = leaf_ty.kind() {
1490 debug!("found use of ty param {:?}", param);
1491 params_used.insert(param.index);
1496 for param in &generics.params {
1497 if !params_used.contains(param.index) {
1498 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1499 let span = tcx.def_span(param.def_id);
1504 "type parameter `{}` is unused",
1507 .span_label(span, "unused type parameter")
1514 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1515 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1518 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1519 wfcheck::check_item_well_formed(tcx, def_id);
1522 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1523 wfcheck::check_trait_item(tcx, def_id);
1526 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1527 wfcheck::check_impl_item(tcx, def_id);
1530 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1531 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1532 .span_label(span, "recursive `async fn`")
1533 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1535 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1540 /// Emit an error for recursive opaque types.
1542 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1543 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1546 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1547 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1548 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1549 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1551 let mut label = false;
1552 if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1553 let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1557 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1558 .all(|ty| matches!(ty.kind(), ty::Never))
1563 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1564 .map(|expr| expr.span)
1565 .collect::<Vec<Span>>();
1566 let span_len = spans.len();
1568 err.span_label(spans[0], "this returned value is of `!` type");
1570 let mut multispan: MultiSpan = spans.clone().into();
1573 .push_span_label(span, "this returned value is of `!` type".to_string());
1575 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1577 err.help("this error will resolve once the item's body returns a concrete type");
1579 let mut seen = FxHashSet::default();
1581 err.span_label(span, "recursive opaque type");
1583 for (sp, ty) in visitor
1586 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1587 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1589 struct VisitTypes(Vec<DefId>);
1590 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1591 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1593 ty::Opaque(def, _) => {
1595 ControlFlow::CONTINUE
1597 _ => t.super_visit_with(self),
1601 let mut visitor = VisitTypes(vec![]);
1602 ty.visit_with(&mut visitor);
1603 for def_id in visitor.0 {
1604 let ty_span = tcx.def_span(def_id);
1605 if !seen.contains(&ty_span) {
1606 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1607 seen.insert(ty_span);
1609 err.span_label(sp, &format!("returning here with type `{}`", ty));
1615 err.span_label(span, "cannot resolve opaque type");