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