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