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