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