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;
9 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
10 use rustc_hir::lang_items::LangItem;
11 use rustc_hir::{ItemKind, Node};
12 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use rustc_infer::infer::RegionVariableOrigin;
14 use rustc_middle::ty::fold::TypeFoldable;
15 use rustc_middle::ty::subst::GenericArgKind;
16 use rustc_middle::ty::util::{Discr, IntTypeExt, Representability};
17 use rustc_middle::ty::{self, RegionKind, ToPredicate, Ty, TyCtxt};
18 use rustc_session::config::EntryFnType;
19 use rustc_span::symbol::sym;
20 use rustc_span::{self, MultiSpan, Span};
21 use rustc_target::spec::abi::Abi;
22 use rustc_trait_selection::traits::{self, ObligationCauseCode};
24 pub fn check_wf_new(tcx: TyCtxt<'_>) {
25 let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
26 tcx.hir().krate().par_visit_all_item_likes(&visit);
29 pub(super) fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) {
30 if !tcx.sess.target.target.is_abi_supported(abi) {
35 "The ABI `{}` is not supported for the current target",
42 /// Helper used for fns and closures. Does the grungy work of checking a function
43 /// body and returns the function context used for that purpose, since in the case of a fn item
44 /// there is still a bit more to do.
47 /// * inherited: other fields inherited from the enclosing fn (if any)
48 pub(super) fn check_fn<'a, 'tcx>(
49 inherited: &'a Inherited<'a, 'tcx>,
50 param_env: ty::ParamEnv<'tcx>,
51 fn_sig: ty::FnSig<'tcx>,
52 decl: &'tcx hir::FnDecl<'tcx>,
54 body: &'tcx hir::Body<'tcx>,
55 can_be_generator: Option<hir::Movability>,
56 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
57 let mut fn_sig = fn_sig;
59 debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env);
61 // Create the function context. This is either derived from scratch or,
62 // in the case of closures, based on the outer context.
63 let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
64 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
70 let declared_ret_ty = fn_sig.output();
73 fcx.instantiate_opaque_types_from_value(fn_id, &declared_ret_ty, decl.output.span());
74 debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty);
75 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty)));
76 fcx.ret_type_span = Some(decl.output.span());
77 if let ty::Opaque(..) = declared_ret_ty.kind() {
78 fcx.ret_coercion_impl_trait = Some(declared_ret_ty);
80 fn_sig = tcx.mk_fn_sig(
81 fn_sig.inputs().iter().cloned(),
88 let span = body.value.span;
90 fn_maybe_err(tcx, span, fn_sig.abi);
92 if body.generator_kind.is_some() && can_be_generator.is_some() {
94 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
95 fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
97 // Resume type defaults to `()` if the generator has no argument.
98 let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
100 fcx.resume_yield_tys = Some((resume_ty, yield_ty));
103 let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id).to_def_id()).expect_local();
104 let outer_hir_id = hir.local_def_id_to_hir_id(outer_def_id);
105 GatherLocalsVisitor::new(&fcx, outer_hir_id).visit_body(body);
107 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
108 // (as it's created inside the body itself, not passed in from outside).
109 let maybe_va_list = if fn_sig.c_variadic {
110 let span = body.params.last().unwrap().span;
111 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
112 let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
114 Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()]))
119 // Add formal parameters.
120 let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
121 let inputs_fn = fn_sig.inputs().iter().copied();
122 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
123 // Check the pattern.
124 let ty_span = try { inputs_hir?.get(idx)?.span };
125 fcx.check_pat_top(¶m.pat, param_ty, ty_span, false);
127 // Check that argument is Sized.
128 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
129 // for simple cases like `fn foo(x: Trait)`,
130 // where we would error once on the parameter as a whole, and once on the binding `x`.
131 if param.pat.simple_ident().is_none() && !tcx.features().unsized_locals {
132 fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
135 fcx.write_ty(param.hir_id, param_ty);
138 inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
140 fcx.in_tail_expr = true;
141 if let ty::Dynamic(..) = declared_ret_ty.kind() {
142 // FIXME: We need to verify that the return type is `Sized` after the return expression has
143 // been evaluated so that we have types available for all the nodes being returned, but that
144 // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
145 // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
146 // while keeping the current ordering we will ignore the tail expression's type because we
147 // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
148 // because we will trigger "unreachable expression" lints unconditionally.
149 // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
150 // case that a newcomer might make, returning a bare trait, and in that case we populate
151 // the tail expression's type so that the suggestion will be correct, but ignore all other
153 fcx.check_expr(&body.value);
154 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
155 tcx.sess.delay_span_bug(decl.output.span(), "`!Sized` return type");
157 fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
158 fcx.check_return_expr(&body.value);
160 fcx.in_tail_expr = false;
162 // We insert the deferred_generator_interiors entry after visiting the body.
163 // This ensures that all nested generators appear before the entry of this generator.
164 // resolve_generator_interiors relies on this property.
165 let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
167 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
168 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
170 let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
171 Some(GeneratorTypes {
175 movability: can_be_generator.unwrap(),
181 // Finalize the return check by taking the LUB of the return types
182 // we saw and assigning it to the expected return type. This isn't
183 // really expected to fail, since the coercions would have failed
184 // earlier when trying to find a LUB.
186 // However, the behavior around `!` is sort of complex. In the
187 // event that the `actual_return_ty` comes back as `!`, that
188 // indicates that the fn either does not return or "returns" only
189 // values of type `!`. In this case, if there is an expected
190 // return type that is *not* `!`, that should be ok. But if the
191 // return type is being inferred, we want to "fallback" to `!`:
193 // let x = move || panic!();
195 // To allow for that, I am creating a type variable with diverging
196 // fallback. This was deemed ever so slightly better than unifying
197 // the return value with `!` because it allows for the caller to
198 // make more assumptions about the return type (e.g., they could do
200 // let y: Option<u32> = Some(x());
202 // which would then cause this return type to become `u32`, not
204 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
205 let mut actual_return_ty = coercion.complete(&fcx);
206 if actual_return_ty.is_never() {
207 actual_return_ty = fcx.next_diverging_ty_var(TypeVariableOrigin {
208 kind: TypeVariableOriginKind::DivergingFn,
212 fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty);
214 // Check that the main return type implements the termination trait.
215 if let Some(term_id) = tcx.lang_items().termination() {
216 if let Some((def_id, EntryFnType::Main)) = tcx.entry_fn(LOCAL_CRATE) {
217 let main_id = hir.local_def_id_to_hir_id(def_id);
218 if main_id == fn_id {
219 let substs = tcx.mk_substs_trait(declared_ret_ty, &[]);
220 let trait_ref = ty::TraitRef::new(term_id, substs);
221 let return_ty_span = decl.output.span();
222 let cause = traits::ObligationCause::new(
225 ObligationCauseCode::MainFunctionType,
228 inherited.register_predicate(traits::Obligation::new(
231 trait_ref.without_const().to_predicate(tcx),
237 // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
238 if let Some(panic_impl_did) = tcx.lang_items().panic_impl() {
239 if panic_impl_did == hir.local_def_id(fn_id).to_def_id() {
240 if let Some(panic_info_did) = tcx.lang_items().panic_info() {
241 if *declared_ret_ty.kind() != ty::Never {
242 sess.span_err(decl.output.span(), "return type should be `!`");
245 let inputs = fn_sig.inputs();
246 let span = hir.span(fn_id);
247 if inputs.len() == 1 {
248 let arg_is_panic_info = match *inputs[0].kind() {
249 ty::Ref(region, ty, mutbl) => match *ty.kind() {
250 ty::Adt(ref adt, _) => {
251 adt.did == panic_info_did
252 && mutbl == hir::Mutability::Not
253 && *region != RegionKind::ReStatic
260 if !arg_is_panic_info {
261 sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
264 if let Node::Item(item) = hir.get(fn_id) {
265 if let ItemKind::Fn(_, ref generics, _) = item.kind {
266 if !generics.params.is_empty() {
267 sess.span_err(span, "should have no type parameters");
272 let span = sess.source_map().guess_head_span(span);
273 sess.span_err(span, "function should have one argument");
276 sess.err("language item required, but not found: `panic_info`");
281 // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
282 if let Some(alloc_error_handler_did) = tcx.lang_items().oom() {
283 if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() {
284 if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() {
285 if *declared_ret_ty.kind() != ty::Never {
286 sess.span_err(decl.output.span(), "return type should be `!`");
289 let inputs = fn_sig.inputs();
290 let span = hir.span(fn_id);
291 if inputs.len() == 1 {
292 let arg_is_alloc_layout = match inputs[0].kind() {
293 ty::Adt(ref adt, _) => adt.did == alloc_layout_did,
297 if !arg_is_alloc_layout {
298 sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
301 if let Node::Item(item) = hir.get(fn_id) {
302 if let ItemKind::Fn(_, ref generics, _) = item.kind {
303 if !generics.params.is_empty() {
306 "`#[alloc_error_handler]` function should have no type \
313 let span = sess.source_map().guess_head_span(span);
314 sess.span_err(span, "function should have one argument");
317 sess.err("language item required, but not found: `alloc_layout`");
325 pub(super) fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) {
326 let def_id = tcx.hir().local_def_id(id);
327 let def = tcx.adt_def(def_id);
328 def.destructor(tcx); // force the destructor to be evaluated
329 check_representable(tcx, span, def_id);
332 check_simd(tcx, span, def_id);
335 check_transparent(tcx, span, def);
336 check_packed(tcx, span, def);
339 pub(super) fn check_union(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) {
340 let def_id = tcx.hir().local_def_id(id);
341 let def = tcx.adt_def(def_id);
342 def.destructor(tcx); // force the destructor to be evaluated
343 check_representable(tcx, span, def_id);
344 check_transparent(tcx, span, def);
345 check_union_fields(tcx, span, def_id);
346 check_packed(tcx, span, def);
349 /// When the `#![feature(untagged_unions)]` gate is active,
350 /// check that the fields of the `union` does not contain fields that need dropping.
351 pub(super) fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
352 let item_type = tcx.type_of(item_def_id);
353 if let ty::Adt(def, substs) = item_type.kind() {
354 assert!(def.is_union());
355 let fields = &def.non_enum_variant().fields;
356 let param_env = tcx.param_env(item_def_id);
357 for field in fields {
358 let field_ty = field.ty(tcx, substs);
359 // We are currently checking the type this field came from, so it must be local.
360 let field_span = tcx.hir().span_if_local(field.did).unwrap();
361 if field_ty.needs_drop(tcx, param_env) {
366 "unions may not contain fields that need dropping"
368 .span_note(field_span, "`std::mem::ManuallyDrop` can be used to wrap the type")
374 span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
379 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
380 /// projections that would result in "inheriting lifetimes".
381 pub(super) fn check_opaque<'tcx>(
384 substs: SubstsRef<'tcx>,
386 origin: &hir::OpaqueTyOrigin,
388 check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
389 tcx.ensure().type_of(def_id);
390 if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
393 check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
396 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
397 /// in "inheriting lifetimes".
398 pub(super) fn check_opaque_for_inheriting_lifetimes(
403 let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(def_id));
405 "check_opaque_for_inheriting_lifetimes: def_id={:?} span={:?} item={:?}",
410 struct ProhibitOpaqueVisitor<'tcx> {
411 opaque_identity_ty: Ty<'tcx>,
412 generics: &'tcx ty::Generics,
413 ty: Option<Ty<'tcx>>,
416 impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
417 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
418 debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
419 if t != self.opaque_identity_ty && t.super_visit_with(self) {
426 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
427 debug!("check_opaque_for_inheriting_lifetimes: (visit_region) r={:?}", r);
428 if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r {
429 return *index < self.generics.parent_count as u32;
432 r.super_visit_with(self)
435 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
436 if let ty::ConstKind::Unevaluated(..) = c.val {
437 // FIXME(#72219) We currenctly don't detect lifetimes within substs
438 // which would violate this check. Even though the particular substitution is not used
439 // within the const, this should still be fixed.
442 c.super_visit_with(self)
446 if let ItemKind::OpaqueTy(hir::OpaqueTy {
447 origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
451 let mut visitor = ProhibitOpaqueVisitor {
452 opaque_identity_ty: tcx.mk_opaque(
454 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
456 generics: tcx.generics_of(def_id),
459 let prohibit_opaque = tcx
460 .explicit_item_bounds(def_id)
462 .any(|(predicate, _)| predicate.visit_with(&mut visitor));
464 "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor={:?}",
465 prohibit_opaque, visitor
469 let is_async = match item.kind {
470 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => match origin {
471 hir::OpaqueTyOrigin::AsyncFn => true,
477 let mut err = struct_span_err!(
481 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
483 if is_async { "async fn" } else { "impl Trait" },
486 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span) {
487 if snippet == "Self" {
488 if let Some(ty) = visitor.ty {
491 "consider spelling out the type instead",
493 Applicability::MaybeIncorrect,
503 /// Checks that an opaque type does not contain cycles.
504 pub(super) fn check_opaque_for_cycles<'tcx>(
507 substs: SubstsRef<'tcx>,
509 origin: &hir::OpaqueTyOrigin,
510 ) -> Result<(), ErrorReported> {
511 if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
514 hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
515 hir::OpaqueTyOrigin::Binding => {
516 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
518 _ => opaque_type_cycle_error(tcx, def_id, span),
526 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
527 fn check_opaque_meets_bounds<'tcx>(
530 substs: SubstsRef<'tcx>,
532 origin: &hir::OpaqueTyOrigin,
535 // Checked when type checking the function containing them.
536 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => return,
537 // Can have different predicates to their defining use
538 hir::OpaqueTyOrigin::Binding | hir::OpaqueTyOrigin::Misc => {}
541 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
542 let param_env = tcx.param_env(def_id);
544 tcx.infer_ctxt().enter(move |infcx| {
545 let inh = Inherited::new(infcx, def_id);
546 let infcx = &inh.infcx;
547 let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
549 let misc_cause = traits::ObligationCause::misc(span, hir_id);
551 let (_, opaque_type_map) = inh.register_infer_ok_obligations(
552 infcx.instantiate_opaque_types(def_id.to_def_id(), hir_id, param_env, &opaque_ty, span),
555 for (def_id, opaque_defn) in opaque_type_map {
557 .at(&misc_cause, param_env)
558 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, opaque_defn.substs))
560 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
561 Err(ty_err) => tcx.sess.delay_span_bug(
562 opaque_defn.definition_span,
564 "could not unify `{}` with revealed type:\n{}",
565 opaque_defn.concrete_ty, ty_err,
571 // Check that all obligations are satisfied by the implementation's
573 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
574 infcx.report_fulfillment_errors(errors, None, false);
577 // Finally, resolve all regions. This catches wily misuses of
578 // lifetime parameters.
579 let fcx = FnCtxt::new(&inh, param_env, hir_id);
580 fcx.regionck_item(hir_id, span, &[]);
584 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
586 "check_item_type(it.hir_id={}, it.name={})",
588 tcx.def_path_str(tcx.hir().local_def_id(it.hir_id).to_def_id())
590 let _indenter = indenter();
592 // Consts can play a role in type-checking, so they are included here.
593 hir::ItemKind::Static(..) => {
594 let def_id = tcx.hir().local_def_id(it.hir_id);
595 tcx.ensure().typeck(def_id);
596 maybe_check_static_with_link_section(tcx, def_id, it.span);
598 hir::ItemKind::Const(..) => {
599 tcx.ensure().typeck(tcx.hir().local_def_id(it.hir_id));
601 hir::ItemKind::Enum(ref enum_definition, _) => {
602 check_enum(tcx, it.span, &enum_definition.variants, it.hir_id);
604 hir::ItemKind::Fn(..) => {} // entirely within check_item_body
605 hir::ItemKind::Impl { ref items, .. } => {
606 debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id);
607 let impl_def_id = tcx.hir().local_def_id(it.hir_id);
608 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
609 check_impl_items_against_trait(tcx, it.span, impl_def_id, impl_trait_ref, items);
610 let trait_def_id = impl_trait_ref.def_id;
611 check_on_unimplemented(tcx, trait_def_id, it);
614 hir::ItemKind::Trait(_, _, _, _, ref items) => {
615 let def_id = tcx.hir().local_def_id(it.hir_id);
616 check_on_unimplemented(tcx, def_id.to_def_id(), it);
618 for item in items.iter() {
619 let item = tcx.hir().trait_item(item.id);
621 hir::TraitItemKind::Fn(ref sig, _) => {
622 let abi = sig.header.abi;
623 fn_maybe_err(tcx, item.ident.span, abi);
625 hir::TraitItemKind::Type(.., Some(_default)) => {
626 let item_def_id = tcx.hir().local_def_id(item.hir_id).to_def_id();
627 let assoc_item = tcx.associated_item(item_def_id);
629 InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
630 let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
635 ty::TraitRef { def_id: def_id.to_def_id(), substs: trait_substs },
642 hir::ItemKind::Struct(..) => {
643 check_struct(tcx, it.hir_id, it.span);
645 hir::ItemKind::Union(..) => {
646 check_union(tcx, it.hir_id, it.span);
648 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
649 // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
650 // `async-std` (and `pub async fn` in general).
651 // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
652 // See https://github.com/rust-lang/rust/issues/75100
653 if !tcx.sess.opts.actually_rustdoc {
654 let def_id = tcx.hir().local_def_id(it.hir_id);
656 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
657 check_opaque(tcx, def_id, substs, it.span, &origin);
660 hir::ItemKind::TyAlias(..) => {
661 let def_id = tcx.hir().local_def_id(it.hir_id);
662 let pty_ty = tcx.type_of(def_id);
663 let generics = tcx.generics_of(def_id);
664 check_type_params_are_used(tcx, &generics, pty_ty);
666 hir::ItemKind::ForeignMod(ref m) => {
667 check_abi(tcx, it.span, m.abi);
669 if m.abi == Abi::RustIntrinsic {
670 for item in m.items {
671 intrinsic::check_intrinsic_type(tcx, item);
673 } else if m.abi == Abi::PlatformIntrinsic {
674 for item in m.items {
675 intrinsic::check_platform_intrinsic_type(tcx, item);
678 for item in m.items {
679 let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id));
680 let own_counts = generics.own_counts();
681 if generics.params.len() - own_counts.lifetimes != 0 {
682 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
683 (_, 0) => ("type", "types", Some("u32")),
684 // We don't specify an example value, because we can't generate
685 // a valid value for any type.
686 (0, _) => ("const", "consts", None),
687 _ => ("type or const", "types or consts", None),
693 "foreign items may not have {} parameters",
696 .span_label(item.span, &format!("can't have {} parameters", kinds))
698 // FIXME: once we start storing spans for type arguments, turn this
699 // into a suggestion.
701 "replace the {} parameters with concrete {}{}",
704 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
710 if let hir::ForeignItemKind::Fn(ref fn_decl, _, _) = item.kind {
711 require_c_abi_if_c_variadic(tcx, fn_decl, m.abi, item.span);
716 _ => { /* nothing to do */ }
720 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
721 let item_def_id = tcx.hir().local_def_id(item.hir_id);
722 // an error would be reported if this fails.
723 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id.to_def_id());
726 pub(super) fn check_specialization_validity<'tcx>(
728 trait_def: &ty::TraitDef,
729 trait_item: &ty::AssocItem,
731 impl_item: &hir::ImplItem<'_>,
733 let kind = match impl_item.kind {
734 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
735 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
736 hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
739 let ancestors = match trait_def.ancestors(tcx, impl_id) {
740 Ok(ancestors) => ancestors,
743 let mut ancestor_impls = ancestors
745 .filter_map(|parent| {
746 if parent.is_from_trait() {
749 Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
754 if ancestor_impls.peek().is_none() {
755 // No parent, nothing to specialize.
759 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
761 // Parent impl exists, and contains the parent item we're trying to specialize, but
762 // doesn't mark it `default`.
763 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
764 Some(Err(parent_impl.def_id()))
767 // Parent impl contains item and makes it specializable.
768 Some(_) => Some(Ok(())),
770 // Parent impl doesn't mention the item. This means it's inherited from the
771 // grandparent. In that case, if parent is a `default impl`, inherited items use the
772 // "defaultness" from the grandparent, else they are final.
774 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
777 Some(Err(parent_impl.def_id()))
783 // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
784 // item. This is allowed, the item isn't actually getting specialized here.
785 let result = opt_result.unwrap_or(Ok(()));
787 if let Err(parent_impl) = result {
788 report_forbidden_specialization(tcx, impl_item, parent_impl);
792 pub(super) fn check_impl_items_against_trait<'tcx>(
794 full_impl_span: Span,
796 impl_trait_ref: ty::TraitRef<'tcx>,
797 impl_item_refs: &[hir::ImplItemRef<'_>],
799 let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
801 // If the trait reference itself is erroneous (so the compilation is going
802 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
803 // isn't populated for such impls.
804 if impl_trait_ref.references_error() {
808 // Negative impls are not expected to have any items
809 match tcx.impl_polarity(impl_id) {
810 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
811 ty::ImplPolarity::Negative => {
812 if let [first_item_ref, ..] = impl_item_refs {
813 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
818 "negative impls cannot have any items"
826 // Locate trait definition and items
827 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
829 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
831 // Check existing impl methods to see if they are both present in trait
832 // and compatible with trait signature
833 for impl_item in impl_items() {
834 let namespace = impl_item.kind.namespace();
835 let ty_impl_item = tcx.associated_item(tcx.hir().local_def_id(impl_item.hir_id));
836 let ty_trait_item = tcx
837 .associated_items(impl_trait_ref.def_id)
838 .find_by_name_and_namespace(tcx, ty_impl_item.ident, namespace, impl_trait_ref.def_id)
840 // Not compatible, but needed for the error message
841 tcx.associated_items(impl_trait_ref.def_id)
842 .filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id)
846 // Check that impl definition matches trait definition
847 if let Some(ty_trait_item) = ty_trait_item {
848 match impl_item.kind {
849 hir::ImplItemKind::Const(..) => {
850 // Find associated const definition.
851 if ty_trait_item.kind == ty::AssocKind::Const {
860 let mut err = struct_span_err!(
864 "item `{}` is an associated const, \
865 which doesn't match its trait `{}`",
867 impl_trait_ref.print_only_trait_path()
869 err.span_label(impl_item.span, "does not match trait");
870 // We can only get the spans from local trait definition
871 // Same for E0324 and E0325
872 if let Some(trait_span) = tcx.hir().span_if_local(ty_trait_item.def_id) {
873 err.span_label(trait_span, "item in trait");
878 hir::ImplItemKind::Fn(..) => {
879 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
880 if ty_trait_item.kind == ty::AssocKind::Fn {
890 let mut err = struct_span_err!(
894 "item `{}` is an associated method, \
895 which doesn't match its trait `{}`",
897 impl_trait_ref.print_only_trait_path()
899 err.span_label(impl_item.span, "does not match trait");
900 if let Some(trait_span) = opt_trait_span {
901 err.span_label(trait_span, "item in trait");
906 hir::ImplItemKind::TyAlias(_) => {
907 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
908 if ty_trait_item.kind == ty::AssocKind::Type {
918 let mut err = struct_span_err!(
922 "item `{}` is an associated type, \
923 which doesn't match its trait `{}`",
925 impl_trait_ref.print_only_trait_path()
927 err.span_label(impl_item.span, "does not match trait");
928 if let Some(trait_span) = opt_trait_span {
929 err.span_label(trait_span, "item in trait");
936 check_specialization_validity(
946 // Check for missing items from trait
947 let mut missing_items = Vec::new();
948 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
949 for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
950 let is_implemented = ancestors
951 .leaf_def(tcx, trait_item.ident, trait_item.kind)
952 .map(|node_item| !node_item.defining_node.is_from_trait())
955 if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
956 if !trait_item.defaultness.has_value() {
957 missing_items.push(*trait_item);
963 if !missing_items.is_empty() {
964 missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
968 /// Checks whether a type can be represented in memory. In particular, it
969 /// identifies types that contain themselves without indirection through a
970 /// pointer, which would mean their size is unbounded.
971 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
972 let rty = tcx.type_of(item_def_id);
974 // Check that it is possible to represent this type. This call identifies
975 // (1) types that contain themselves and (2) types that contain a different
976 // recursive type. It is only necessary to throw an error on those that
977 // contain themselves. For case 2, there must be an inner type that will be
979 match rty.is_representable(tcx, sp) {
980 Representability::SelfRecursive(spans) => {
981 recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
984 Representability::Representable | Representability::ContainsRecursive => (),
989 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
990 let t = tcx.type_of(def_id);
991 if let ty::Adt(def, substs) = t.kind() {
993 let fields = &def.non_enum_variant().fields;
994 if fields.is_empty() {
995 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
998 let e = fields[0].ty(tcx, substs);
999 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1000 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1001 .span_label(sp, "SIMD elements must have the same type")
1006 ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ }
1007 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1013 "SIMD vector element type should be machine type"
1023 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1024 let repr = def.repr;
1026 for attr in tcx.get_attrs(def.did).iter() {
1027 for r in attr::find_repr_attrs(&tcx.sess, attr) {
1028 if let attr::ReprPacked(pack) = r {
1029 if let Some(repr_pack) = repr.pack {
1030 if pack as u64 != repr_pack.bytes() {
1035 "type has conflicting packed representation hints"
1043 if repr.align.is_some() {
1048 "type has conflicting packed and align representation hints"
1052 if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1053 let mut err = struct_span_err!(
1057 "packed type cannot transitively contain a `#[repr(align)]` type"
1061 tcx.def_span(def_spans[0].0),
1063 "`{}` has a `#[repr(align)]` attribute",
1064 tcx.item_name(def_spans[0].0)
1068 if def_spans.len() > 2 {
1069 let mut first = true;
1070 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1071 let ident = tcx.item_name(*adt_def);
1076 "`{}` contains a field of type `{}`",
1077 tcx.type_of(def.did),
1081 format!("...which contains a field of type `{}`", ident)
1094 pub(super) fn check_packed_inner(
1097 stack: &mut Vec<DefId>,
1098 ) -> Option<Vec<(DefId, Span)>> {
1099 if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1100 if def.is_struct() || def.is_union() {
1101 if def.repr.align.is_some() {
1102 return Some(vec![(def.did, DUMMY_SP)]);
1106 for field in &def.non_enum_variant().fields {
1107 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1108 if !stack.contains(&def.did) {
1109 if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1110 defs.push((def.did, field.ident.span));
1123 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1124 if !adt.repr.transparent() {
1127 let sp = tcx.sess.source_map().guess_head_span(sp);
1129 if adt.is_union() && !tcx.features().transparent_unions {
1131 &tcx.sess.parse_sess,
1132 sym::transparent_unions,
1134 "transparent unions are unstable",
1139 if adt.variants.len() != 1 {
1140 bad_variant_count(tcx, adt, sp, adt.did);
1141 if adt.variants.is_empty() {
1142 // Don't bother checking the fields. No variants (and thus no fields) exist.
1147 // For each field, figure out if it's known to be a ZST and align(1)
1148 let field_infos = adt.all_fields().map(|field| {
1149 let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1150 let param_env = tcx.param_env(field.did);
1151 let layout = tcx.layout_of(param_env.and(ty));
1152 // We are currently checking the type this field came from, so it must be local
1153 let span = tcx.hir().span_if_local(field.did).unwrap();
1154 let zst = layout.map(|layout| layout.is_zst()).unwrap_or(false);
1155 let align1 = layout.map(|layout| layout.align.abi.bytes() == 1).unwrap_or(false);
1159 let non_zst_fields =
1160 field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1161 let non_zst_count = non_zst_fields.clone().count();
1162 if non_zst_count != 1 {
1163 bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1165 for (span, zst, align1) in field_infos {
1171 "zero-sized field in transparent {} has alignment larger than 1",
1174 .span_label(span, "has alignment larger than 1")
1180 #[allow(trivial_numeric_casts)]
1181 pub fn check_enum<'tcx>(
1184 vs: &'tcx [hir::Variant<'tcx>],
1187 let def_id = tcx.hir().local_def_id(id);
1188 let def = tcx.adt_def(def_id);
1189 def.destructor(tcx); // force the destructor to be evaluated
1192 let attributes = tcx.get_attrs(def_id.to_def_id());
1193 if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1198 "unsupported representation for zero-variant enum"
1200 .span_label(sp, "zero-variant enum")
1205 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1206 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1207 if !tcx.features().repr128 {
1209 &tcx.sess.parse_sess,
1212 "repr with 128-bit type is unstable",
1219 if let Some(ref e) = v.disr_expr {
1220 tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1224 if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1225 let is_unit = |var: &hir::Variant<'_>| match var.data {
1226 hir::VariantData::Unit(..) => true,
1230 let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1231 let has_non_units = vs.iter().any(|var| !is_unit(var));
1232 let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1233 let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1235 if disr_non_unit || (disr_units && has_non_units) {
1237 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1242 let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1243 for ((_, discr), v) in def.discriminants(tcx).zip(vs) {
1244 // Check for duplicate discriminant values
1245 if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1246 let variant_did = def.variants[VariantIdx::new(i)].def_id;
1247 let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1248 let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1249 let i_span = match variant_i.disr_expr {
1250 Some(ref expr) => tcx.hir().span(expr.hir_id),
1251 None => tcx.hir().span(variant_i_hir_id),
1253 let span = match v.disr_expr {
1254 Some(ref expr) => tcx.hir().span(expr.hir_id),
1261 "discriminant value `{}` already exists",
1264 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1265 .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1268 disr_vals.push(discr);
1271 check_representable(tcx, sp, def_id);
1272 check_transparent(tcx, sp, def);
1275 pub(super) fn check_type_params_are_used<'tcx>(
1277 generics: &ty::Generics,
1280 debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1282 assert_eq!(generics.parent, None);
1284 if generics.own_counts().types == 0 {
1288 let mut params_used = BitSet::new_empty(generics.params.len());
1290 if ty.references_error() {
1291 // If there is already another error, do not emit
1292 // an error for not using a type parameter.
1293 assert!(tcx.sess.has_errors());
1297 for leaf in ty.walk() {
1298 if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1299 if let ty::Param(param) = leaf_ty.kind() {
1300 debug!("found use of ty param {:?}", param);
1301 params_used.insert(param.index);
1306 for param in &generics.params {
1307 if !params_used.contains(param.index) {
1308 if let ty::GenericParamDefKind::Type { .. } = param.kind {
1309 let span = tcx.def_span(param.def_id);
1314 "type parameter `{}` is unused",
1317 .span_label(span, "unused type parameter")
1324 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1325 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1328 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1329 wfcheck::check_item_well_formed(tcx, def_id);
1332 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1333 wfcheck::check_trait_item(tcx, def_id);
1336 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1337 wfcheck::check_impl_item(tcx, def_id);
1340 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1341 struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1342 .span_label(span, "recursive `async fn`")
1343 .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1347 /// Emit an error for recursive opaque types.
1349 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1350 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1353 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1354 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1355 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1356 let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1358 let mut label = false;
1359 if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1360 let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1364 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1365 .all(|ty| matches!(ty.kind(), ty::Never))
1370 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1371 .map(|expr| expr.span)
1372 .collect::<Vec<Span>>();
1373 let span_len = spans.len();
1375 err.span_label(spans[0], "this returned value is of `!` type");
1377 let mut multispan: MultiSpan = spans.clone().into();
1380 .push_span_label(span, "this returned value is of `!` type".to_string());
1382 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1384 err.help("this error will resolve once the item's body returns a concrete type");
1386 let mut seen = FxHashSet::default();
1388 err.span_label(span, "recursive opaque type");
1390 for (sp, ty) in visitor
1393 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1394 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1396 struct VisitTypes(Vec<DefId>);
1397 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1398 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
1400 ty::Opaque(def, _) => {
1404 _ => t.super_visit_with(self),
1408 let mut visitor = VisitTypes(vec![]);
1409 ty.visit_with(&mut visitor);
1410 for def_id in visitor.0 {
1411 let ty_span = tcx.def_span(def_id);
1412 if !seen.contains(&ty_span) {
1413 err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1414 seen.insert(ty_span);
1416 err.span_label(sp, &format!("returning here with type `{}`", ty));
1422 err.span_label(span, "cannot resolve opaque type");