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