]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/check.rs
Rollup merge of #97599 - GuillaumeGomez:reexport-json, r=CraftSpider
[rust.git] / compiler / rustc_typeck / src / check / check.rs
1 use crate::check::wfcheck::for_item;
2
3 use super::coercion::CoerceMany;
4 use super::compare_method::check_type_bounds;
5 use super::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl};
6 use super::*;
7
8 use rustc_attr as attr;
9 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{DefId, LocalDefId};
13 use rustc_hir::intravisit::Visitor;
14 use rustc_hir::lang_items::LangItem;
15 use rustc_hir::{ItemKind, Node, PathSegment};
16 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17 use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
18 use rustc_infer::traits::Obligation;
19 use rustc_middle::hir::nested_filter;
20 use rustc_middle::ty::fold::TypeFoldable;
21 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
22 use rustc_middle::ty::subst::GenericArgKind;
23 use rustc_middle::ty::util::{Discr, IntTypeExt};
24 use rustc_middle::ty::{self, ParamEnv, ToPredicate, Ty, TyCtxt};
25 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
26 use rustc_span::symbol::sym;
27 use rustc_span::{self, Span};
28 use rustc_target::spec::abi::Abi;
29 use rustc_trait_selection::traits;
30 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
31 use rustc_ty_utils::representability::{self, Representability};
32
33 use std::iter;
34 use std::ops::ControlFlow;
35
36 pub fn check_wf_new(tcx: TyCtxt<'_>) {
37     let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
38     tcx.hir().par_visit_all_item_likes(&visit);
39 }
40
41 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
42     match tcx.sess.target.is_abi_supported(abi) {
43         Some(true) => (),
44         Some(false) => {
45             struct_span_err!(
46                 tcx.sess,
47                 span,
48                 E0570,
49                 "`{abi}` is not a supported ABI for the current target",
50             )
51             .emit();
52         }
53         None => {
54             tcx.struct_span_lint_hir(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
55                 lint.build("use of calling convention not supported on this target").emit();
56             });
57         }
58     }
59
60     // This ABI is only allowed on function pointers
61     if abi == Abi::CCmseNonSecureCall {
62         struct_span_err!(
63             tcx.sess,
64             span,
65             E0781,
66             "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
67         )
68         .emit();
69     }
70 }
71
72 /// Helper used for fns and closures. Does the grungy work of checking a function
73 /// body and returns the function context used for that purpose, since in the case of a fn item
74 /// there is still a bit more to do.
75 ///
76 /// * ...
77 /// * inherited: other fields inherited from the enclosing fn (if any)
78 #[instrument(skip(inherited, body), level = "debug")]
79 pub(super) fn check_fn<'a, 'tcx>(
80     inherited: &'a Inherited<'a, 'tcx>,
81     param_env: ty::ParamEnv<'tcx>,
82     fn_sig: ty::FnSig<'tcx>,
83     decl: &'tcx hir::FnDecl<'tcx>,
84     fn_id: hir::HirId,
85     body: &'tcx hir::Body<'tcx>,
86     can_be_generator: Option<hir::Movability>,
87     return_type_pre_known: bool,
88 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
89     // Create the function context. This is either derived from scratch or,
90     // in the case of closures, based on the outer context.
91     let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
92     fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
93     fcx.return_type_pre_known = return_type_pre_known;
94
95     let tcx = fcx.tcx;
96     let hir = tcx.hir();
97
98     let declared_ret_ty = fn_sig.output();
99
100     let ret_ty =
101         fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
102             declared_ret_ty,
103             body.value.hir_id,
104             DUMMY_SP,
105             param_env,
106         ));
107     fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
108     fcx.ret_type_span = Some(decl.output.span());
109
110     let span = body.value.span;
111
112     fn_maybe_err(tcx, span, fn_sig.abi);
113
114     if fn_sig.abi == Abi::RustCall {
115         let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
116
117         let err = || {
118             let item = match tcx.hir().get(fn_id) {
119                 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
120                 Node::ImplItem(hir::ImplItem {
121                     kind: hir::ImplItemKind::Fn(header, ..), ..
122                 }) => Some(header),
123                 Node::TraitItem(hir::TraitItem {
124                     kind: hir::TraitItemKind::Fn(header, ..),
125                     ..
126                 }) => Some(header),
127                 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
128                 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => None,
129                 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
130             };
131
132             if let Some(header) = item {
133                 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple");
134             }
135         };
136
137         if fn_sig.inputs().len() != expected_args {
138             err()
139         } else {
140             // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
141             //   This will probably require wide-scale changes to support a TupleKind obligation
142             //   We can't resolve this without knowing the type of the param
143             if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
144                 err()
145             }
146         }
147     }
148
149     if body.generator_kind.is_some() && can_be_generator.is_some() {
150         let yield_ty = fcx
151             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
152         fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
153
154         // Resume type defaults to `()` if the generator has no argument.
155         let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
156
157         fcx.resume_yield_tys = Some((resume_ty, yield_ty));
158     }
159
160     GatherLocalsVisitor::new(&fcx).visit_body(body);
161
162     // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
163     // (as it's created inside the body itself, not passed in from outside).
164     let maybe_va_list = if fn_sig.c_variadic {
165         let span = body.params.last().unwrap().span;
166         let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
167         let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
168
169         Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
170     } else {
171         None
172     };
173
174     // Add formal parameters.
175     let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
176     let inputs_fn = fn_sig.inputs().iter().copied();
177     for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
178         // Check the pattern.
179         let ty_span = try { inputs_hir?.get(idx)?.span };
180         fcx.check_pat_top(&param.pat, param_ty, ty_span, false);
181
182         // Check that argument is Sized.
183         // The check for a non-trivial pattern is a hack to avoid duplicate warnings
184         // for simple cases like `fn foo(x: Trait)`,
185         // where we would error once on the parameter as a whole, and once on the binding `x`.
186         if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
187             fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
188         }
189
190         fcx.write_ty(param.hir_id, param_ty);
191     }
192
193     inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
194
195     fcx.in_tail_expr = true;
196     if let ty::Dynamic(..) = declared_ret_ty.kind() {
197         // FIXME: We need to verify that the return type is `Sized` after the return expression has
198         // been evaluated so that we have types available for all the nodes being returned, but that
199         // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
200         // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
201         // while keeping the current ordering we will ignore the tail expression's type because we
202         // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
203         // because we will trigger "unreachable expression" lints unconditionally.
204         // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
205         // case that a newcomer might make, returning a bare trait, and in that case we populate
206         // the tail expression's type so that the suggestion will be correct, but ignore all other
207         // possible cases.
208         fcx.check_expr(&body.value);
209         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
210     } else {
211         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
212         fcx.check_return_expr(&body.value, false);
213     }
214     fcx.in_tail_expr = false;
215
216     // We insert the deferred_generator_interiors entry after visiting the body.
217     // This ensures that all nested generators appear before the entry of this generator.
218     // resolve_generator_interiors relies on this property.
219     let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
220         let interior = fcx
221             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
222         fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
223
224         let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
225         Some(GeneratorTypes {
226             resume_ty,
227             yield_ty,
228             interior,
229             movability: can_be_generator.unwrap(),
230         })
231     } else {
232         None
233     };
234
235     // Finalize the return check by taking the LUB of the return types
236     // we saw and assigning it to the expected return type. This isn't
237     // really expected to fail, since the coercions would have failed
238     // earlier when trying to find a LUB.
239     let coercion = fcx.ret_coercion.take().unwrap().into_inner();
240     let mut actual_return_ty = coercion.complete(&fcx);
241     debug!("actual_return_ty = {:?}", actual_return_ty);
242     if let ty::Dynamic(..) = declared_ret_ty.kind() {
243         // We have special-cased the case where the function is declared
244         // `-> dyn Foo` and we don't actually relate it to the
245         // `fcx.ret_coercion`, so just substitute a type variable.
246         actual_return_ty =
247             fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
248         debug!("actual_return_ty replaced with {:?}", actual_return_ty);
249     }
250
251     // HACK(oli-obk, compiler-errors): We should be comparing this against
252     // `declared_ret_ty`, but then anything uninferred would be inferred to
253     // the opaque type itself. That again would cause writeback to assume
254     // we have a recursive call site and do the sadly stabilized fallback to `()`.
255     fcx.demand_suptype(span, ret_ty, actual_return_ty);
256
257     // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
258     if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
259         && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
260     {
261         check_panic_info_fn(tcx, panic_impl_did.expect_local(), fn_sig, decl, declared_ret_ty);
262     }
263
264     // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
265     if let Some(alloc_error_handler_did) = tcx.lang_items().oom()
266         && alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id()
267     {
268         check_alloc_error_fn(tcx, alloc_error_handler_did.expect_local(), fn_sig, decl, declared_ret_ty);
269     }
270
271     (fcx, gen_ty)
272 }
273
274 fn check_panic_info_fn(
275     tcx: TyCtxt<'_>,
276     fn_id: LocalDefId,
277     fn_sig: ty::FnSig<'_>,
278     decl: &hir::FnDecl<'_>,
279     declared_ret_ty: Ty<'_>,
280 ) {
281     let Some(panic_info_did) = tcx.lang_items().panic_info() else {
282         tcx.sess.err("language item required, but not found: `panic_info`");
283         return;
284     };
285
286     if *declared_ret_ty.kind() != ty::Never {
287         tcx.sess.span_err(decl.output.span(), "return type should be `!`");
288     }
289
290     let span = tcx.def_span(fn_id);
291     let inputs = fn_sig.inputs();
292     if inputs.len() != 1 {
293         let span = tcx.sess.source_map().guess_head_span(span);
294         tcx.sess.span_err(span, "function should have one argument");
295         return;
296     }
297
298     let arg_is_panic_info = match *inputs[0].kind() {
299         ty::Ref(region, ty, mutbl) => match *ty.kind() {
300             ty::Adt(ref adt, _) => {
301                 adt.did() == panic_info_did && mutbl == hir::Mutability::Not && !region.is_static()
302             }
303             _ => false,
304         },
305         _ => false,
306     };
307
308     if !arg_is_panic_info {
309         tcx.sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
310     }
311
312     let DefKind::Fn = tcx.def_kind(fn_id) else {
313         let span = tcx.def_span(fn_id);
314         tcx.sess.span_err(span, "should be a function");
315         return;
316     };
317
318     let generic_counts = tcx.generics_of(fn_id).own_counts();
319     if generic_counts.types != 0 {
320         let span = tcx.def_span(fn_id);
321         tcx.sess.span_err(span, "should have no type parameters");
322     }
323     if generic_counts.consts != 0 {
324         let span = tcx.def_span(fn_id);
325         tcx.sess.span_err(span, "should have no const parameters");
326     }
327 }
328
329 fn check_alloc_error_fn(
330     tcx: TyCtxt<'_>,
331     fn_id: LocalDefId,
332     fn_sig: ty::FnSig<'_>,
333     decl: &hir::FnDecl<'_>,
334     declared_ret_ty: Ty<'_>,
335 ) {
336     let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() else {
337         tcx.sess.err("language item required, but not found: `alloc_layout`");
338         return;
339     };
340
341     if *declared_ret_ty.kind() != ty::Never {
342         tcx.sess.span_err(decl.output.span(), "return type should be `!`");
343     }
344
345     let inputs = fn_sig.inputs();
346     if inputs.len() != 1 {
347         let span = tcx.def_span(fn_id);
348         let span = tcx.sess.source_map().guess_head_span(span);
349         tcx.sess.span_err(span, "function should have one argument");
350         return;
351     }
352
353     let arg_is_alloc_layout = match inputs[0].kind() {
354         ty::Adt(ref adt, _) => adt.did() == alloc_layout_did,
355         _ => false,
356     };
357
358     if !arg_is_alloc_layout {
359         tcx.sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
360     }
361
362     let DefKind::Fn = tcx.def_kind(fn_id) else {
363         let span = tcx.def_span(fn_id);
364         tcx.sess.span_err(span, "`#[alloc_error_handler]` should be a function");
365         return;
366     };
367
368     let generic_counts = tcx.generics_of(fn_id).own_counts();
369     if generic_counts.types != 0 {
370         let span = tcx.def_span(fn_id);
371         tcx.sess.span_err(span, "`#[alloc_error_handler]` function should have no type parameters");
372     }
373     if generic_counts.consts != 0 {
374         let span = tcx.def_span(fn_id);
375         tcx.sess
376             .span_err(span, "`#[alloc_error_handler]` function should have no const parameters");
377     }
378 }
379
380 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
381     let def = tcx.adt_def(def_id);
382     def.destructor(tcx); // force the destructor to be evaluated
383     check_representable(tcx, span, def_id);
384
385     if def.repr().simd() {
386         check_simd(tcx, span, def_id);
387     }
388
389     check_transparent(tcx, span, def);
390     check_packed(tcx, span, def);
391 }
392
393 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) {
394     let def = tcx.adt_def(def_id);
395     def.destructor(tcx); // force the destructor to be evaluated
396     check_representable(tcx, span, def_id);
397     check_transparent(tcx, span, def);
398     check_union_fields(tcx, span, def_id);
399     check_packed(tcx, span, def);
400 }
401
402 /// Check that the fields of the `union` do not need dropping.
403 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
404     let item_type = tcx.type_of(item_def_id);
405     if let ty::Adt(def, substs) = item_type.kind() {
406         assert!(def.is_union());
407         let fields = &def.non_enum_variant().fields;
408         let param_env = tcx.param_env(item_def_id);
409         for field in fields {
410             let field_ty = field.ty(tcx, substs);
411             if field_ty.needs_drop(tcx, param_env) {
412                 let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
413                     // We are currently checking the type this field came from, so it must be local.
414                     Some(Node::Field(field)) => (field.span, field.ty.span),
415                     _ => unreachable!("mir field has to correspond to hir field"),
416                 };
417                 struct_span_err!(
418                     tcx.sess,
419                     field_span,
420                     E0740,
421                     "unions cannot contain fields that may need dropping"
422                 )
423                 .note(
424                     "a type is guaranteed not to need dropping \
425                     when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
426                 )
427                 .multipart_suggestion_verbose(
428                     "when the type does not implement `Copy`, \
429                     wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
430                     vec![
431                         (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
432                         (ty_span.shrink_to_hi(), ">".into()),
433                     ],
434                     Applicability::MaybeIncorrect,
435                 )
436                 .emit();
437                 return false;
438             }
439         }
440     } else {
441         span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind());
442     }
443     true
444 }
445
446 /// Check that a `static` is inhabited.
447 fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
448     // Make sure statics are inhabited.
449     // Other parts of the compiler assume that there are no uninhabited places. In principle it
450     // would be enough to check this for `extern` statics, as statics with an initializer will
451     // have UB during initialization if they are uninhabited, but there also seems to be no good
452     // reason to allow any statics to be uninhabited.
453     let ty = tcx.type_of(def_id);
454     let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) {
455         Ok(l) => l,
456         // Foreign statics that overflow their allowed size should emit an error
457         Err(LayoutError::SizeOverflow(_))
458             if {
459                 let node = tcx.hir().get_by_def_id(def_id);
460                 matches!(
461                     node,
462                     hir::Node::ForeignItem(hir::ForeignItem {
463                         kind: hir::ForeignItemKind::Static(..),
464                         ..
465                     })
466                 )
467             } =>
468         {
469             tcx.sess
470                 .struct_span_err(span, "extern static is too large for the current architecture")
471                 .emit();
472             return;
473         }
474         // Generic statics are rejected, but we still reach this case.
475         Err(e) => {
476             tcx.sess.delay_span_bug(span, &e.to_string());
477             return;
478         }
479     };
480     if layout.abi.is_uninhabited() {
481         tcx.struct_span_lint_hir(
482             UNINHABITED_STATIC,
483             tcx.hir().local_def_id_to_hir_id(def_id),
484             span,
485             |lint| {
486                 lint.build("static of uninhabited type")
487                 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
488                 .emit();
489             },
490         );
491     }
492 }
493
494 /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
495 /// projections that would result in "inheriting lifetimes".
496 pub(super) fn check_opaque<'tcx>(
497     tcx: TyCtxt<'tcx>,
498     def_id: LocalDefId,
499     substs: SubstsRef<'tcx>,
500     span: Span,
501     origin: &hir::OpaqueTyOrigin,
502 ) {
503     check_opaque_for_inheriting_lifetimes(tcx, def_id, span);
504     if tcx.type_of(def_id).references_error() {
505         return;
506     }
507     if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() {
508         return;
509     }
510     check_opaque_meets_bounds(tcx, def_id, substs, span, origin);
511 }
512
513 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
514 /// in "inheriting lifetimes".
515 #[instrument(level = "debug", skip(tcx, span))]
516 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
517     tcx: TyCtxt<'tcx>,
518     def_id: LocalDefId,
519     span: Span,
520 ) {
521     let item = tcx.hir().expect_item(def_id);
522     debug!(?item, ?span);
523
524     struct FoundParentLifetime;
525     struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
526     impl<'tcx> ty::fold::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
527         type BreakTy = FoundParentLifetime;
528
529         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
530             debug!("FindParentLifetimeVisitor: r={:?}", r);
531             if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
532                 if index < self.0.parent_count as u32 {
533                     return ControlFlow::Break(FoundParentLifetime);
534                 } else {
535                     return ControlFlow::CONTINUE;
536                 }
537             }
538
539             r.super_visit_with(self)
540         }
541
542         fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
543             if let ty::ConstKind::Unevaluated(..) = c.val() {
544                 // FIXME(#72219) We currently don't detect lifetimes within substs
545                 // which would violate this check. Even though the particular substitution is not used
546                 // within the const, this should still be fixed.
547                 return ControlFlow::CONTINUE;
548             }
549             c.super_visit_with(self)
550         }
551     }
552
553     struct ProhibitOpaqueVisitor<'tcx> {
554         tcx: TyCtxt<'tcx>,
555         opaque_identity_ty: Ty<'tcx>,
556         generics: &'tcx ty::Generics,
557         selftys: Vec<(Span, Option<String>)>,
558     }
559
560     impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
561         type BreakTy = Ty<'tcx>;
562
563         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
564             debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
565             if t == self.opaque_identity_ty {
566                 ControlFlow::CONTINUE
567             } else {
568                 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
569                     .map_break(|FoundParentLifetime| t)
570             }
571         }
572     }
573
574     impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
575         type NestedFilter = nested_filter::OnlyBodies;
576
577         fn nested_visit_map(&mut self) -> Self::Map {
578             self.tcx.hir()
579         }
580
581         fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
582             match arg.kind {
583                 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
584                     [
585                         PathSegment {
586                             res: Some(Res::SelfTy { trait_: _, alias_to: impl_ref }),
587                             ..
588                         },
589                     ] => {
590                         let impl_ty_name =
591                             impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
592                         self.selftys.push((path.span, impl_ty_name));
593                     }
594                     _ => {}
595                 },
596                 _ => {}
597             }
598             hir::intravisit::walk_ty(self, arg);
599         }
600     }
601
602     if let ItemKind::OpaqueTy(hir::OpaqueTy {
603         origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
604         ..
605     }) = item.kind
606     {
607         let mut visitor = ProhibitOpaqueVisitor {
608             opaque_identity_ty: tcx.mk_opaque(
609                 def_id.to_def_id(),
610                 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
611             ),
612             generics: tcx.generics_of(def_id),
613             tcx,
614             selftys: vec![],
615         };
616         let prohibit_opaque = tcx
617             .explicit_item_bounds(def_id)
618             .iter()
619             .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
620         debug!(
621             "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
622             prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
623         );
624
625         if let Some(ty) = prohibit_opaque.break_value() {
626             visitor.visit_item(&item);
627             let is_async = match item.kind {
628                 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
629                     matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
630                 }
631                 _ => unreachable!(),
632             };
633
634             let mut err = struct_span_err!(
635                 tcx.sess,
636                 span,
637                 E0760,
638                 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
639                  a parent scope",
640                 if is_async { "async fn" } else { "impl Trait" },
641             );
642
643             for (span, name) in visitor.selftys {
644                 err.span_suggestion(
645                     span,
646                     "consider spelling out the type instead",
647                     name.unwrap_or_else(|| format!("{:?}", ty)),
648                     Applicability::MaybeIncorrect,
649                 );
650             }
651             err.emit();
652         }
653     }
654 }
655
656 /// Checks that an opaque type does not contain cycles.
657 pub(super) fn check_opaque_for_cycles<'tcx>(
658     tcx: TyCtxt<'tcx>,
659     def_id: LocalDefId,
660     substs: SubstsRef<'tcx>,
661     span: Span,
662     origin: &hir::OpaqueTyOrigin,
663 ) -> Result<(), ErrorGuaranteed> {
664     if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
665         let reported = match origin {
666             hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
667             _ => opaque_type_cycle_error(tcx, def_id, span),
668         };
669         Err(reported)
670     } else {
671         Ok(())
672     }
673 }
674
675 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
676 ///
677 /// This is mostly checked at the places that specify the opaque type, but we
678 /// check those cases in the `param_env` of that function, which may have
679 /// bounds not on this opaque type:
680 ///
681 /// type X<T> = impl Clone
682 /// fn f<T: Clone>(t: T) -> X<T> {
683 ///     t
684 /// }
685 ///
686 /// Without this check the above code is incorrectly accepted: we would ICE if
687 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
688 #[instrument(level = "debug", skip(tcx))]
689 fn check_opaque_meets_bounds<'tcx>(
690     tcx: TyCtxt<'tcx>,
691     def_id: LocalDefId,
692     substs: SubstsRef<'tcx>,
693     span: Span,
694     origin: &hir::OpaqueTyOrigin,
695 ) {
696     let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
697
698     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
699     let defining_use_anchor = match *origin {
700         hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
701         hir::OpaqueTyOrigin::TyAlias => def_id,
702     };
703     let param_env = tcx.param_env(defining_use_anchor);
704
705     tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| {
706         let inh = Inherited::new(infcx, def_id);
707         let infcx = &inh.infcx;
708         let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
709
710         let misc_cause = traits::ObligationCause::misc(span, hir_id);
711
712         match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) {
713             Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
714             Err(ty_err) => {
715                 tcx.sess.delay_span_bug(
716                     span,
717                     &format!("could not unify `{hidden_type}` with revealed type:\n{ty_err}"),
718                 );
719             }
720         }
721
722         // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
723         // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
724         // hidden type is well formed even without those bounds.
725         let predicate =
726             ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx);
727         inh.register_predicate(Obligation::new(misc_cause, param_env, predicate));
728
729         // Check that all obligations are satisfied by the implementation's
730         // version.
731         let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
732         if !errors.is_empty() {
733             infcx.report_fulfillment_errors(&errors, None, false);
734         }
735
736         match origin {
737             // Checked when type checking the function containing them.
738             hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
739             // Can have different predicates to their defining use
740             hir::OpaqueTyOrigin::TyAlias => {
741                 // Finally, resolve all regions. This catches wily misuses of
742                 // lifetime parameters.
743                 let fcx = FnCtxt::new(&inh, param_env, hir_id);
744                 fcx.regionck_item(hir_id, span, FxHashSet::default());
745             }
746         }
747
748         // Clean up after ourselves
749         let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
750     });
751 }
752
753 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
754     debug!(
755         "check_item_type(it.def_id={:?}, it.name={})",
756         id.def_id,
757         tcx.def_path_str(id.def_id.to_def_id())
758     );
759     let _indenter = indenter();
760     match tcx.def_kind(id.def_id) {
761         DefKind::Static(..) => {
762             tcx.ensure().typeck(id.def_id);
763             maybe_check_static_with_link_section(tcx, id.def_id, tcx.def_span(id.def_id));
764             check_static_inhabited(tcx, id.def_id, tcx.def_span(id.def_id));
765         }
766         DefKind::Const => {
767             tcx.ensure().typeck(id.def_id);
768         }
769         DefKind::Enum => {
770             let item = tcx.hir().item(id);
771             let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else {
772                 return;
773             };
774             check_enum(tcx, item.span, &enum_definition.variants, item.def_id);
775         }
776         DefKind::Fn => {} // entirely within check_item_body
777         DefKind::Impl => {
778             let it = tcx.hir().item(id);
779             let hir::ItemKind::Impl(ref impl_) = it.kind else {
780                 return;
781             };
782             debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
783             if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
784                 check_impl_items_against_trait(
785                     tcx,
786                     it.span,
787                     it.def_id,
788                     impl_trait_ref,
789                     &impl_.items,
790                 );
791                 check_on_unimplemented(tcx, it);
792             }
793         }
794         DefKind::Trait => {
795             let it = tcx.hir().item(id);
796             let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
797                 return;
798             };
799             check_on_unimplemented(tcx, it);
800
801             for item in items.iter() {
802                 let item = tcx.hir().trait_item(item.id);
803                 match item.kind {
804                     hir::TraitItemKind::Fn(ref sig, _) => {
805                         let abi = sig.header.abi;
806                         fn_maybe_err(tcx, item.ident.span, abi);
807                     }
808                     hir::TraitItemKind::Type(.., Some(default)) => {
809                         let assoc_item = tcx.associated_item(item.def_id);
810                         let trait_substs =
811                             InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
812                         let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
813                             tcx,
814                             assoc_item,
815                             assoc_item,
816                             default.span,
817                             ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
818                         );
819                     }
820                     _ => {}
821                 }
822             }
823         }
824         DefKind::Struct => {
825             check_struct(tcx, id.def_id, tcx.def_span(id.def_id));
826         }
827         DefKind::Union => {
828             check_union(tcx, id.def_id, tcx.def_span(id.def_id));
829         }
830         DefKind::OpaqueTy => {
831             let item = tcx.hir().item(id);
832             let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
833                 return;
834             };
835             // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
836             // `async-std` (and `pub async fn` in general).
837             // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
838             // See https://github.com/rust-lang/rust/issues/75100
839             if !tcx.sess.opts.actually_rustdoc {
840                 let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id());
841                 check_opaque(tcx, item.def_id, substs, item.span, &origin);
842             }
843         }
844         DefKind::TyAlias => {
845             let pty_ty = tcx.type_of(id.def_id);
846             let generics = tcx.generics_of(id.def_id);
847             check_type_params_are_used(tcx, &generics, pty_ty);
848         }
849         DefKind::ForeignMod => {
850             let it = tcx.hir().item(id);
851             let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
852                 return;
853             };
854             check_abi(tcx, it.hir_id(), it.span, abi);
855
856             if abi == Abi::RustIntrinsic {
857                 for item in items {
858                     let item = tcx.hir().foreign_item(item.id);
859                     intrinsic::check_intrinsic_type(tcx, item);
860                 }
861             } else if abi == Abi::PlatformIntrinsic {
862                 for item in items {
863                     let item = tcx.hir().foreign_item(item.id);
864                     intrinsic::check_platform_intrinsic_type(tcx, item);
865                 }
866             } else {
867                 for item in items {
868                     let def_id = item.id.def_id;
869                     let generics = tcx.generics_of(def_id);
870                     let own_counts = generics.own_counts();
871                     if generics.params.len() - own_counts.lifetimes != 0 {
872                         let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
873                             (_, 0) => ("type", "types", Some("u32")),
874                             // We don't specify an example value, because we can't generate
875                             // a valid value for any type.
876                             (0, _) => ("const", "consts", None),
877                             _ => ("type or const", "types or consts", None),
878                         };
879                         struct_span_err!(
880                             tcx.sess,
881                             item.span,
882                             E0044,
883                             "foreign items may not have {kinds} parameters",
884                         )
885                         .span_label(item.span, &format!("can't have {kinds} parameters"))
886                         .help(
887                             // FIXME: once we start storing spans for type arguments, turn this
888                             // into a suggestion.
889                             &format!(
890                                 "replace the {} parameters with concrete {}{}",
891                                 kinds,
892                                 kinds_pl,
893                                 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
894                             ),
895                         )
896                         .emit();
897                     }
898
899                     let item = tcx.hir().foreign_item(item.id);
900                     match item.kind {
901                         hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
902                             require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
903                         }
904                         hir::ForeignItemKind::Static(..) => {
905                             check_static_inhabited(tcx, def_id, item.span);
906                         }
907                         _ => {}
908                     }
909                 }
910             }
911         }
912         DefKind::GlobalAsm => {
913             let it = tcx.hir().item(id);
914             let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
915             for_item(tcx, it).with_fcx(|fcx| {
916                 fcx.check_asm(asm, it.hir_id());
917                 Default::default()
918             })
919         }
920         _ => {}
921     }
922 }
923
924 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
925     // an error would be reported if this fails.
926     let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
927 }
928
929 pub(super) fn check_specialization_validity<'tcx>(
930     tcx: TyCtxt<'tcx>,
931     trait_def: &ty::TraitDef,
932     trait_item: &ty::AssocItem,
933     impl_id: DefId,
934     impl_item: &hir::ImplItemRef,
935 ) {
936     let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
937     let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
938         if parent.is_from_trait() {
939             None
940         } else {
941             Some((parent, parent.item(tcx, trait_item.def_id)))
942         }
943     });
944
945     let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
946         match parent_item {
947             // Parent impl exists, and contains the parent item we're trying to specialize, but
948             // doesn't mark it `default`.
949             Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
950                 Some(Err(parent_impl.def_id()))
951             }
952
953             // Parent impl contains item and makes it specializable.
954             Some(_) => Some(Ok(())),
955
956             // Parent impl doesn't mention the item. This means it's inherited from the
957             // grandparent. In that case, if parent is a `default impl`, inherited items use the
958             // "defaultness" from the grandparent, else they are final.
959             None => {
960                 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
961                     None
962                 } else {
963                     Some(Err(parent_impl.def_id()))
964                 }
965             }
966         }
967     });
968
969     // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
970     // item. This is allowed, the item isn't actually getting specialized here.
971     let result = opt_result.unwrap_or(Ok(()));
972
973     if let Err(parent_impl) = result {
974         report_forbidden_specialization(tcx, impl_item, parent_impl);
975     }
976 }
977
978 fn check_impl_items_against_trait<'tcx>(
979     tcx: TyCtxt<'tcx>,
980     full_impl_span: Span,
981     impl_id: LocalDefId,
982     impl_trait_ref: ty::TraitRef<'tcx>,
983     impl_item_refs: &[hir::ImplItemRef],
984 ) {
985     // If the trait reference itself is erroneous (so the compilation is going
986     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
987     // isn't populated for such impls.
988     if impl_trait_ref.references_error() {
989         return;
990     }
991
992     // Negative impls are not expected to have any items
993     match tcx.impl_polarity(impl_id) {
994         ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
995         ty::ImplPolarity::Negative => {
996             if let [first_item_ref, ..] = impl_item_refs {
997                 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
998                 struct_span_err!(
999                     tcx.sess,
1000                     first_item_span,
1001                     E0749,
1002                     "negative impls cannot have any items"
1003                 )
1004                 .emit();
1005             }
1006             return;
1007         }
1008     }
1009
1010     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1011
1012     for impl_item in impl_item_refs {
1013         let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
1014         let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1015             tcx.associated_item(trait_item_id)
1016         } else {
1017             // Checked in `associated_item`.
1018             tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
1019             continue;
1020         };
1021         let impl_item_full = tcx.hir().impl_item(impl_item.id);
1022         match impl_item_full.kind {
1023             hir::ImplItemKind::Const(..) => {
1024                 // Find associated const definition.
1025                 compare_const_impl(
1026                     tcx,
1027                     &ty_impl_item,
1028                     impl_item.span,
1029                     &ty_trait_item,
1030                     impl_trait_ref,
1031                 );
1032             }
1033             hir::ImplItemKind::Fn(..) => {
1034                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1035                 compare_impl_method(
1036                     tcx,
1037                     &ty_impl_item,
1038                     impl_item.span,
1039                     &ty_trait_item,
1040                     impl_trait_ref,
1041                     opt_trait_span,
1042                 );
1043             }
1044             hir::ImplItemKind::TyAlias(impl_ty) => {
1045                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1046                 compare_ty_impl(
1047                     tcx,
1048                     &ty_impl_item,
1049                     impl_ty.span,
1050                     &ty_trait_item,
1051                     impl_trait_ref,
1052                     opt_trait_span,
1053                 );
1054             }
1055         }
1056
1057         check_specialization_validity(
1058             tcx,
1059             trait_def,
1060             &ty_trait_item,
1061             impl_id.to_def_id(),
1062             impl_item,
1063         );
1064     }
1065
1066     if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1067         // Check for missing items from trait
1068         let mut missing_items = Vec::new();
1069
1070         let mut must_implement_one_of: Option<&[Ident]> =
1071             trait_def.must_implement_one_of.as_deref();
1072
1073         for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1074             let is_implemented = ancestors
1075                 .leaf_def(tcx, trait_item_id)
1076                 .map_or(false, |node_item| node_item.item.defaultness.has_value());
1077
1078             if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1079                 missing_items.push(tcx.associated_item(trait_item_id));
1080             }
1081
1082             if let Some(required_items) = &must_implement_one_of {
1083                 // true if this item is specifically implemented in this impl
1084                 let is_implemented_here = ancestors
1085                     .leaf_def(tcx, trait_item_id)
1086                     .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1087
1088                 if is_implemented_here {
1089                     let trait_item = tcx.associated_item(trait_item_id);
1090                     if required_items.contains(&trait_item.ident(tcx)) {
1091                         must_implement_one_of = None;
1092                     }
1093                 }
1094             }
1095         }
1096
1097         if !missing_items.is_empty() {
1098             let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1099             missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1100         }
1101
1102         if let Some(missing_items) = must_implement_one_of {
1103             let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1104             let attr_span = tcx
1105                 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
1106                 .map(|attr| attr.span);
1107
1108             missing_items_must_implement_one_of_err(tcx, impl_span, missing_items, attr_span);
1109         }
1110     }
1111 }
1112
1113 /// Checks whether a type can be represented in memory. In particular, it
1114 /// identifies types that contain themselves without indirection through a
1115 /// pointer, which would mean their size is unbounded.
1116 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1117     let rty = tcx.type_of(item_def_id);
1118
1119     // Check that it is possible to represent this type. This call identifies
1120     // (1) types that contain themselves and (2) types that contain a different
1121     // recursive type. It is only necessary to throw an error on those that
1122     // contain themselves. For case 2, there must be an inner type that will be
1123     // caught by case 1.
1124     match representability::ty_is_representable(tcx, rty, sp, None) {
1125         Representability::SelfRecursive(spans) => {
1126             recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1127             return false;
1128         }
1129         Representability::Representable | Representability::ContainsRecursive => (),
1130     }
1131     true
1132 }
1133
1134 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1135     let t = tcx.type_of(def_id);
1136     if let ty::Adt(def, substs) = t.kind()
1137         && def.is_struct()
1138     {
1139         let fields = &def.non_enum_variant().fields;
1140         if fields.is_empty() {
1141             struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1142             return;
1143         }
1144         let e = fields[0].ty(tcx, substs);
1145         if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1146             struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1147                 .span_label(sp, "SIMD elements must have the same type")
1148                 .emit();
1149             return;
1150         }
1151
1152         let len = if let ty::Array(_ty, c) = e.kind() {
1153             c.try_eval_usize(tcx, tcx.param_env(def.did()))
1154         } else {
1155             Some(fields.len() as u64)
1156         };
1157         if let Some(len) = len {
1158             if len == 0 {
1159                 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1160                 return;
1161             } else if len > MAX_SIMD_LANES {
1162                 struct_span_err!(
1163                     tcx.sess,
1164                     sp,
1165                     E0075,
1166                     "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1167                 )
1168                 .emit();
1169                 return;
1170             }
1171         }
1172
1173         // Check that we use types valid for use in the lanes of a SIMD "vector register"
1174         // These are scalar types which directly match a "machine" type
1175         // Yes: Integers, floats, "thin" pointers
1176         // No: char, "fat" pointers, compound types
1177         match e.kind() {
1178             ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1179             ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1180             ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1181             ty::Array(t, _clen)
1182                 if matches!(
1183                     t.kind(),
1184                     ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1185                 ) =>
1186             { /* struct([f32; 4]) is ok */ }
1187             _ => {
1188                 struct_span_err!(
1189                     tcx.sess,
1190                     sp,
1191                     E0077,
1192                     "SIMD vector element type should be a \
1193                         primitive scalar (integer/float/pointer) type"
1194                 )
1195                 .emit();
1196                 return;
1197             }
1198         }
1199     }
1200 }
1201
1202 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1203     let repr = def.repr();
1204     if repr.packed() {
1205         for attr in tcx.get_attrs(def.did(), sym::repr) {
1206             for r in attr::parse_repr_attr(&tcx.sess, attr) {
1207                 if let attr::ReprPacked(pack) = r
1208                 && let Some(repr_pack) = repr.pack
1209                 && pack as u64 != repr_pack.bytes()
1210             {
1211                         struct_span_err!(
1212                             tcx.sess,
1213                             sp,
1214                             E0634,
1215                             "type has conflicting packed representation hints"
1216                         )
1217                         .emit();
1218             }
1219             }
1220         }
1221         if repr.align.is_some() {
1222             struct_span_err!(
1223                 tcx.sess,
1224                 sp,
1225                 E0587,
1226                 "type has conflicting packed and align representation hints"
1227             )
1228             .emit();
1229         } else {
1230             if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1231                 let mut err = struct_span_err!(
1232                     tcx.sess,
1233                     sp,
1234                     E0588,
1235                     "packed type cannot transitively contain a `#[repr(align)]` type"
1236                 );
1237
1238                 err.span_note(
1239                     tcx.def_span(def_spans[0].0),
1240                     &format!(
1241                         "`{}` has a `#[repr(align)]` attribute",
1242                         tcx.item_name(def_spans[0].0)
1243                     ),
1244                 );
1245
1246                 if def_spans.len() > 2 {
1247                     let mut first = true;
1248                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
1249                         let ident = tcx.item_name(*adt_def);
1250                         err.span_note(
1251                             *span,
1252                             &if first {
1253                                 format!(
1254                                     "`{}` contains a field of type `{}`",
1255                                     tcx.type_of(def.did()),
1256                                     ident
1257                                 )
1258                             } else {
1259                                 format!("...which contains a field of type `{ident}`")
1260                             },
1261                         );
1262                         first = false;
1263                     }
1264                 }
1265
1266                 err.emit();
1267             }
1268         }
1269     }
1270 }
1271
1272 pub(super) fn check_packed_inner(
1273     tcx: TyCtxt<'_>,
1274     def_id: DefId,
1275     stack: &mut Vec<DefId>,
1276 ) -> Option<Vec<(DefId, Span)>> {
1277     if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1278         if def.is_struct() || def.is_union() {
1279             if def.repr().align.is_some() {
1280                 return Some(vec![(def.did(), DUMMY_SP)]);
1281             }
1282
1283             stack.push(def_id);
1284             for field in &def.non_enum_variant().fields {
1285                 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1286                     && !stack.contains(&def.did())
1287                     && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1288                 {
1289                     defs.push((def.did(), field.ident(tcx).span));
1290                     return Some(defs);
1291                 }
1292             }
1293             stack.pop();
1294         }
1295     }
1296
1297     None
1298 }
1299
1300 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1301     if !adt.repr().transparent() {
1302         return;
1303     }
1304     let sp = tcx.sess.source_map().guess_head_span(sp);
1305
1306     if adt.is_union() && !tcx.features().transparent_unions {
1307         feature_err(
1308             &tcx.sess.parse_sess,
1309             sym::transparent_unions,
1310             sp,
1311             "transparent unions are unstable",
1312         )
1313         .emit();
1314     }
1315
1316     if adt.variants().len() != 1 {
1317         bad_variant_count(tcx, adt, sp, adt.did());
1318         if adt.variants().is_empty() {
1319             // Don't bother checking the fields. No variants (and thus no fields) exist.
1320             return;
1321         }
1322     }
1323
1324     // For each field, figure out if it's known to be a ZST and align(1)
1325     let field_infos = adt.all_fields().map(|field| {
1326         let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1327         let param_env = tcx.param_env(field.did);
1328         let layout = tcx.layout_of(param_env.and(ty));
1329         // We are currently checking the type this field came from, so it must be local
1330         let span = tcx.hir().span_if_local(field.did).unwrap();
1331         let zst = layout.map_or(false, |layout| layout.is_zst());
1332         let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1333         (span, zst, align1)
1334     });
1335
1336     let non_zst_fields =
1337         field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1338     let non_zst_count = non_zst_fields.clone().count();
1339     if non_zst_count >= 2 {
1340         bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1341     }
1342     for (span, zst, align1) in field_infos {
1343         if zst && !align1 {
1344             struct_span_err!(
1345                 tcx.sess,
1346                 span,
1347                 E0691,
1348                 "zero-sized field in transparent {} has alignment larger than 1",
1349                 adt.descr(),
1350             )
1351             .span_label(span, "has alignment larger than 1")
1352             .emit();
1353         }
1354     }
1355 }
1356
1357 #[allow(trivial_numeric_casts)]
1358 fn check_enum<'tcx>(
1359     tcx: TyCtxt<'tcx>,
1360     sp: Span,
1361     vs: &'tcx [hir::Variant<'tcx>],
1362     def_id: LocalDefId,
1363 ) {
1364     let def = tcx.adt_def(def_id);
1365     def.destructor(tcx); // force the destructor to be evaluated
1366
1367     if vs.is_empty() {
1368         if let Some(attr) = tcx.get_attr(def_id.to_def_id(), sym::repr) {
1369             struct_span_err!(
1370                 tcx.sess,
1371                 attr.span,
1372                 E0084,
1373                 "unsupported representation for zero-variant enum"
1374             )
1375             .span_label(sp, "zero-variant enum")
1376             .emit();
1377         }
1378     }
1379
1380     let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1381     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1382         if !tcx.features().repr128 {
1383             feature_err(
1384                 &tcx.sess.parse_sess,
1385                 sym::repr128,
1386                 sp,
1387                 "repr with 128-bit type is unstable",
1388             )
1389             .emit();
1390         }
1391     }
1392
1393     for v in vs {
1394         if let Some(ref e) = v.disr_expr {
1395             tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1396         }
1397     }
1398
1399     if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1400         let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1401
1402         let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1403         let has_non_units = vs.iter().any(|var| !is_unit(var));
1404         let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1405         let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1406
1407         if disr_non_unit || (disr_units && has_non_units) {
1408             let mut err =
1409                 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1410             err.emit();
1411         }
1412     }
1413
1414     let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1415     // This tracks the previous variant span (in the loop) incase we need it for diagnostics
1416     let mut prev_variant_span: Span = DUMMY_SP;
1417     for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1418         // Check for duplicate discriminant values
1419         if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1420             let variant_did = def.variant(VariantIdx::new(i)).def_id;
1421             let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1422             let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1423             let i_span = match variant_i.disr_expr {
1424                 Some(ref expr) => tcx.hir().span(expr.hir_id),
1425                 None => tcx.def_span(variant_did),
1426             };
1427             let span = match v.disr_expr {
1428                 Some(ref expr) => tcx.hir().span(expr.hir_id),
1429                 None => v.span,
1430             };
1431             let display_discr = format_discriminant_overflow(tcx, v, discr);
1432             let display_discr_i = format_discriminant_overflow(tcx, variant_i, disr_vals[i]);
1433             let no_disr = v.disr_expr.is_none();
1434             let mut err = struct_span_err!(
1435                 tcx.sess,
1436                 sp,
1437                 E0081,
1438                 "discriminant value `{}` assigned more than once",
1439                 discr,
1440             );
1441
1442             err.span_label(i_span, format!("first assignment of {display_discr_i}"));
1443             err.span_label(span, format!("second assignment of {display_discr}"));
1444
1445             if no_disr {
1446                 err.span_label(
1447                     prev_variant_span,
1448                     format!(
1449                         "assigned discriminant for `{}` was incremented from this discriminant",
1450                         v.ident
1451                     ),
1452                 );
1453             }
1454             err.emit();
1455         }
1456
1457         disr_vals.push(discr);
1458         prev_variant_span = v.span;
1459     }
1460
1461     check_representable(tcx, sp, def_id);
1462     check_transparent(tcx, sp, def);
1463 }
1464
1465 /// In the case that a discriminant is both a duplicate and an overflowing literal,
1466 /// we insert both the assigned discriminant and the literal it overflowed from into the formatted
1467 /// output. Otherwise we format the discriminant normally.
1468 fn format_discriminant_overflow<'tcx>(
1469     tcx: TyCtxt<'tcx>,
1470     variant: &hir::Variant<'_>,
1471     dis: Discr<'tcx>,
1472 ) -> String {
1473     if let Some(expr) = &variant.disr_expr {
1474         let body = &tcx.hir().body(expr.body).value;
1475         if let hir::ExprKind::Lit(lit) = &body.kind
1476             && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1477             && dis.val != *lit_value
1478         {
1479                     return format!("`{dis}` (overflowed from `{lit_value}`)");
1480         }
1481     }
1482
1483     format!("`{dis}`")
1484 }
1485
1486 pub(super) fn check_type_params_are_used<'tcx>(
1487     tcx: TyCtxt<'tcx>,
1488     generics: &ty::Generics,
1489     ty: Ty<'tcx>,
1490 ) {
1491     debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1492
1493     assert_eq!(generics.parent, None);
1494
1495     if generics.own_counts().types == 0 {
1496         return;
1497     }
1498
1499     let mut params_used = BitSet::new_empty(generics.params.len());
1500
1501     if ty.references_error() {
1502         // If there is already another error, do not emit
1503         // an error for not using a type parameter.
1504         assert!(tcx.sess.has_errors().is_some());
1505         return;
1506     }
1507
1508     for leaf in ty.walk() {
1509         if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1510             && let ty::Param(param) = leaf_ty.kind()
1511         {
1512             debug!("found use of ty param {:?}", param);
1513             params_used.insert(param.index);
1514         }
1515     }
1516
1517     for param in &generics.params {
1518         if !params_used.contains(param.index)
1519             && let ty::GenericParamDefKind::Type { .. } = param.kind
1520         {
1521             let span = tcx.def_span(param.def_id);
1522             struct_span_err!(
1523                 tcx.sess,
1524                 span,
1525                 E0091,
1526                 "type parameter `{}` is unused",
1527                 param.name,
1528             )
1529             .span_label(span, "unused type parameter")
1530             .emit();
1531         }
1532     }
1533 }
1534
1535 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1536     let module = tcx.hir_module_items(module_def_id);
1537     for id in module.items() {
1538         check_item_type(tcx, id);
1539     }
1540 }
1541
1542 pub(super) use wfcheck::check_item_well_formed;
1543
1544 pub(super) use wfcheck::check_trait_item as check_trait_item_well_formed;
1545
1546 pub(super) use wfcheck::check_impl_item as check_impl_item_well_formed;
1547
1548 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1549     struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1550         .span_label(span, "recursive `async fn`")
1551         .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1552         .note(
1553             "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1554         )
1555         .emit()
1556 }
1557
1558 /// Emit an error for recursive opaque types.
1559 ///
1560 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1561 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1562 /// `impl Trait`.
1563 ///
1564 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1565 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1566 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1567     let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1568
1569     let mut label = false;
1570     if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1571         let typeck_results = tcx.typeck(def_id);
1572         if visitor
1573             .returns
1574             .iter()
1575             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1576             .all(|ty| matches!(ty.kind(), ty::Never))
1577         {
1578             let spans = visitor
1579                 .returns
1580                 .iter()
1581                 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1582                 .map(|expr| expr.span)
1583                 .collect::<Vec<Span>>();
1584             let span_len = spans.len();
1585             if span_len == 1 {
1586                 err.span_label(spans[0], "this returned value is of `!` type");
1587             } else {
1588                 let mut multispan: MultiSpan = spans.clone().into();
1589                 for span in spans {
1590                     multispan
1591                         .push_span_label(span, "this returned value is of `!` type".to_string());
1592                 }
1593                 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1594             }
1595             err.help("this error will resolve once the item's body returns a concrete type");
1596         } else {
1597             let mut seen = FxHashSet::default();
1598             seen.insert(span);
1599             err.span_label(span, "recursive opaque type");
1600             label = true;
1601             for (sp, ty) in visitor
1602                 .returns
1603                 .iter()
1604                 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1605                 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1606             {
1607                 struct OpaqueTypeCollector(Vec<DefId>);
1608                 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypeCollector {
1609                     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1610                         match *t.kind() {
1611                             ty::Opaque(def, _) => {
1612                                 self.0.push(def);
1613                                 ControlFlow::CONTINUE
1614                             }
1615                             _ => t.super_visit_with(self),
1616                         }
1617                     }
1618                 }
1619                 let mut visitor = OpaqueTypeCollector(vec![]);
1620                 ty.visit_with(&mut visitor);
1621                 for def_id in visitor.0 {
1622                     let ty_span = tcx.def_span(def_id);
1623                     if !seen.contains(&ty_span) {
1624                         err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1625                         seen.insert(ty_span);
1626                     }
1627                     err.span_label(sp, &format!("returning here with type `{ty}`"));
1628                 }
1629             }
1630         }
1631     }
1632     if !label {
1633         err.span_label(span, "cannot resolve opaque type");
1634     }
1635     err.emit()
1636 }