1 use super::coercion::CoerceMany;
2 use super::compare_method::check_type_bounds;
3 use super::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl};
6 use rustc_attr as attr;
7 use rustc_errors::{Applicability, ErrorReported};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::lang_items::LangItem;
12 use rustc_hir::{def::Res, ItemKind, Node, PathSegment};
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
15 use rustc_middle::hir::nested_filter;
16 use rustc_middle::ty::fold::TypeFoldable;
17 use rustc_middle::ty::layout::MAX_SIMD_LANES;
18 use rustc_middle::ty::subst::GenericArgKind;
19 use rustc_middle::ty::util::{Discr, IntTypeExt};
20 use rustc_middle::ty::{self, OpaqueTypeKey, ParamEnv, Ty, TyCtxt};
21 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
22 use rustc_span::symbol::sym;
23 use rustc_span::{self, MultiSpan, Span};
24 use rustc_target::spec::abi::Abi;
25 use rustc_trait_selection::traits;
26 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
27 use rustc_ty_utils::representability::{self, Representability};
30 use std::ops::ControlFlow;
32 pub fn check_wf_new(tcx: TyCtxt<'_>) {
33 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
34 tcx.hir().par_visit_all_item_likes(&visit);
37 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
38 match tcx.sess.target.is_abi_supported(abi) {
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 #[instrument(skip(inherited, body), level = "debug")]
74 pub(super) fn check_fn<'a, 'tcx>(
75 inherited: &'a Inherited<'a, 'tcx>,
76 param_env: ty::ParamEnv<'tcx>,
77 fn_sig: ty::FnSig<'tcx>,
78 decl: &'tcx hir::FnDecl<'tcx>,
80 body: &'tcx hir::Body<'tcx>,
81 can_be_generator: Option<hir::Movability>,
82 return_type_pre_known: bool,
83 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
84 let mut fn_sig = fn_sig;
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));
90 fcx.return_type_pre_known = return_type_pre_known;
96 let declared_ret_ty = fn_sig.output();
99 fcx.instantiate_opaque_types_from_value(declared_ret_ty, decl.output.span());
100 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
101 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
102 fcx.ret_type_span = Some(decl.output.span());
103 if let ty::Opaque(..) = declared_ret_ty.kind() {
104 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
106 fn_sig = tcx.mk_fn_sig(
107 fn_sig.inputs().iter().cloned(),
114 let span = body.value.span;
116 fn_maybe_err(tcx, span, fn_sig.abi);
118 if fn_sig.abi == Abi::RustCall {
119 let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
122 let item = match tcx.hir().get(fn_id) {
123 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
124 Node::ImplItem(hir::ImplItem {
125 kind: hir::ImplItemKind::Fn(header, ..), ..
127 Node::TraitItem(hir::TraitItem {
128 kind: hir::TraitItemKind::Fn(header, ..),
131 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
132 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
133 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
136 if let Some(header) = item {
137 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple")
141 if fn_sig.inputs().len() != expected_args {
144 // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
145 // This will probably require wide-scale changes to support a TupleKind obligation
146 // We can't resolve this without knowing the type of the param
147 if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
153 if body.generator_kind.is_some() && can_be_generator.is_some() {
155 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
156 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
158 // Resume type defaults to `()` if the generator has no argument.
159 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
161 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
164 GatherLocalsVisitor::new(&fcx).visit_body(body);
166 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
167 // (as it's created inside the body itself, not passed in from outside).
168 let maybe_va_list = if fn_sig.c_variadic {
169 let span = body.params.last().unwrap().span;
170 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
171 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
173 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
178 // Add formal parameters.
179 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
180 let inputs_fn = fn_sig.inputs().iter().copied();
181 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
182 // Check the pattern.
183 let ty_span = try { inputs_hir?.get(idx)?.span };
184 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
186 // Check that argument is Sized.
187 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
188 // for simple cases like `fn foo(x: Trait)`,
189 // where we would error once on the parameter as a whole, and once on the binding `x`.
190 if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
191 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
194 fcx.write_ty(param.hir_id, param_ty);
197 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
199 fcx.in_tail_expr = true;
200 if let ty::Dynamic(..) = declared_ret_ty.kind() {
201 // FIXME: We need to verify that the return type is `Sized` after the return expression has
202 // been evaluated so that we have types available for all the nodes being returned, but that
203 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
204 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
205 // while keeping the current ordering we will ignore the tail expression's type because we
206 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
207 // because we will trigger "unreachable expression" lints unconditionally.
208 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
209 // case that a newcomer might make, returning a bare trait, and in that case we populate
210 // the tail expression's type so that the suggestion will be correct, but ignore all other
212 fcx.check_expr(&body.value);
213 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
215 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
216 fcx.check_return_expr(&body.value, false);
218 fcx.in_tail_expr = false;
220 // We insert the deferred_generator_interiors entry after visiting the body.
221 // This ensures that all nested generators appear before the entry of this generator.
222 // resolve_generator_interiors relies on this property.
223 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
225 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
226 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
228 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
229 Some(GeneratorTypes {
233 movability: can_be_generator.unwrap(),
239 // Finalize the return check by taking the LUB of the return types
240 // we saw and assigning it to the expected return type. This isn't
241 // really expected to fail, since the coercions would have failed
242 // earlier when trying to find a LUB.
243 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
244 let mut actual_return_ty = coercion.complete(&fcx);
245 debug!("actual_return_ty = {:?}", actual_return_ty);
246 if let ty::Dynamic(..) = declared_ret_ty.kind() {
247 // We have special-cased the case where the function is declared
248 // `-> dyn Foo` and we don't actually relate it to the
249 // `fcx.ret_coercion`, so just substitute a type variable.
251 fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
252 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
254 fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty);
256 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
257 if let Some(panic_impl_did) = tcx.lang_items().panic_impl() {
258 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
259 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
260 if *declared_ret_ty.kind() != ty::Never {
261 sess.span_err(decl.output.span(), "return type should be `!`");
264 let inputs = fn_sig.inputs();
265 let span = hir.span(fn_id);
266 if inputs.len() == 1 {
267 let arg_is_panic_info = match *inputs[0].kind() {
268 ty::Ref(region, ty, mutbl) => match *ty.kind() {
269 ty::Adt(ref adt, _) => {
270 adt.did == panic_info_did
271 && mutbl == hir::Mutability::Not
272 && !region.is_static()
279 if !arg_is_panic_info {
280 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
283 if let Node::Item(item) = hir.get(fn_id) {
284 if let ItemKind::Fn(_, ref generics, _) = item.kind {
285 if !generics.params.is_empty() {
286 sess.span_err(span, "should have no type parameters");
291 let span = sess.source_map().guess_head_span(span);
292 sess.span_err(span, "function should have one argument");
295 sess.err("language item required, but not found: `panic_info`");
300 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
301 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
302 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
303 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
304 if *declared_ret_ty.kind() != ty::Never {
305 sess.span_err(decl.output.span(), "return type should be `!`");
308 let inputs = fn_sig.inputs();
309 let span = hir.span(fn_id);
310 if inputs.len() == 1 {
311 let arg_is_alloc_layout = match inputs[0].kind() {
312 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
316 if !arg_is_alloc_layout {
317 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
320 if let Node::Item(item) = hir.get(fn_id) {
321 if let ItemKind::Fn(_, ref generics, _) = item.kind {
322 if !generics.params.is_empty() {
325 "`#[alloc_error_handler]` function should have no type \
332 let span = sess.source_map().guess_head_span(span);
333 sess.span_err(span, "function should have one argument");
336 sess.err("language item required, but not found: `alloc_layout`");
344 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
345 let def = tcx.adt_def(def_id);
346 def.destructor(tcx); // force the destructor to be evaluated
347 check_representable(tcx, span, def_id);
350 check_simd(tcx, span, def_id);
353 check_transparent(tcx, span, def);
354 check_packed(tcx, span, def);
357 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
358 let def = tcx.adt_def(def_id);
359 def.destructor(tcx); // force the destructor to be evaluated
360 check_representable(tcx, span, def_id);
361 check_transparent(tcx, span, def);
362 check_union_fields(tcx, span, def_id);
363 check_packed(tcx, span, def);
366 /// Check that the fields of the `union` do not need dropping.
367 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
368 let item_type = tcx.type_of(item_def_id);
369 if let ty::Adt(def, substs) = item_type.kind() {
370 assert!(def.is_union());
371 let fields = &def.non_enum_variant().fields;
372 let param_env = tcx.param_env(item_def_id);
373 for field in fields {
374 let field_ty = field.ty(tcx, substs);
375 if field_ty.needs_drop(tcx, param_env) {
376 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
377 // We are currently checking the type this field came from, so it must be local.
378 Some(Node::Field(field)) => (field.span, field.ty.span),
379 _ => unreachable!("mir field has to correspond to hir field"),
385 "unions cannot contain fields that may need dropping"
388 "a type is guaranteed not to need dropping \
389 when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
391 .multipart_suggestion_verbose(
392 "when the type does not implement `Copy`, \
393 wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
395 (ty_span.shrink_to_lo(), format!("std::mem::ManuallyDrop<")),
396 (ty_span.shrink_to_hi(), ">".into()),
398 Applicability::MaybeIncorrect,
405 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
410 /// Check that a `static` is inhabited.
411 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
412 // Make sure statics are inhabited.
413 // Other parts of the compiler assume that there are no uninhabited places. In principle it
414 // would be enough to check this for `extern` statics, as statics with an initializer will
415 // have UB during initialization if they are uninhabited, but there also seems to be no good
416 // reason to allow any statics to be uninhabited.
417 let ty = tcx.type_of(def_id);
418 let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
421 // Generic statics are rejected, but we still reach this case.
422 tcx.sess.delay_span_bug(span, "generic static must be rejected");
426 if layout.abi.is_uninhabited() {
427 tcx.struct_span_lint_hir(
429 tcx.hir().local_def_id_to_hir_id(def_id),
432 lint.build("static of uninhabited type")
433 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
440 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
441 /// projections that would result in "inheriting lifetimes".
442 pub(super) fn check_opaque<'tcx>(
445 substs: SubstsRef<'tcx>,
447 origin: &hir::OpaqueTyOrigin,
449 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
450 if tcx.type_of(def_id).references_error() {
453 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
456 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
459 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
460 /// in "inheriting lifetimes".
461 #[instrument(level = "debug", skip(tcx, span))]
462 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
467 let item = tcx.hir().expect_item(def_id);
468 debug!(?item, ?span);
470 struct FoundParentLifetime;
471 struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
472 impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
473 type BreakTy = FoundParentLifetime;
475 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
476 debug!("FindParentLifetimeVisitor: r={:?}", r);
477 if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
478 if index < self.0.parent_count as u32 {
479 return ControlFlow::Break(FoundParentLifetime);
481 return ControlFlow::CONTINUE;
485 r.super_visit_with(self)
488 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
489 if let ty::ConstKind::Unevaluated(..) = c.val() {
490 // FIXME(#72219) We currently don't detect lifetimes within substs
491 // which would violate this check. Even though the particular substitution is not used
492 // within the const, this should still be fixed.
493 return ControlFlow::CONTINUE;
495 c.super_visit_with(self)
499 struct ProhibitOpaqueVisitor<'tcx> {
501 opaque_identity_ty: Ty<'tcx>,
502 generics: &'tcx ty::Generics,
503 selftys: Vec<(Span, Option<String>)>,
506 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
507 type BreakTy = Ty<'tcx>;
509 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
510 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
511 if t == self.opaque_identity_ty {
512 ControlFlow::CONTINUE
514 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
515 .map_break(|FoundParentLifetime| t)
520 impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
521 type NestedFilter = nested_filter::OnlyBodies;
523 fn nested_visit_map(&mut self) -> Self::Map {
527 fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
529 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
532 res: Some(Res::SelfTy { trait_: _, alias_to: impl_ref }),
537 impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
538 self.selftys.push((path.span, impl_ty_name));
544 hir::intravisit::walk_ty(self, arg);
548 if let ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(..), .. }) =
551 let mut visitor = ProhibitOpaqueVisitor {
552 opaque_identity_ty: tcx.mk_opaque(
554 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
556 generics: tcx.generics_of(def_id),
560 let prohibit_opaque = tcx
561 .explicit_item_bounds(def_id)
563 .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
565 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
566 prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
569 if let Some(ty) = prohibit_opaque.break_value() {
570 visitor.visit_item(&item);
572 let mut err = struct_span_err!(
576 "`impl Trait` return type cannot contain a projection or `Self` that references lifetimes from \
580 for (span, name) in visitor.selftys {
583 "consider spelling out the type instead",
584 name.unwrap_or_else(|| format!("{:?}", ty)),
585 Applicability::MaybeIncorrect,
593 /// Checks that an opaque type does not contain cycles.
594 pub(super) fn check_opaque_for_cycles<'tcx>(
597 substs: SubstsRef<'tcx>,
599 origin: &hir::OpaqueTyOrigin,
600 ) -> Result<(), ErrorReported> {
601 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
603 hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
604 _ => opaque_type_cycle_error(tcx, def_id, span),
612 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
614 /// This is mostly checked at the places that specify the opaque type, but we
615 /// check those cases in the `param_env` of that function, which may have
616 /// bounds not on this opaque type:
618 /// type X<T> = impl Clone
619 /// fn f<T: Clone>(t: T) -> X<T> {
623 /// Without this check the above code is incorrectly accepted: we would ICE if
624 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
625 #[instrument(level = "debug", skip(tcx))]
626 fn check_opaque_meets_bounds<'tcx>(
629 substs: SubstsRef<'tcx>,
631 origin: &hir::OpaqueTyOrigin,
633 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
634 let defining_use_anchor = match *origin {
635 hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
636 hir::OpaqueTyOrigin::TyAlias => def_id,
638 let param_env = tcx.param_env(defining_use_anchor);
640 tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
641 let inh = Inherited::new(infcx, def_id);
642 let infcx = &inh.infcx;
643 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
645 let misc_cause = traits::ObligationCause::misc(span, hir_id);
647 let _ = inh.register_infer_ok_obligations(
648 infcx.instantiate_opaque_types(hir_id, param_env, opaque_ty, span),
651 let opaque_type_map = infcx.inner.borrow().opaque_types.clone();
652 for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map {
653 let hidden_type = tcx.type_of(def_id).subst(tcx, substs);
654 trace!(?hidden_type);
655 match infcx.at(&misc_cause, param_env).eq(opaque_defn.concrete_ty, hidden_type) {
656 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
657 Err(ty_err) => tcx.sess.delay_span_bug(
660 "could not check bounds on revealed type `{}`:\n{}",
667 // Check that all obligations are satisfied by the implementation's
669 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
670 if !errors.is_empty() {
671 infcx.report_fulfillment_errors(&errors, None, false);
675 // Checked when type checking the function containing them.
676 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return,
677 // Can have different predicates to their defining use
678 hir::OpaqueTyOrigin::TyAlias => {
679 // Finally, resolve all regions. This catches wily misuses of
680 // lifetime parameters.
681 let fcx = FnCtxt::new(&inh, param_env, hir_id);
682 fcx.regionck_item(hir_id, span, FxHashSet::default());
688 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
690 "check_item_type(it.def_id={:?}, it.name={})",
692 tcx.def_path_str(it.def_id.to_def_id())
694 let _indenter = indenter();
696 // Consts can play a role in type-checking, so they are included here.
697 hir::ItemKind::Static(..) => {
698 tcx.ensure().typeck(it.def_id);
699 maybe_check_static_with_link_section(tcx, it.def_id, it.span);
700 check_static_inhabited(tcx, it.def_id, it.span);
702 hir::ItemKind::Const(..) => {
703 tcx.ensure().typeck(it.def_id);
705 hir::ItemKind::Enum(ref enum_definition, _) => {
706 check_enum(tcx, it.span, &enum_definition.variants, it.def_id);
708 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
709 hir::ItemKind::Impl(ref impl_) => {
710 debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
711 if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
712 check_impl_items_against_trait(
719 let trait_def_id = impl_trait_ref.def_id;
720 check_on_unimplemented(tcx, trait_def_id, it);
723 hir::ItemKind::Trait(_, _, _, _, ref items) => {
724 check_on_unimplemented(tcx, it.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 assoc_item = tcx.associated_item(item.def_id);
736 InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
737 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
742 ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
749 hir::ItemKind::Struct(..) => {
750 check_struct(tcx, it.def_id, it.span);
752 hir::ItemKind::Union(..) => {
753 check_union(tcx, it.def_id, it.span);
755 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
756 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
757 // `async-std` (and `pub async fn` in general).
758 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
759 // See https://github.com/rust-lang/rust/issues/75100
760 if !tcx.sess.opts.actually_rustdoc {
761 let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
762 check_opaque(tcx, it.def_id, substs, it.span, &origin);
765 hir::ItemKind::TyAlias(..) => {
766 let pty_ty = tcx.type_of(it.def_id);
767 let generics = tcx.generics_of(it.def_id);
768 check_type_params_are_used(tcx, &generics, pty_ty);
770 hir::ItemKind::ForeignMod { abi, items } => {
771 check_abi(tcx, it.hir_id(), it.span, abi);
773 if abi == Abi::RustIntrinsic {
775 let item = tcx.hir().foreign_item(item.id);
776 intrinsic::check_intrinsic_type(tcx, item);
778 } else if abi == Abi::PlatformIntrinsic {
780 let item = tcx.hir().foreign_item(item.id);
781 intrinsic::check_platform_intrinsic_type(tcx, item);
785 let def_id = item.id.def_id;
786 let generics = tcx.generics_of(def_id);
787 let own_counts = generics.own_counts();
788 if generics.params.len() - own_counts.lifetimes != 0 {
789 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
790 (_, 0) => ("type", "types", Some("u32")),
791 // We don't specify an example value, because we can't generate
792 // a valid value for any type.
793 (0, _) => ("const", "consts", None),
794 _ => ("type or const", "types or consts", None),
800 "foreign items may not have {} parameters",
803 .span_label(item.span, &format!("can't have {} parameters", kinds))
805 // FIXME: once we start storing spans for type arguments, turn this
806 // into a suggestion.
808 "replace the {} parameters with concrete {}{}",
811 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
817 let item = tcx.hir().foreign_item(item.id);
819 hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
820 require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
822 hir::ForeignItemKind::Static(..) => {
823 check_static_inhabited(tcx, def_id, item.span);
830 _ => { /* nothing to do */ }
834 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
835 // an error would be reported if this fails.
836 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
839 pub(super) fn check_specialization_validity<'tcx>(
841 trait_def: &ty::TraitDef,
842 trait_item: &ty::AssocItem,
844 impl_item: &hir::ImplItemRef,
846 let ancestors = match trait_def.ancestors(tcx, impl_id) {
847 Ok(ancestors) => ancestors,
850 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
851 if parent.is_from_trait() {
854 Some((parent, parent.item(tcx, trait_item.def_id)))
858 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
860 // Parent impl exists, and contains the parent item we're trying to specialize, but
861 // doesn't mark it `default`.
862 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
863 Some(Err(parent_impl.def_id()))
866 // Parent impl contains item and makes it specializable.
867 Some(_) => Some(Ok(())),
869 // Parent impl doesn't mention the item. This means it's inherited from the
870 // grandparent. In that case, if parent is a `default impl`, inherited items use the
871 // "defaultness" from the grandparent, else they are final.
873 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
876 Some(Err(parent_impl.def_id()))
882 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
883 // item. This is allowed, the item isn't actually getting specialized here.
884 let result = opt_result.unwrap_or(Ok(()));
886 if let Err(parent_impl) = result {
887 report_forbidden_specialization(tcx, impl_item, parent_impl);
891 fn check_impl_items_against_trait<'tcx>(
893 full_impl_span: Span,
895 impl_trait_ref: ty::TraitRef<'tcx>,
896 impl_item_refs: &[hir::ImplItemRef],
898 // If the trait reference itself is erroneous (so the compilation is going
899 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
900 // isn't populated for such impls.
901 if impl_trait_ref.references_error() {
905 // Negative impls are not expected to have any items
906 match tcx.impl_polarity(impl_id) {
907 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
908 ty::ImplPolarity::Negative => {
909 if let [first_item_ref, ..] = impl_item_refs {
910 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
915 "negative impls cannot have any items"
923 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
925 for impl_item in impl_item_refs {
926 let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
927 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
928 tcx.associated_item(trait_item_id)
930 // Checked in `associated_item`.
931 tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
934 let impl_item_full = tcx.hir().impl_item(impl_item.id);
935 match impl_item_full.kind {
936 hir::ImplItemKind::Const(..) => {
937 // Find associated const definition.
946 hir::ImplItemKind::Fn(..) => {
947 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
957 hir::ImplItemKind::TyAlias(impl_ty) => {
958 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
970 check_specialization_validity(
979 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
980 // Check for missing items from trait
981 let mut missing_items = Vec::new();
983 let mut must_implement_one_of: Option<&[Ident]> =
984 trait_def.must_implement_one_of.as_deref();
986 for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
987 let is_implemented = ancestors
988 .leaf_def(tcx, trait_item_id)
989 .map_or(false, |node_item| node_item.item.defaultness.has_value());
991 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
992 missing_items.push(tcx.associated_item(trait_item_id));
995 if let Some(required_items) = &must_implement_one_of {
996 // true if this item is specifically implemented in this impl
997 let is_implemented_here = ancestors
998 .leaf_def(tcx, trait_item_id)
999 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1001 if is_implemented_here {
1002 let trait_item = tcx.associated_item(trait_item_id);
1003 if required_items.contains(&trait_item.ident(tcx)) {
1004 must_implement_one_of = None;
1010 if !missing_items.is_empty() {
1011 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1012 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1015 if let Some(missing_items) = must_implement_one_of {
1016 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1018 .get_attrs(impl_trait_ref.def_id)
1020 .find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1021 .map(|attr| attr.span);
1023 missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1028 /// Checks whether a type can be represented in memory. In particular, it
1029 /// identifies types that contain themselves without indirection through a
1030 /// pointer, which would mean their size is unbounded.
1031 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1032 let rty = tcx.type_of(item_def_id);
1034 // Check that it is possible to represent this type. This call identifies
1035 // (1) types that contain themselves and (2) types that contain a different
1036 // recursive type. It is only necessary to throw an error on those that
1037 // contain themselves. For case 2, there must be an inner type that will be
1038 // caught by case 1.
1039 match representability::ty_is_representable(tcx, rty, sp) {
1040 Representability::SelfRecursive(spans) => {
1041 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1044 Representability::Representable | Representability::ContainsRecursive => (),
1049 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1050 let t = tcx.type_of(def_id);
1051 if let ty::Adt(def, substs) = t.kind() {
1052 if def.is_struct() {
1053 let fields = &def.non_enum_variant().fields;
1054 if fields.is_empty() {
1055 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1058 let e = fields[0].ty(tcx, substs);
1059 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1060 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1061 .span_label(sp, "SIMD elements must have the same type")
1066 let len = if let ty::Array(_ty, c) = e.kind() {
1067 c.try_eval_usize(tcx, tcx.param_env(def.did))
1069 Some(fields.len() as u64)
1071 if let Some(len) = len {
1073 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1075 } else if len > MAX_SIMD_LANES {
1080 "SIMD vector cannot have more than {} elements",
1088 // Check that we use types valid for use in the lanes of a SIMD "vector register"
1089 // These are scalar types which directly match a "machine" type
1090 // Yes: Integers, floats, "thin" pointers
1091 // No: char, "fat" pointers, compound types
1093 ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1094 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1095 ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1099 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1101 { /* struct([f32; 4]) is ok */ }
1107 "SIMD vector element type should be a \
1108 primitive scalar (integer/float/pointer) type"
1118 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1119 let repr = def.repr;
1121 for attr in tcx.get_attrs(def.did).iter() {
1122 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1123 if let attr::ReprPacked(pack) = r {
1124 if let Some(repr_pack) = repr.pack {
1125 if pack as u64 != repr_pack.bytes() {
1130 "type has conflicting packed representation hints"
1138 if repr.align.is_some() {
1143 "type has conflicting packed and align representation hints"
1147 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1148 let mut err = struct_span_err!(
1152 "packed type cannot transitively contain a `#[repr(align)]` type"
1156 tcx.def_span(def_spans[0].0),
1158 "`{}` has a `#[repr(align)]` attribute",
1159 tcx.item_name(def_spans[0].0)
1163 if def_spans.len() > 2 {
1164 let mut first = true;
1165 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1166 let ident = tcx.item_name(*adt_def);
1171 "`{}` contains a field of type `{}`",
1172 tcx.type_of(def.did),
1176 format!("...which contains a field of type `{}`", ident)
1189 pub(super) fn check_packed_inner(
1192 stack: &mut Vec<DefId>,
1193 ) -> Option<Vec<(DefId, Span)>> {
1194 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1195 if def.is_struct() || def.is_union() {
1196 if def.repr.align.is_some() {
1197 return Some(vec![(def.did, DUMMY_SP)]);
1201 for field in &def.non_enum_variant().fields {
1202 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1203 if !stack.contains(&def.did) {
1204 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1205 defs.push((def.did, field.ident(tcx).span));
1218 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1219 if !adt.repr.transparent() {
1222 let sp = tcx.sess.source_map().guess_head_span(sp);
1224 if adt.is_union() && !tcx.features().transparent_unions {
1226 &tcx.sess.parse_sess,
1227 sym::transparent_unions,
1229 "transparent unions are unstable",
1234 if adt.variants.len() != 1 {
1235 bad_variant_count(tcx, adt, sp, adt.did);
1236 if adt.variants.is_empty() {
1237 // Don't bother checking the fields. No variants (and thus no fields) exist.
1242 // For each field, figure out if it's known to be a ZST and align(1)
1243 let field_infos = adt.all_fields().map(|field| {
1244 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1245 let param_env = tcx.param_env(field.did);
1246 let layout = tcx.layout_of(param_env.and(ty));
1247 // We are currently checking the type this field came from, so it must be local
1248 let span = tcx.hir().span_if_local(field.did).unwrap();
1249 let zst = layout.map_or(false, |layout| layout.is_zst());
1250 let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1254 let non_zst_fields =
1255 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1256 let non_zst_count = non_zst_fields.clone().count();
1257 if non_zst_count >= 2 {
1258 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1260 for (span, zst, align1) in field_infos {
1266 "zero-sized field in transparent {} has alignment larger than 1",
1269 .span_label(span, "has alignment larger than 1")
1275 #[allow(trivial_numeric_casts)]
1276 fn check_enum<'tcx>(
1279 vs: &'tcx [hir::Variant<'tcx>],
1282 let def = tcx.adt_def(def_id);
1283 def.destructor(tcx); // force the destructor to be evaluated
1286 let attributes = tcx.get_attrs(def_id.to_def_id());
1287 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1292 "unsupported representation for zero-variant enum"
1294 .span_label(sp, "zero-variant enum")
1299 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1300 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1301 if !tcx.features().repr128 {
1303 &tcx.sess.parse_sess,
1306 "repr with 128-bit type is unstable",
1313 if let Some(ref e) = v.disr_expr {
1314 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1318 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1319 let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1321 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1322 let has_non_units = vs.iter().any(|var| !is_unit(var));
1323 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1324 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1326 if disr_non_unit || (disr_units && has_non_units) {
1328 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1333 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1334 for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1335 // Check for duplicate discriminant values
1336 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1337 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1338 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1339 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1340 let i_span = match variant_i.disr_expr {
1341 Some(ref expr) => tcx.hir().span(expr.hir_id),
1342 None => tcx.def_span(variant_did),
1344 let span = match v.disr_expr {
1345 Some(ref expr) => tcx.hir().span(expr.hir_id),
1348 let display_discr = display_discriminant_value(tcx, v, discr.val);
1349 let display_discr_i = display_discriminant_value(tcx, variant_i, disr_vals[i].val);
1354 "discriminant value `{}` already exists",
1357 .span_label(i_span, format!("first use of {}", display_discr_i))
1358 .span_label(span, format!("enum already has {}", display_discr))
1361 disr_vals.push(discr);
1364 check_representable(tcx, sp, def_id);
1365 check_transparent(tcx, sp, def);
1368 /// Format an enum discriminant value for use in a diagnostic message.
1369 fn display_discriminant_value<'tcx>(
1371 variant: &hir::Variant<'_>,
1374 if let Some(expr) = &variant.disr_expr {
1375 let body = &tcx.hir().body(expr.body).value;
1376 if let hir::ExprKind::Lit(lit) = &body.kind {
1377 if let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node {
1378 if evaluated != *lit_value {
1379 return format!("`{}` (overflowed from `{}`)", evaluated, lit_value);
1384 format!("`{}`", evaluated)
1387 pub(super) fn check_type_params_are_used<'tcx>(
1389 generics: &ty::Generics,
1392 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1394 assert_eq!(generics.parent, None);
1396 if generics.own_counts().types == 0 {
1400 let mut params_used = BitSet::new_empty(generics.params.len());
1402 if ty.references_error() {
1403 // If there is already another error, do not emit
1404 // an error for not using a type parameter.
1405 assert!(tcx.sess.has_errors());
1409 for leaf in ty.walk() {
1410 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1411 if let ty::Param(param) = leaf_ty.kind() {
1412 debug!("found use of ty param {:?}", param);
1413 params_used.insert(param.index);
1418 for param in &generics.params {
1419 if !params_used.contains(param.index) {
1420 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1421 let span = tcx.def_span(param.def_id);
1426 "type parameter `{}` is unused",
1429 .span_label(span, "unused type parameter")
1436 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1437 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1440 pub(super) use wfcheck::check_item_well_formed;
1442 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1444 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1446 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) {
1447 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1448 .span_label(span, "recursive `async fn`")
1449 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1451 "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1456 /// Emit an error for recursive opaque types.
1458 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1459 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1462 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1463 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1464 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
1465 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1467 let mut label = false;
1468 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1469 let typeck_results = tcx.typeck(def_id);
1473 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1474 .all(|ty| matches!(ty.kind(), ty::Never))
1479 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1480 .map(|expr| expr.span)
1481 .collect::<Vec<Span>>();
1482 let span_len = spans.len();
1484 err.span_label(spans[0], "this returned value is of `!` type");
1486 let mut multispan: MultiSpan = spans.clone().into();
1489 .push_span_label(span, "this returned value is of `!` type".to_string());
1491 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1493 err.help("this error will resolve once the item's body returns a concrete type");
1495 let mut seen = FxHashSet::default();
1497 err.span_label(span, "recursive opaque type");
1499 for (sp, ty) in visitor
1502 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1503 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1505 struct OpaqueTypeCollector(Vec<DefId>);
1506 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1507 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1509 ty::Opaque(def, _) => {
1511 ControlFlow::CONTINUE
1513 _ => t.super_visit_with(self),
1517 let mut visitor = OpaqueTypeCollector(vec![]);
1518 ty.visit_with(&mut visitor);
1519 for def_id in visitor.0 {
1520 let ty_span = tcx.def_span(def_id);
1521 if !seen.contains(&ty_span) {
1522 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1523 seen.insert(ty_span);
1525 err.span_label(sp, &format!("returning here with type `{}`", ty));
1531 err.span_label(span, "cannot resolve opaque type");