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::{ItemKind, Node};
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)
520 struct ProhibitOpaqueVisitor<'tcx> {
521 opaque_identity_ty: Ty<'tcx>,
522 generics: &'tcx ty::Generics,
525 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
526 type BreakTy = Ty<'tcx>;
528 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
529 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
530 if t == self.opaque_identity_ty {
531 ControlFlow::CONTINUE
533 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
534 .map_break(|FoundParentLifetime| t)
539 if let ItemKind::OpaqueTy(hir::OpaqueTy {
540 origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
544 let mut visitor = ProhibitOpaqueVisitor {
545 opaque_identity_ty: tcx.mk_opaque(
547 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
549 generics: tcx.generics_of(def_id),
551 let prohibit_opaque = tcx
552 .explicit_item_bounds(def_id)
554 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
556 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor={:?}",
557 prohibit_opaque, visitor
560 if let Some(ty) = prohibit_opaque.break_value() {
561 let mut visitor = SelfTySpanVisitor { tcx, selfty_spans: vec![] };
562 visitor.visit_item(&item);
563 let is_async = match item.kind {
564 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
565 matches!(origin, hir::OpaqueTyOrigin::AsyncFn)
570 let mut err = struct_span_err!(
574 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
576 if is_async { "async fn" } else { "impl Trait" },
579 for span in visitor.selfty_spans {
582 "consider spelling out the type instead",
584 Applicability::MaybeIncorrect,
592 /// Checks that an opaque type does not contain cycles.
593 pub(super) fn check_opaque_for_cycles<'tcx>(
596 substs: SubstsRef<'tcx>,
598 origin: &hir::OpaqueTyOrigin,
599 ) -> Result<(), ErrorReported> {
600 if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
603 hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
604 hir::OpaqueTyOrigin::Binding => {
605 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
607 _ => opaque_type_cycle_error(tcx, def_id, span),
615 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
617 /// This is mostly checked at the places that specify the opaque type, but we
618 /// check those cases in the `param_env` of that function, which may have
619 /// bounds not on this opaque type:
621 /// type X<T> = impl Clone
622 /// fn f<T: Clone>(t: T) -> X<T> {
626 /// Without this check the above code is incorrectly accepted: we would ICE if
627 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
628 fn check_opaque_meets_bounds<'tcx>(
631 substs: SubstsRef<'tcx>,
633 origin: &hir::OpaqueTyOrigin,
636 // Checked when type checking the function containing them.
637 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => return,
638 // Can have different predicates to their defining use
639 hir::OpaqueTyOrigin::Binding | hir::OpaqueTyOrigin::Misc => {}
642 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
643 let param_env = tcx.param_env(def_id);
645 tcx.infer_ctxt().enter(move |infcx| {
646 let inh = Inherited::new(infcx, def_id);
647 let infcx = &inh.infcx;
648 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
650 let misc_cause = traits::ObligationCause::misc(span, hir_id);
652 let (_, opaque_type_map) = inh.register_infer_ok_obligations(
653 infcx.instantiate_opaque_types(def_id, hir_id, param_env, opaque_ty, span),
656 for (def_id, opaque_defn) in opaque_type_map {
658 .at(&misc_cause, param_env)
659 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, opaque_defn.substs))
661 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
662 Err(ty_err) => tcx.sess.delay_span_bug(
663 opaque_defn.definition_span,
665 "could not unify `{}` with revealed type:\n{}",
666 opaque_defn.concrete_ty, ty_err,
672 // Check that all obligations are satisfied by the implementation's
674 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
675 infcx.report_fulfillment_errors(errors, None, false);
678 // Finally, resolve all regions. This catches wily misuses of
679 // lifetime parameters.
680 let fcx = FnCtxt::new(&inh, param_env, hir_id);
681 fcx.regionck_item(hir_id, span, &[]);
685 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
687 "check_item_type(it.hir_id={}, it.name={})",
689 tcx.def_path_str(tcx.hir().local_def_id(it.hir_id).to_def_id())
691 let _indenter = indenter();
693 // Consts can play a role in type-checking, so they are included here.
694 hir::ItemKind::Static(..) => {
695 let def_id = tcx.hir().local_def_id(it.hir_id);
696 tcx.ensure().typeck(def_id);
697 maybe_check_static_with_link_section(tcx, def_id, it.span);
698 check_static_inhabited(tcx, def_id, it.span);
700 hir::ItemKind::Const(..) => {
701 tcx.ensure().typeck(tcx.hir().local_def_id(it.hir_id));
703 hir::ItemKind::Enum(ref enum_definition, _) => {
704 check_enum(tcx, it.span, &enum_definition.variants, it.hir_id);
706 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
707 hir::ItemKind::Impl(ref impl_) => {
708 debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id);
709 let impl_def_id = tcx.hir().local_def_id(it.hir_id);
710 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
711 check_impl_items_against_trait(
718 let trait_def_id = impl_trait_ref.def_id;
719 check_on_unimplemented(tcx, trait_def_id, it);
722 hir::ItemKind::Trait(_, _, _, _, ref items) => {
723 let def_id = tcx.hir().local_def_id(it.hir_id);
724 check_on_unimplemented(tcx, def_id.to_def_id(), it);
726 for item in items.iter() {
727 let item = tcx.hir().trait_item(item.id);
729 hir::TraitItemKind::Fn(ref sig, _) => {
730 let abi = sig.header.abi;
731 fn_maybe_err(tcx, item.ident.span, abi);
733 hir::TraitItemKind::Type(.., Some(_default)) => {
734 let item_def_id = tcx.hir().local_def_id(item.hir_id).to_def_id();
735 let assoc_item = tcx.associated_item(item_def_id);
737 InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
738 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
743 ty::TraitRef { def_id: def_id.to_def_id(), substs: trait_substs },
750 hir::ItemKind::Struct(..) => {
751 check_struct(tcx, it.hir_id, it.span);
753 hir::ItemKind::Union(..) => {
754 check_union(tcx, it.hir_id, it.span);
756 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
757 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
758 // `async-std` (and `pub async fn` in general).
759 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
760 // See https://github.com/rust-lang/rust/issues/75100
761 if !tcx.sess.opts.actually_rustdoc {
762 let def_id = tcx.hir().local_def_id(it.hir_id);
764 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
765 check_opaque(tcx, def_id, substs, it.span, &origin);
768 hir::ItemKind::TyAlias(..) => {
769 let def_id = tcx.hir().local_def_id(it.hir_id);
770 let pty_ty = tcx.type_of(def_id);
771 let generics = tcx.generics_of(def_id);
772 check_type_params_are_used(tcx, &generics, pty_ty);
774 hir::ItemKind::ForeignMod { abi, items } => {
775 check_abi(tcx, it.span, abi);
777 if abi == Abi::RustIntrinsic {
779 let item = tcx.hir().foreign_item(item.id);
780 intrinsic::check_intrinsic_type(tcx, item);
782 } else if abi == Abi::PlatformIntrinsic {
784 let item = tcx.hir().foreign_item(item.id);
785 intrinsic::check_platform_intrinsic_type(tcx, item);
789 let def_id = tcx.hir().local_def_id(item.id.hir_id);
790 let generics = tcx.generics_of(def_id);
791 let own_counts = generics.own_counts();
792 if generics.params.len() - own_counts.lifetimes != 0 {
793 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
794 (_, 0) => ("type", "types", Some("u32")),
795 // We don't specify an example value, because we can't generate
796 // a valid value for any type.
797 (0, _) => ("const", "consts", None),
798 _ => ("type or const", "types or consts", None),
804 "foreign items may not have {} parameters",
807 .span_label(item.span, &format!("can't have {} parameters", kinds))
809 // FIXME: once we start storing spans for type arguments, turn this
810 // into a suggestion.
812 "replace the {} parameters with concrete {}{}",
815 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
821 let item = tcx.hir().foreign_item(item.id);
823 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
824 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
826 hir::ForeignItemKind::Static(..) => {
827 check_static_inhabited(tcx, def_id, item.span);
834 _ => { /* nothing to do */ }
838 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
839 let item_def_id = tcx.hir().local_def_id(item.hir_id);
840 // an error would be reported if this fails.
841 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id.to_def_id());
844 pub(super) fn check_specialization_validity<'tcx>(
846 trait_def: &ty::TraitDef,
847 trait_item: &ty::AssocItem,
849 impl_item: &hir::ImplItem<'_>,
851 let kind = match impl_item.kind {
852 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
853 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
854 hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
857 let ancestors = match trait_def.ancestors(tcx, impl_id) {
858 Ok(ancestors) => ancestors,
861 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
862 if parent.is_from_trait() {
865 Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
869 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
871 // Parent impl exists, and contains the parent item we're trying to specialize, but
872 // doesn't mark it `default`.
873 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
874 Some(Err(parent_impl.def_id()))
877 // Parent impl contains item and makes it specializable.
878 Some(_) => Some(Ok(())),
880 // Parent impl doesn't mention the item. This means it's inherited from the
881 // grandparent. In that case, if parent is a `default impl`, inherited items use the
882 // "defaultness" from the grandparent, else they are final.
884 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
887 Some(Err(parent_impl.def_id()))
893 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
894 // item. This is allowed, the item isn't actually getting specialized here.
895 let result = opt_result.unwrap_or(Ok(()));
897 if let Err(parent_impl) = result {
898 report_forbidden_specialization(tcx, impl_item, parent_impl);
902 pub(super) fn check_impl_items_against_trait<'tcx>(
904 full_impl_span: Span,
906 impl_trait_ref: ty::TraitRef<'tcx>,
907 impl_item_refs: &[hir::ImplItemRef<'_>],
909 // If the trait reference itself is erroneous (so the compilation is going
910 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
911 // isn't populated for such impls.
912 if impl_trait_ref.references_error() {
916 // Negative impls are not expected to have any items
917 match tcx.impl_polarity(impl_id) {
918 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
919 ty::ImplPolarity::Negative => {
920 if let [first_item_ref, ..] = impl_item_refs {
921 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
926 "negative impls cannot have any items"
934 // Locate trait definition and items
935 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
936 let impl_items = impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
937 let associated_items = tcx.associated_items(impl_trait_ref.def_id);
939 // Check existing impl methods to see if they are both present in trait
940 // and compatible with trait signature
941 for impl_item in impl_items {
942 let ty_impl_item = tcx.associated_item(tcx.hir().local_def_id(impl_item.hir_id));
945 associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id);
947 let (compatible_kind, ty_trait_item) = if let Some(ty_trait_item) = items.next() {
948 let is_compatible = |ty: &&ty::AssocItem| match (ty.kind, &impl_item.kind) {
949 (ty::AssocKind::Const, hir::ImplItemKind::Const(..)) => true,
950 (ty::AssocKind::Fn, hir::ImplItemKind::Fn(..)) => true,
951 (ty::AssocKind::Type, hir::ImplItemKind::TyAlias(..)) => true,
955 // If we don't have a compatible item, we'll use the first one whose name matches
956 // to report an error.
957 let mut compatible_kind = is_compatible(&ty_trait_item);
958 let mut trait_item = ty_trait_item;
960 if !compatible_kind {
961 if let Some(ty_trait_item) = items.find(is_compatible) {
962 compatible_kind = true;
963 trait_item = ty_trait_item;
967 (compatible_kind, trait_item)
973 match impl_item.kind {
974 hir::ImplItemKind::Const(..) => {
975 // Find associated const definition.
984 hir::ImplItemKind::Fn(..) => {
985 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
995 hir::ImplItemKind::TyAlias(_) => {
996 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1008 check_specialization_validity(
1012 impl_id.to_def_id(),
1016 report_mismatch_error(
1018 ty_trait_item.def_id,
1026 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1027 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1029 // Check for missing items from trait
1030 let mut missing_items = Vec::new();
1031 for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
1032 let is_implemented = ancestors
1033 .leaf_def(tcx, trait_item.ident, trait_item.kind)
1034 .map(|node_item| !node_item.defining_node.is_from_trait())
1037 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1038 if !trait_item.defaultness.has_value() {
1039 missing_items.push(*trait_item);
1044 if !missing_items.is_empty() {
1045 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1052 fn report_mismatch_error<'tcx>(
1054 trait_item_def_id: DefId,
1055 impl_trait_ref: ty::TraitRef<'tcx>,
1056 impl_item: &hir::ImplItem<'_>,
1057 ty_impl_item: &ty::AssocItem,
1059 let mut err = match impl_item.kind {
1060 hir::ImplItemKind::Const(..) => {
1061 // Find associated const definition.
1066 "item `{}` is an associated const, which doesn't match its trait `{}`",
1068 impl_trait_ref.print_only_trait_path()
1072 hir::ImplItemKind::Fn(..) => {
1077 "item `{}` is an associated method, which doesn't match its trait `{}`",
1079 impl_trait_ref.print_only_trait_path()
1083 hir::ImplItemKind::TyAlias(_) => {
1088 "item `{}` is an associated type, which doesn't match its trait `{}`",
1090 impl_trait_ref.print_only_trait_path()
1095 err.span_label(impl_item.span, "does not match trait");
1096 if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) {
1097 err.span_label(trait_span, "item in trait");
1102 /// Checks whether a type can be represented in memory. In particular, it
1103 /// identifies types that contain themselves without indirection through a
1104 /// pointer, which would mean their size is unbounded.
1105 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1106 let rty = tcx.type_of(item_def_id);
1108 // Check that it is possible to represent this type. This call identifies
1109 // (1) types that contain themselves and (2) types that contain a different
1110 // recursive type. It is only necessary to throw an error on those that
1111 // contain themselves. For case 2, there must be an inner type that will be
1112 // caught by case 1.
1113 match rty.is_representable(tcx, sp) {
1114 Representability::SelfRecursive(spans) => {
1115 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1118 Representability::Representable | Representability::ContainsRecursive => (),
1123 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1124 let t = tcx.type_of(def_id);
1125 if let ty::Adt(def, substs) = t.kind() {
1126 if def.is_struct() {
1127 let fields = &def.non_enum_variant().fields;
1128 if fields.is_empty() {
1129 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1132 let e = fields[0].ty(tcx, substs);
1133 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1134 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1135 .span_label(sp, "SIMD elements must have the same type")
1140 let len = if let ty::Array(_ty, c) = e.kind() {
1141 c.try_eval_usize(tcx, tcx.param_env(def.did))
1143 Some(fields.len() as u64)
1145 if let Some(len) = len {
1147 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1149 } else if !len.is_power_of_two() {
1154 "SIMD vector length must be a power of two"
1158 } else if len > MAX_SIMD_LANES {
1163 "SIMD vector cannot have more than {} elements",
1172 ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ }
1173 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1174 ty::Array(ty, _c) if ty.is_machine() => { /* struct([f32; 4]) */ }
1180 "SIMD vector element type should be a \
1181 primitive scalar (integer/float/pointer) type"
1191 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1192 let repr = def.repr;
1194 for attr in tcx.get_attrs(def.did).iter() {
1195 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1196 if let attr::ReprPacked(pack) = r {
1197 if let Some(repr_pack) = repr.pack {
1198 if pack as u64 != repr_pack.bytes() {
1203 "type has conflicting packed representation hints"
1211 if repr.align.is_some() {
1216 "type has conflicting packed and align representation hints"
1220 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1221 let mut err = struct_span_err!(
1225 "packed type cannot transitively contain a `#[repr(align)]` type"
1229 tcx.def_span(def_spans[0].0),
1231 "`{}` has a `#[repr(align)]` attribute",
1232 tcx.item_name(def_spans[0].0)
1236 if def_spans.len() > 2 {
1237 let mut first = true;
1238 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1239 let ident = tcx.item_name(*adt_def);
1244 "`{}` contains a field of type `{}`",
1245 tcx.type_of(def.did),
1249 format!("...which contains a field of type `{}`", ident)
1262 pub(super) fn check_packed_inner(
1265 stack: &mut Vec<DefId>,
1266 ) -> Option<Vec<(DefId, Span)>> {
1267 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1268 if def.is_struct() || def.is_union() {
1269 if def.repr.align.is_some() {
1270 return Some(vec![(def.did, DUMMY_SP)]);
1274 for field in &def.non_enum_variant().fields {
1275 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1276 if !stack.contains(&def.did) {
1277 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1278 defs.push((def.did, field.ident.span));
1291 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1292 if !adt.repr.transparent() {
1295 let sp = tcx.sess.source_map().guess_head_span(sp);
1297 if adt.is_union() && !tcx.features().transparent_unions {
1299 &tcx.sess.parse_sess,
1300 sym::transparent_unions,
1302 "transparent unions are unstable",
1307 if adt.variants.len() != 1 {
1308 bad_variant_count(tcx, adt, sp, adt.did);
1309 if adt.variants.is_empty() {
1310 // Don't bother checking the fields. No variants (and thus no fields) exist.
1315 // For each field, figure out if it's known to be a ZST and align(1)
1316 let field_infos = adt.all_fields().map(|field| {
1317 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1318 let param_env = tcx.param_env(field.did);
1319 let layout = tcx.layout_of(param_env.and(ty));
1320 // We are currently checking the type this field came from, so it must be local
1321 let span = tcx.hir().span_if_local(field.did).unwrap();
1322 let zst = layout.map_or(false, |layout| layout.is_zst());
1323 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1327 let non_zst_fields =
1328 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1329 let non_zst_count = non_zst_fields.clone().count();
1330 if non_zst_count != 1 {
1331 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1333 for (span, zst, align1) in field_infos {
1339 "zero-sized field in transparent {} has alignment larger than 1",
1342 .span_label(span, "has alignment larger than 1")
1348 #[allow(trivial_numeric_casts)]
1349 pub fn check_enum<'tcx>(
1352 vs: &'tcx [hir::Variant<'tcx>],
1355 let def_id = tcx.hir().local_def_id(id);
1356 let def = tcx.adt_def(def_id);
1357 def.destructor(tcx); // force the destructor to be evaluated
1360 let attributes = tcx.get_attrs(def_id.to_def_id());
1361 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1366 "unsupported representation for zero-variant enum"
1368 .span_label(sp, "zero-variant enum")
1373 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1374 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1375 if !tcx.features().repr128 {
1377 &tcx.sess.parse_sess,
1380 "repr with 128-bit type is unstable",
1387 if let Some(ref e) = v.disr_expr {
1388 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1392 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1393 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1395 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1396 let has_non_units = vs.iter().any(|var| !is_unit(var));
1397 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1398 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1400 if disr_non_unit || (disr_units && has_non_units) {
1402 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1407 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1408 for ((_, discr), v) in def.discriminants(tcx).zip(vs) {
1409 // Check for duplicate discriminant values
1410 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1411 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1412 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1413 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1414 let i_span = match variant_i.disr_expr {
1415 Some(ref expr) => tcx.hir().span(expr.hir_id),
1416 None => tcx.hir().span(variant_i_hir_id),
1418 let span = match v.disr_expr {
1419 Some(ref expr) => tcx.hir().span(expr.hir_id),
1426 "discriminant value `{}` already exists",
1429 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1430 .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1433 disr_vals.push(discr);
1436 check_representable(tcx, sp, def_id);
1437 check_transparent(tcx, sp, def);
1440 pub(super) fn check_type_params_are_used<'tcx>(
1442 generics: &ty::Generics,
1445 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1447 assert_eq!(generics.parent, None);
1449 if generics.own_counts().types == 0 {
1453 let mut params_used = BitSet::new_empty(generics.params.len());
1455 if ty.references_error() {
1456 // If there is already another error, do not emit
1457 // an error for not using a type parameter.
1458 assert!(tcx.sess.has_errors());
1462 for leaf in ty.walk() {
1463 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1464 if let ty::Param(param) = leaf_ty.kind() {
1465 debug!("found use of ty param {:?}", param);
1466 params_used.insert(param.index);
1471 for param in &generics.params {
1472 if !params_used.contains(param.index) {
1473 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1474 let span = tcx.def_span(param.def_id);
1479 "type parameter `{}` is unused",
1482 .span_label(span, "unused type parameter")
1489 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1490 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1493 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1494 wfcheck::check_item_well_formed(tcx, def_id);
1497 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1498 wfcheck::check_trait_item(tcx, def_id);
1501 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1502 wfcheck::check_impl_item(tcx, def_id);
1505 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1506 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1507 .span_label(span, "recursive `async fn`")
1508 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1510 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1515 /// Emit an error for recursive opaque types.
1517 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1518 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1521 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1522 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1523 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1524 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1526 let mut label = false;
1527 if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1528 let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1532 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1533 .all(|ty| matches!(ty.kind(), ty::Never))
1538 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1539 .map(|expr| expr.span)
1540 .collect::<Vec<Span>>();
1541 let span_len = spans.len();
1543 err.span_label(spans[0], "this returned value is of `!` type");
1545 let mut multispan: MultiSpan = spans.clone().into();
1548 .push_span_label(span, "this returned value is of `!` type".to_string());
1550 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1552 err.help("this error will resolve once the item's body returns a concrete type");
1554 let mut seen = FxHashSet::default();
1556 err.span_label(span, "recursive opaque type");
1558 for (sp, ty) in visitor
1561 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1562 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1564 struct VisitTypes(Vec<DefId>);
1565 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1566 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1568 ty::Opaque(def, _) => {
1570 ControlFlow::CONTINUE
1572 _ => t.super_visit_with(self),
1576 let mut visitor = VisitTypes(vec![]);
1577 ty.visit_with(&mut visitor);
1578 for def_id in visitor.0 {
1579 let ty_span = tcx.def_span(def_id);
1580 if !seen.contains(&ty_span) {
1581 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1582 seen.insert(ty_span);
1584 err.span_label(sp, &format!("returning here with type `{}`", ty));
1590 err.span_label(span, "cannot resolve opaque type");
1595 struct SelfTySpanVisitor<'tcx> {
1597 selfty_spans: Vec<Span>,
1600 impl Visitor<'tcx> for SelfTySpanVisitor<'tcx> {
1601 type Map = rustc_middle::hir::map::Map<'tcx>;
1603 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1604 hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
1607 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
1609 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
1611 if segment.res.map(|res| matches!(res, Res::SelfTy(_, _))).unwrap_or(false) =>
1613 self.selfty_spans.push(path.span);
1619 hir::intravisit::walk_ty(self, arg);