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