]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/check.rs
Rollup merge of #102187 - b-naber:inline-const-source-info, r=eholk
[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 /// ```ignore (illustrative)
711 /// type X<T> = impl Clone;
712 /// fn f<T: Clone>(t: T) -> X<T> {
713 ///     t
714 /// }
715 /// ```
716 ///
717 /// Without this check the above code is incorrectly accepted: we would ICE if
718 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
719 #[instrument(level = "debug", skip(tcx))]
720 fn check_opaque_meets_bounds<'tcx>(
721     tcx: TyCtxt<'tcx>,
722     def_id: LocalDefId,
723     substs: SubstsRef<'tcx>,
724     span: Span,
725     origin: &hir::OpaqueTyOrigin,
726 ) {
727     let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
728
729     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
730     let defining_use_anchor = match *origin {
731         hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
732         hir::OpaqueTyOrigin::TyAlias => def_id,
733     };
734     let param_env = tcx.param_env(defining_use_anchor);
735
736     let infcx = tcx
737         .infer_ctxt()
738         .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
739         .build();
740     let ocx = ObligationCtxt::new(&infcx);
741     let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
742
743     let misc_cause = traits::ObligationCause::misc(span, hir_id);
744
745     match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) {
746         Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok),
747         Err(ty_err) => {
748             tcx.sess.delay_span_bug(
749                 span,
750                 &format!("could not unify `{hidden_type}` with revealed type:\n{ty_err}"),
751             );
752         }
753     }
754
755     // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
756     // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
757     // hidden type is well formed even without those bounds.
758     let predicate =
759         ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx);
760     ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate));
761
762     // Check that all obligations are satisfied by the implementation's
763     // version.
764     let errors = ocx.select_all_or_error();
765     if !errors.is_empty() {
766         infcx.err_ctxt().report_fulfillment_errors(&errors, None, false);
767     }
768     match origin {
769         // Checked when type checking the function containing them.
770         hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
771         // Can have different predicates to their defining use
772         hir::OpaqueTyOrigin::TyAlias => {
773             let outlives_environment = OutlivesEnvironment::new(param_env);
774             infcx.check_region_obligations_and_report_errors(
775                 defining_use_anchor,
776                 &outlives_environment,
777             );
778         }
779     }
780     // Clean up after ourselves
781     let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
782 }
783
784 fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
785     debug!(
786         "check_item_type(it.def_id={:?}, it.name={})",
787         id.def_id,
788         tcx.def_path_str(id.def_id.to_def_id())
789     );
790     let _indenter = indenter();
791     match tcx.def_kind(id.def_id) {
792         DefKind::Static(..) => {
793             tcx.ensure().typeck(id.def_id.def_id);
794             maybe_check_static_with_link_section(tcx, id.def_id.def_id);
795             check_static_inhabited(tcx, id.def_id.def_id);
796         }
797         DefKind::Const => {
798             tcx.ensure().typeck(id.def_id.def_id);
799         }
800         DefKind::Enum => {
801             let item = tcx.hir().item(id);
802             let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else {
803                 return;
804             };
805             check_enum(tcx, &enum_definition.variants, item.def_id.def_id);
806         }
807         DefKind::Fn => {} // entirely within check_item_body
808         DefKind::Impl => {
809             let it = tcx.hir().item(id);
810             let hir::ItemKind::Impl(ref impl_) = it.kind else {
811                 return;
812             };
813             debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
814             if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
815                 check_impl_items_against_trait(
816                     tcx,
817                     it.span,
818                     it.def_id.def_id,
819                     impl_trait_ref,
820                     &impl_.items,
821                 );
822                 check_on_unimplemented(tcx, it);
823             }
824         }
825         DefKind::Trait => {
826             let it = tcx.hir().item(id);
827             let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
828                 return;
829             };
830             check_on_unimplemented(tcx, it);
831
832             for item in items.iter() {
833                 let item = tcx.hir().trait_item(item.id);
834                 match item.kind {
835                     hir::TraitItemKind::Fn(ref sig, _) => {
836                         let abi = sig.header.abi;
837                         fn_maybe_err(tcx, item.ident.span, abi);
838                     }
839                     hir::TraitItemKind::Type(.., Some(default)) => {
840                         let assoc_item = tcx.associated_item(item.def_id);
841                         let trait_substs =
842                             InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
843                         let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
844                             tcx,
845                             assoc_item,
846                             assoc_item,
847                             default.span,
848                             ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
849                         );
850                     }
851                     _ => {}
852                 }
853             }
854         }
855         DefKind::Struct => {
856             check_struct(tcx, id.def_id.def_id);
857         }
858         DefKind::Union => {
859             check_union(tcx, id.def_id.def_id);
860         }
861         DefKind::OpaqueTy => {
862             let item = tcx.hir().item(id);
863             let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
864                 return;
865             };
866             // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
867             // `async-std` (and `pub async fn` in general).
868             // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
869             // See https://github.com/rust-lang/rust/issues/75100
870             if !tcx.sess.opts.actually_rustdoc {
871                 let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id());
872                 check_opaque(tcx, item.def_id.def_id, substs, &origin);
873             }
874         }
875         DefKind::TyAlias => {
876             let pty_ty = tcx.type_of(id.def_id);
877             let generics = tcx.generics_of(id.def_id);
878             check_type_params_are_used(tcx, &generics, pty_ty);
879         }
880         DefKind::ForeignMod => {
881             let it = tcx.hir().item(id);
882             let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
883                 return;
884             };
885             check_abi(tcx, it.hir_id(), it.span, abi);
886
887             if abi == Abi::RustIntrinsic {
888                 for item in items {
889                     let item = tcx.hir().foreign_item(item.id);
890                     intrinsic::check_intrinsic_type(tcx, item);
891                 }
892             } else if abi == Abi::PlatformIntrinsic {
893                 for item in items {
894                     let item = tcx.hir().foreign_item(item.id);
895                     intrinsic::check_platform_intrinsic_type(tcx, item);
896                 }
897             } else {
898                 for item in items {
899                     let def_id = item.id.def_id.def_id;
900                     let generics = tcx.generics_of(def_id);
901                     let own_counts = generics.own_counts();
902                     if generics.params.len() - own_counts.lifetimes != 0 {
903                         let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
904                             (_, 0) => ("type", "types", Some("u32")),
905                             // We don't specify an example value, because we can't generate
906                             // a valid value for any type.
907                             (0, _) => ("const", "consts", None),
908                             _ => ("type or const", "types or consts", None),
909                         };
910                         struct_span_err!(
911                             tcx.sess,
912                             item.span,
913                             E0044,
914                             "foreign items may not have {kinds} parameters",
915                         )
916                         .span_label(item.span, &format!("can't have {kinds} parameters"))
917                         .help(
918                             // FIXME: once we start storing spans for type arguments, turn this
919                             // into a suggestion.
920                             &format!(
921                                 "replace the {} parameters with concrete {}{}",
922                                 kinds,
923                                 kinds_pl,
924                                 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
925                             ),
926                         )
927                         .emit();
928                     }
929
930                     let item = tcx.hir().foreign_item(item.id);
931                     match item.kind {
932                         hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
933                             require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
934                         }
935                         hir::ForeignItemKind::Static(..) => {
936                             check_static_inhabited(tcx, def_id);
937                         }
938                         _ => {}
939                     }
940                 }
941             }
942         }
943         DefKind::GlobalAsm => {
944             let it = tcx.hir().item(id);
945             let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
946             InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
947         }
948         _ => {}
949     }
950 }
951
952 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
953     // an error would be reported if this fails.
954     let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
955 }
956
957 pub(super) fn check_specialization_validity<'tcx>(
958     tcx: TyCtxt<'tcx>,
959     trait_def: &ty::TraitDef,
960     trait_item: &ty::AssocItem,
961     impl_id: DefId,
962     impl_item: &hir::ImplItemRef,
963 ) {
964     let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
965     let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
966         if parent.is_from_trait() {
967             None
968         } else {
969             Some((parent, parent.item(tcx, trait_item.def_id)))
970         }
971     });
972
973     let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
974         match parent_item {
975             // Parent impl exists, and contains the parent item we're trying to specialize, but
976             // doesn't mark it `default`.
977             Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
978                 Some(Err(parent_impl.def_id()))
979             }
980
981             // Parent impl contains item and makes it specializable.
982             Some(_) => Some(Ok(())),
983
984             // Parent impl doesn't mention the item. This means it's inherited from the
985             // grandparent. In that case, if parent is a `default impl`, inherited items use the
986             // "defaultness" from the grandparent, else they are final.
987             None => {
988                 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
989                     None
990                 } else {
991                     Some(Err(parent_impl.def_id()))
992                 }
993             }
994         }
995     });
996
997     // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
998     // item. This is allowed, the item isn't actually getting specialized here.
999     let result = opt_result.unwrap_or(Ok(()));
1000
1001     if let Err(parent_impl) = result {
1002         report_forbidden_specialization(tcx, impl_item, parent_impl);
1003     }
1004 }
1005
1006 fn check_impl_items_against_trait<'tcx>(
1007     tcx: TyCtxt<'tcx>,
1008     full_impl_span: Span,
1009     impl_id: LocalDefId,
1010     impl_trait_ref: ty::TraitRef<'tcx>,
1011     impl_item_refs: &[hir::ImplItemRef],
1012 ) {
1013     // If the trait reference itself is erroneous (so the compilation is going
1014     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1015     // isn't populated for such impls.
1016     if impl_trait_ref.references_error() {
1017         return;
1018     }
1019
1020     // Negative impls are not expected to have any items
1021     match tcx.impl_polarity(impl_id) {
1022         ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1023         ty::ImplPolarity::Negative => {
1024             if let [first_item_ref, ..] = impl_item_refs {
1025                 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
1026                 struct_span_err!(
1027                     tcx.sess,
1028                     first_item_span,
1029                     E0749,
1030                     "negative impls cannot have any items"
1031                 )
1032                 .emit();
1033             }
1034             return;
1035         }
1036     }
1037
1038     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1039
1040     for impl_item in impl_item_refs {
1041         let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
1042         let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1043             tcx.associated_item(trait_item_id)
1044         } else {
1045             // Checked in `associated_item`.
1046             tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
1047             continue;
1048         };
1049         let impl_item_full = tcx.hir().impl_item(impl_item.id);
1050         match impl_item_full.kind {
1051             hir::ImplItemKind::Const(..) => {
1052                 let _ = tcx.compare_assoc_const_impl_item_with_trait_item((
1053                     impl_item.id.def_id.def_id,
1054                     ty_impl_item.trait_item_def_id.unwrap(),
1055                 ));
1056             }
1057             hir::ImplItemKind::Fn(..) => {
1058                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1059                 compare_impl_method(
1060                     tcx,
1061                     &ty_impl_item,
1062                     &ty_trait_item,
1063                     impl_trait_ref,
1064                     opt_trait_span,
1065                 );
1066             }
1067             hir::ImplItemKind::Type(impl_ty) => {
1068                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1069                 compare_ty_impl(
1070                     tcx,
1071                     &ty_impl_item,
1072                     impl_ty.span,
1073                     &ty_trait_item,
1074                     impl_trait_ref,
1075                     opt_trait_span,
1076                 );
1077             }
1078         }
1079
1080         check_specialization_validity(
1081             tcx,
1082             trait_def,
1083             &ty_trait_item,
1084             impl_id.to_def_id(),
1085             impl_item,
1086         );
1087     }
1088
1089     if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1090         // Check for missing items from trait
1091         let mut missing_items = Vec::new();
1092
1093         let mut must_implement_one_of: Option<&[Ident]> =
1094             trait_def.must_implement_one_of.as_deref();
1095
1096         for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1097             let is_implemented = ancestors
1098                 .leaf_def(tcx, trait_item_id)
1099                 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
1100
1101             if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1102                 missing_items.push(tcx.associated_item(trait_item_id));
1103             }
1104
1105             // true if this item is specifically implemented in this impl
1106             let is_implemented_here = ancestors
1107                 .leaf_def(tcx, trait_item_id)
1108                 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1109
1110             if !is_implemented_here {
1111                 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1112                     EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1113                         tcx,
1114                         full_impl_span,
1115                         trait_item_id,
1116                         feature,
1117                         reason,
1118                         issue,
1119                     ),
1120
1121                     // Unmarked default bodies are considered stable (at least for now).
1122                     EvalResult::Allow | EvalResult::Unmarked => {}
1123                 }
1124             }
1125
1126             if let Some(required_items) = &must_implement_one_of {
1127                 if is_implemented_here {
1128                     let trait_item = tcx.associated_item(trait_item_id);
1129                     if required_items.contains(&trait_item.ident(tcx)) {
1130                         must_implement_one_of = None;
1131                     }
1132                 }
1133             }
1134         }
1135
1136         if !missing_items.is_empty() {
1137             missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
1138         }
1139
1140         if let Some(missing_items) = must_implement_one_of {
1141             let attr_span = tcx
1142                 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
1143                 .map(|attr| attr.span);
1144
1145             missing_items_must_implement_one_of_err(
1146                 tcx,
1147                 tcx.def_span(impl_id),
1148                 missing_items,
1149                 attr_span,
1150             );
1151         }
1152     }
1153 }
1154
1155 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1156     let t = tcx.type_of(def_id);
1157     if let ty::Adt(def, substs) = t.kind()
1158         && def.is_struct()
1159     {
1160         let fields = &def.non_enum_variant().fields;
1161         if fields.is_empty() {
1162             struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1163             return;
1164         }
1165         let e = fields[0].ty(tcx, substs);
1166         if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1167             struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1168                 .span_label(sp, "SIMD elements must have the same type")
1169                 .emit();
1170             return;
1171         }
1172
1173         let len = if let ty::Array(_ty, c) = e.kind() {
1174             c.try_eval_usize(tcx, tcx.param_env(def.did()))
1175         } else {
1176             Some(fields.len() as u64)
1177         };
1178         if let Some(len) = len {
1179             if len == 0 {
1180                 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1181                 return;
1182             } else if len > MAX_SIMD_LANES {
1183                 struct_span_err!(
1184                     tcx.sess,
1185                     sp,
1186                     E0075,
1187                     "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1188                 )
1189                 .emit();
1190                 return;
1191             }
1192         }
1193
1194         // Check that we use types valid for use in the lanes of a SIMD "vector register"
1195         // These are scalar types which directly match a "machine" type
1196         // Yes: Integers, floats, "thin" pointers
1197         // No: char, "fat" pointers, compound types
1198         match e.kind() {
1199             ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1200             ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1201             ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1202             ty::Array(t, _clen)
1203                 if matches!(
1204                     t.kind(),
1205                     ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1206                 ) =>
1207             { /* struct([f32; 4]) is ok */ }
1208             _ => {
1209                 struct_span_err!(
1210                     tcx.sess,
1211                     sp,
1212                     E0077,
1213                     "SIMD vector element type should be a \
1214                         primitive scalar (integer/float/pointer) type"
1215                 )
1216                 .emit();
1217                 return;
1218             }
1219         }
1220     }
1221 }
1222
1223 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1224     let repr = def.repr();
1225     if repr.packed() {
1226         for attr in tcx.get_attrs(def.did(), sym::repr) {
1227             for r in attr::parse_repr_attr(&tcx.sess, attr) {
1228                 if let attr::ReprPacked(pack) = r
1229                 && let Some(repr_pack) = repr.pack
1230                 && pack as u64 != repr_pack.bytes()
1231             {
1232                         struct_span_err!(
1233                             tcx.sess,
1234                             sp,
1235                             E0634,
1236                             "type has conflicting packed representation hints"
1237                         )
1238                         .emit();
1239             }
1240             }
1241         }
1242         if repr.align.is_some() {
1243             struct_span_err!(
1244                 tcx.sess,
1245                 sp,
1246                 E0587,
1247                 "type has conflicting packed and align representation hints"
1248             )
1249             .emit();
1250         } else {
1251             if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1252                 let mut err = struct_span_err!(
1253                     tcx.sess,
1254                     sp,
1255                     E0588,
1256                     "packed type cannot transitively contain a `#[repr(align)]` type"
1257                 );
1258
1259                 err.span_note(
1260                     tcx.def_span(def_spans[0].0),
1261                     &format!(
1262                         "`{}` has a `#[repr(align)]` attribute",
1263                         tcx.item_name(def_spans[0].0)
1264                     ),
1265                 );
1266
1267                 if def_spans.len() > 2 {
1268                     let mut first = true;
1269                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
1270                         let ident = tcx.item_name(*adt_def);
1271                         err.span_note(
1272                             *span,
1273                             &if first {
1274                                 format!(
1275                                     "`{}` contains a field of type `{}`",
1276                                     tcx.type_of(def.did()),
1277                                     ident
1278                                 )
1279                             } else {
1280                                 format!("...which contains a field of type `{ident}`")
1281                             },
1282                         );
1283                         first = false;
1284                     }
1285                 }
1286
1287                 err.emit();
1288             }
1289         }
1290     }
1291 }
1292
1293 pub(super) fn check_packed_inner(
1294     tcx: TyCtxt<'_>,
1295     def_id: DefId,
1296     stack: &mut Vec<DefId>,
1297 ) -> Option<Vec<(DefId, Span)>> {
1298     if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1299         if def.is_struct() || def.is_union() {
1300             if def.repr().align.is_some() {
1301                 return Some(vec![(def.did(), DUMMY_SP)]);
1302             }
1303
1304             stack.push(def_id);
1305             for field in &def.non_enum_variant().fields {
1306                 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1307                     && !stack.contains(&def.did())
1308                     && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1309                 {
1310                     defs.push((def.did(), field.ident(tcx).span));
1311                     return Some(defs);
1312                 }
1313             }
1314             stack.pop();
1315         }
1316     }
1317
1318     None
1319 }
1320
1321 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1322     if !adt.repr().transparent() {
1323         return;
1324     }
1325
1326     if adt.is_union() && !tcx.features().transparent_unions {
1327         feature_err(
1328             &tcx.sess.parse_sess,
1329             sym::transparent_unions,
1330             sp,
1331             "transparent unions are unstable",
1332         )
1333         .emit();
1334     }
1335
1336     if adt.variants().len() != 1 {
1337         bad_variant_count(tcx, adt, sp, adt.did());
1338         if adt.variants().is_empty() {
1339             // Don't bother checking the fields. No variants (and thus no fields) exist.
1340             return;
1341         }
1342     }
1343
1344     // For each field, figure out if it's known to be a ZST and align(1), with "known"
1345     // respecting #[non_exhaustive] attributes.
1346     let field_infos = adt.all_fields().map(|field| {
1347         let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1348         let param_env = tcx.param_env(field.did);
1349         let layout = tcx.layout_of(param_env.and(ty));
1350         // We are currently checking the type this field came from, so it must be local
1351         let span = tcx.hir().span_if_local(field.did).unwrap();
1352         let zst = layout.map_or(false, |layout| layout.is_zst());
1353         let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1354         if !zst {
1355             return (span, zst, align1, None);
1356         }
1357
1358         fn check_non_exhaustive<'tcx>(
1359             tcx: TyCtxt<'tcx>,
1360             t: Ty<'tcx>,
1361         ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1362             match t.kind() {
1363                 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1364                 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1365                 ty::Adt(def, subst) => {
1366                     if !def.did().is_local() {
1367                         let non_exhaustive = def.is_variant_list_non_exhaustive()
1368                             || def
1369                                 .variants()
1370                                 .iter()
1371                                 .any(ty::VariantDef::is_field_list_non_exhaustive);
1372                         let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1373                         if non_exhaustive || has_priv {
1374                             return ControlFlow::Break((
1375                                 def.descr(),
1376                                 def.did(),
1377                                 subst,
1378                                 non_exhaustive,
1379                             ));
1380                         }
1381                     }
1382                     def.all_fields()
1383                         .map(|field| field.ty(tcx, subst))
1384                         .try_for_each(|t| check_non_exhaustive(tcx, t))
1385                 }
1386                 _ => ControlFlow::Continue(()),
1387             }
1388         }
1389
1390         (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1391     });
1392
1393     let non_zst_fields = field_infos
1394         .clone()
1395         .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1396     let non_zst_count = non_zst_fields.clone().count();
1397     if non_zst_count >= 2 {
1398         bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1399     }
1400     let incompatible_zst_fields =
1401         field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1402     let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1403     for (span, zst, align1, non_exhaustive) in field_infos {
1404         if zst && !align1 {
1405             struct_span_err!(
1406                 tcx.sess,
1407                 span,
1408                 E0691,
1409                 "zero-sized field in transparent {} has alignment larger than 1",
1410                 adt.descr(),
1411             )
1412             .span_label(span, "has alignment larger than 1")
1413             .emit();
1414         }
1415         if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1416             tcx.struct_span_lint_hir(
1417                 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1418                 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1419                 span,
1420                 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1421                 |lint| {
1422                     let note = if non_exhaustive {
1423                         "is marked with `#[non_exhaustive]`"
1424                     } else {
1425                         "contains private fields"
1426                     };
1427                     let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1428                     lint
1429                         .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1430                             and makes it not a breaking change to become non-zero-sized in the future."))
1431                 },
1432             )
1433         }
1434     }
1435 }
1436
1437 #[allow(trivial_numeric_casts)]
1438 fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: LocalDefId) {
1439     let def = tcx.adt_def(def_id);
1440     let sp = tcx.def_span(def_id);
1441     def.destructor(tcx); // force the destructor to be evaluated
1442
1443     if vs.is_empty() {
1444         if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1445             struct_span_err!(
1446                 tcx.sess,
1447                 attr.span,
1448                 E0084,
1449                 "unsupported representation for zero-variant enum"
1450             )
1451             .span_label(sp, "zero-variant enum")
1452             .emit();
1453         }
1454     }
1455
1456     let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1457     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1458         if !tcx.features().repr128 {
1459             feature_err(
1460                 &tcx.sess.parse_sess,
1461                 sym::repr128,
1462                 sp,
1463                 "repr with 128-bit type is unstable",
1464             )
1465             .emit();
1466         }
1467     }
1468
1469     for v in vs {
1470         if let Some(ref e) = v.disr_expr {
1471             tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1472         }
1473     }
1474
1475     if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1476         let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1477
1478         let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1479         let has_non_units = vs.iter().any(|var| !is_unit(var));
1480         let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1481         let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1482
1483         if disr_non_unit || (disr_units && has_non_units) {
1484             let mut err =
1485                 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1486             err.emit();
1487         }
1488     }
1489
1490     detect_discriminant_duplicate(tcx, def.discriminants(tcx).collect(), vs, sp);
1491
1492     let _ = tcx.representability(def_id);
1493     check_transparent(tcx, sp, def);
1494 }
1495
1496 /// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1497 fn detect_discriminant_duplicate<'tcx>(
1498     tcx: TyCtxt<'tcx>,
1499     mut discrs: Vec<(VariantIdx, Discr<'tcx>)>,
1500     vs: &'tcx [hir::Variant<'tcx>],
1501     self_span: Span,
1502 ) {
1503     // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1504     // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1505     let report = |dis: Discr<'tcx>, idx: usize, err: &mut Diagnostic| {
1506         let var = &vs[idx]; // HIR for the duplicate discriminant
1507         let (span, display_discr) = match var.disr_expr {
1508             Some(ref expr) => {
1509                 // In the case the discriminant is both a duplicate and overflowed, let the user know
1510                 if let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1511                     && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1512                     && *lit_value != dis.val
1513                 {
1514                     (tcx.hir().span(expr.hir_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1515                 // Otherwise, format the value as-is
1516                 } else {
1517                     (tcx.hir().span(expr.hir_id), format!("`{dis}`"))
1518                 }
1519             }
1520             None => {
1521                 // At this point we know this discriminant is a duplicate, and was not explicitly
1522                 // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1523                 // explicitly assigned discriminant, and letting the user know that this was the
1524                 // increment startpoint, and how many steps from there leading to the duplicate
1525                 if let Some((n, hir::Variant { span, ident, .. })) =
1526                     vs[..idx].iter().rev().enumerate().find(|v| v.1.disr_expr.is_some())
1527                 {
1528                     let ve_ident = var.ident;
1529                     let n = n + 1;
1530                     let sp = if n > 1 { "variants" } else { "variant" };
1531
1532                     err.span_label(
1533                         *span,
1534                         format!("discriminant for `{ve_ident}` incremented from this startpoint (`{ident}` + {n} {sp} later => `{ve_ident}` = {dis})"),
1535                     );
1536                 }
1537
1538                 (vs[idx].span, format!("`{dis}`"))
1539             }
1540         };
1541
1542         err.span_label(span, format!("{display_discr} assigned here"));
1543     };
1544
1545     // Here we loop through the discriminants, comparing each discriminant to another.
1546     // When a duplicate is detected, we instantiate an error and point to both
1547     // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1548     // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1549     // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1550     // style as we are mutating `discrs` on the fly).
1551     let mut i = 0;
1552     while i < discrs.len() {
1553         let hir_var_i_idx = discrs[i].0.index();
1554         let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1555
1556         let mut o = i + 1;
1557         while o < discrs.len() {
1558             let hir_var_o_idx = discrs[o].0.index();
1559
1560             if discrs[i].1.val == discrs[o].1.val {
1561                 let err = error.get_or_insert_with(|| {
1562                     let mut ret = struct_span_err!(
1563                         tcx.sess,
1564                         self_span,
1565                         E0081,
1566                         "discriminant value `{}` assigned more than once",
1567                         discrs[i].1,
1568                     );
1569
1570                     report(discrs[i].1, hir_var_i_idx, &mut ret);
1571
1572                     ret
1573                 });
1574
1575                 report(discrs[o].1, hir_var_o_idx, err);
1576
1577                 // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1578                 discrs[o] = *discrs.last().unwrap();
1579                 discrs.pop();
1580             } else {
1581                 o += 1;
1582             }
1583         }
1584
1585         if let Some(mut e) = error {
1586             e.emit();
1587         }
1588
1589         i += 1;
1590     }
1591 }
1592
1593 pub(super) fn check_type_params_are_used<'tcx>(
1594     tcx: TyCtxt<'tcx>,
1595     generics: &ty::Generics,
1596     ty: Ty<'tcx>,
1597 ) {
1598     debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1599
1600     assert_eq!(generics.parent, None);
1601
1602     if generics.own_counts().types == 0 {
1603         return;
1604     }
1605
1606     let mut params_used = BitSet::new_empty(generics.params.len());
1607
1608     if ty.references_error() {
1609         // If there is already another error, do not emit
1610         // an error for not using a type parameter.
1611         assert!(tcx.sess.has_errors().is_some());
1612         return;
1613     }
1614
1615     for leaf in ty.walk() {
1616         if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1617             && let ty::Param(param) = leaf_ty.kind()
1618         {
1619             debug!("found use of ty param {:?}", param);
1620             params_used.insert(param.index);
1621         }
1622     }
1623
1624     for param in &generics.params {
1625         if !params_used.contains(param.index)
1626             && let ty::GenericParamDefKind::Type { .. } = param.kind
1627         {
1628             let span = tcx.def_span(param.def_id);
1629             struct_span_err!(
1630                 tcx.sess,
1631                 span,
1632                 E0091,
1633                 "type parameter `{}` is unused",
1634                 param.name,
1635             )
1636             .span_label(span, "unused type parameter")
1637             .emit();
1638         }
1639     }
1640 }
1641
1642 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1643     let module = tcx.hir_module_items(module_def_id);
1644     for id in module.items() {
1645         check_item_type(tcx, id);
1646     }
1647 }
1648
1649 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1650     struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1651         .span_label(span, "recursive `async fn`")
1652         .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1653         .note(
1654             "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1655         )
1656         .emit()
1657 }
1658
1659 /// Emit an error for recursive opaque types.
1660 ///
1661 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1662 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1663 /// `impl Trait`.
1664 ///
1665 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1666 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1667 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1668     let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1669
1670     let mut label = false;
1671     if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1672         let typeck_results = tcx.typeck(def_id);
1673         if visitor
1674             .returns
1675             .iter()
1676             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1677             .all(|ty| matches!(ty.kind(), ty::Never))
1678         {
1679             let spans = visitor
1680                 .returns
1681                 .iter()
1682                 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1683                 .map(|expr| expr.span)
1684                 .collect::<Vec<Span>>();
1685             let span_len = spans.len();
1686             if span_len == 1 {
1687                 err.span_label(spans[0], "this returned value is of `!` type");
1688             } else {
1689                 let mut multispan: MultiSpan = spans.clone().into();
1690                 for span in spans {
1691                     multispan.push_span_label(span, "this returned value is of `!` type");
1692                 }
1693                 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1694             }
1695             err.help("this error will resolve once the item's body returns a concrete type");
1696         } else {
1697             let mut seen = FxHashSet::default();
1698             seen.insert(span);
1699             err.span_label(span, "recursive opaque type");
1700             label = true;
1701             for (sp, ty) in visitor
1702                 .returns
1703                 .iter()
1704                 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1705                 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1706             {
1707                 struct OpaqueTypeCollector(Vec<DefId>);
1708                 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypeCollector {
1709                     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1710                         match *t.kind() {
1711                             ty::Opaque(def, _) => {
1712                                 self.0.push(def);
1713                                 ControlFlow::CONTINUE
1714                             }
1715                             _ => t.super_visit_with(self),
1716                         }
1717                     }
1718                 }
1719                 let mut visitor = OpaqueTypeCollector(vec![]);
1720                 ty.visit_with(&mut visitor);
1721                 for def_id in visitor.0 {
1722                     let ty_span = tcx.def_span(def_id);
1723                     if !seen.contains(&ty_span) {
1724                         err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1725                         seen.insert(ty_span);
1726                     }
1727                     err.span_label(sp, &format!("returning here with type `{ty}`"));
1728                 }
1729             }
1730         }
1731     }
1732     if !label {
1733         err.span_label(span, "cannot resolve opaque type");
1734     }
1735     err.emit()
1736 }