]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/check.rs
Auto merge of #102783 - RalfJung:tls, r=thomcc
[rust.git] / compiler / rustc_hir_analysis / src / check / check.rs
1 use crate::check::intrinsicck::InlineAsmCtxt;
2
3 use super::coercion::CoerceMany;
4 use super::compare_method::check_type_bounds;
5 use super::compare_method::{compare_impl_method, compare_ty_impl};
6 use super::*;
7 use rustc_attr as attr;
8 use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_hir::{ItemKind, Node, PathSegment};
15 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
16 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17 use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt};
18 use rustc_infer::traits::Obligation;
19 use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::middle::stability::EvalResult;
22 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
23 use rustc_middle::ty::subst::GenericArgKind;
24 use rustc_middle::ty::util::{Discr, IntTypeExt};
25 use rustc_middle::ty::{
26     self, ParamEnv, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
27 };
28 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
29 use rustc_span::symbol::sym;
30 use rustc_span::{self, Span};
31 use rustc_target::spec::abi::Abi;
32 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
33 use rustc_trait_selection::traits::{self, ObligationCtxt};
34
35 use std::ops::ControlFlow;
36
37 pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
38     match tcx.sess.target.is_abi_supported(abi) {
39         Some(true) => (),
40         Some(false) => {
41             struct_span_err!(
42                 tcx.sess,
43                 span,
44                 E0570,
45                 "`{abi}` is not a supported ABI for the current target",
46             )
47             .emit();
48         }
49         None => {
50             tcx.struct_span_lint_hir(
51                 UNSUPPORTED_CALLING_CONVENTIONS,
52                 hir_id,
53                 span,
54                 "use of calling convention not supported on this target",
55                 |lint| lint,
56             );
57         }
58     }
59
60     // This ABI is only allowed on function pointers
61     if abi == Abi::CCmseNonSecureCall {
62         struct_span_err!(
63             tcx.sess,
64             span,
65             E0781,
66             "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
67         )
68         .emit();
69     }
70 }
71
72 /// Helper used for fns and closures. Does the grungy work of checking a function
73 /// body and returns the function context used for that purpose, since in the case of a fn item
74 /// there is still a bit more to do.
75 ///
76 /// * ...
77 /// * inherited: other fields inherited from the enclosing fn (if any)
78 #[instrument(skip(inherited, body), level = "debug")]
79 pub(super) fn check_fn<'a, 'tcx>(
80     inherited: &'a Inherited<'tcx>,
81     param_env: ty::ParamEnv<'tcx>,
82     fn_sig: ty::FnSig<'tcx>,
83     decl: &'tcx hir::FnDecl<'tcx>,
84     fn_id: hir::HirId,
85     body: &'tcx hir::Body<'tcx>,
86     can_be_generator: Option<hir::Movability>,
87     return_type_pre_known: bool,
88 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
89     // Create the function context. This is either derived from scratch or,
90     // in the case of closures, based on the outer context.
91     let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
92     fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
93     fcx.return_type_pre_known = return_type_pre_known;
94
95     let tcx = fcx.tcx;
96     let hir = tcx.hir();
97
98     let declared_ret_ty = fn_sig.output();
99
100     let ret_ty =
101         fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
102             declared_ret_ty,
103             body.value.hir_id,
104             decl.output.span(),
105             param_env,
106         ));
107     // If we replaced declared_ret_ty with infer vars, then we must be inferring
108     // an opaque type, so set a flag so we can improve diagnostics.
109     fcx.return_type_has_opaque = ret_ty != declared_ret_ty;
110
111     fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
112
113     let span = body.value.span;
114
115     fn_maybe_err(tcx, span, fn_sig.abi);
116
117     if fn_sig.abi == Abi::RustCall {
118         let expected_args = if let ImplicitSelfKind::None = decl.implicit_self { 1 } else { 2 };
119
120         let err = || {
121             let item = match tcx.hir().get(fn_id) {
122                 Node::Item(hir::Item { kind: ItemKind::Fn(header, ..), .. }) => Some(header),
123                 Node::ImplItem(hir::ImplItem {
124                     kind: hir::ImplItemKind::Fn(header, ..), ..
125                 }) => Some(header),
126                 Node::TraitItem(hir::TraitItem {
127                     kind: hir::TraitItemKind::Fn(header, ..),
128                     ..
129                 }) => Some(header),
130                 // Closures are RustCall, but they tuple their arguments, so shouldn't be checked
131                 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => None,
132                 node => bug!("Item being checked wasn't a function/closure: {:?}", node),
133             };
134
135             if let Some(header) = item {
136                 tcx.sess.span_err(header.span, "functions with the \"rust-call\" ABI must take a single non-self argument that is a tuple");
137             }
138         };
139
140         if fn_sig.inputs().len() != expected_args {
141             err()
142         } else {
143             // FIXME(CraftSpider) Add a check on parameter expansion, so we don't just make the ICE happen later on
144             //   This will probably require wide-scale changes to support a TupleKind obligation
145             //   We can't resolve this without knowing the type of the param
146             if !matches!(fn_sig.inputs()[expected_args - 1].kind(), ty::Tuple(_) | ty::Param(_)) {
147                 err()
148             }
149         }
150     }
151
152     if body.generator_kind.is_some() && can_be_generator.is_some() {
153         let yield_ty = fcx
154             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
155         fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
156
157         // Resume type defaults to `()` if the generator has no argument.
158         let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
159
160         fcx.resume_yield_tys = Some((resume_ty, yield_ty));
161     }
162
163     GatherLocalsVisitor::new(&fcx).visit_body(body);
164
165     // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
166     // (as it's created inside the body itself, not passed in from outside).
167     let maybe_va_list = if fn_sig.c_variadic {
168         let span = body.params.last().unwrap().span;
169         let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
170         let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
171
172         Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
173     } else {
174         None
175     };
176
177     // Add formal parameters.
178     let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
179     let inputs_fn = fn_sig.inputs().iter().copied();
180     for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
181         // Check the pattern.
182         let ty_span = try { inputs_hir?.get(idx)?.span };
183         fcx.check_pat_top(&param.pat, param_ty, ty_span, false);
184
185         // Check that argument is Sized.
186         // The check for a non-trivial pattern is a hack to avoid duplicate warnings
187         // for simple cases like `fn foo(x: Trait)`,
188         // where we would error once on the parameter as a whole, and once on the binding `x`.
189         if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
190             fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
191         }
192
193         fcx.write_ty(param.hir_id, param_ty);
194     }
195
196     inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
197
198     fcx.in_tail_expr = true;
199     if let ty::Dynamic(..) = declared_ret_ty.kind() {
200         // FIXME: We need to verify that the return type is `Sized` after the return expression has
201         // been evaluated so that we have types available for all the nodes being returned, but that
202         // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
203         // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
204         // while keeping the current ordering we will ignore the tail expression's type because we
205         // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
206         // because we will trigger "unreachable expression" lints unconditionally.
207         // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
208         // case that a newcomer might make, returning a bare trait, and in that case we populate
209         // the tail expression's type so that the suggestion will be correct, but ignore all other
210         // possible cases.
211         fcx.check_expr(&body.value);
212         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
213     } else {
214         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
215         fcx.check_return_expr(&body.value, false);
216     }
217     fcx.in_tail_expr = false;
218
219     // We insert the deferred_generator_interiors entry after visiting the body.
220     // This ensures that all nested generators appear before the entry of this generator.
221     // resolve_generator_interiors relies on this property.
222     let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
223         let interior = fcx
224             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
225         fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
226
227         let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
228         Some(GeneratorTypes {
229             resume_ty,
230             yield_ty,
231             interior,
232             movability: can_be_generator.unwrap(),
233         })
234     } else {
235         None
236     };
237
238     // Finalize the return check by taking the LUB of the return types
239     // we saw and assigning it to the expected return type. This isn't
240     // really expected to fail, since the coercions would have failed
241     // earlier when trying to find a LUB.
242     let coercion = fcx.ret_coercion.take().unwrap().into_inner();
243     let mut actual_return_ty = coercion.complete(&fcx);
244     debug!("actual_return_ty = {:?}", actual_return_ty);
245     if let ty::Dynamic(..) = declared_ret_ty.kind() {
246         // We have special-cased the case where the function is declared
247         // `-> dyn Foo` and we don't actually relate it to the
248         // `fcx.ret_coercion`, so just substitute a type variable.
249         actual_return_ty =
250             fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
251         debug!("actual_return_ty replaced with {:?}", actual_return_ty);
252     }
253
254     // HACK(oli-obk, compiler-errors): We should be comparing this against
255     // `declared_ret_ty`, but then anything uninferred would be inferred to
256     // the opaque type itself. That again would cause writeback to assume
257     // we have a recursive call site and do the sadly stabilized fallback to `()`.
258     fcx.demand_suptype(span, ret_ty, actual_return_ty);
259
260     // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
261     if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
262         && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
263     {
264         check_panic_info_fn(tcx, panic_impl_did.expect_local(), fn_sig, decl, declared_ret_ty);
265     }
266
267     // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !`
268     if let Some(alloc_error_handler_did) = tcx.lang_items().oom()
269         && alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id()
270     {
271         check_alloc_error_fn(tcx, alloc_error_handler_did.expect_local(), fn_sig, decl, declared_ret_ty);
272     }
273
274     (fcx, gen_ty)
275 }
276
277 fn check_panic_info_fn(
278     tcx: TyCtxt<'_>,
279     fn_id: LocalDefId,
280     fn_sig: ty::FnSig<'_>,
281     decl: &hir::FnDecl<'_>,
282     declared_ret_ty: Ty<'_>,
283 ) {
284     let Some(panic_info_did) = tcx.lang_items().panic_info() else {
285         tcx.sess.err("language item required, but not found: `panic_info`");
286         return;
287     };
288
289     if *declared_ret_ty.kind() != ty::Never {
290         tcx.sess.span_err(decl.output.span(), "return type should be `!`");
291     }
292
293     let inputs = fn_sig.inputs();
294     if inputs.len() != 1 {
295         tcx.sess.span_err(tcx.def_span(fn_id), "function should have one argument");
296         return;
297     }
298
299     let arg_is_panic_info = match *inputs[0].kind() {
300         ty::Ref(region, ty, mutbl) => match *ty.kind() {
301             ty::Adt(ref adt, _) => {
302                 adt.did() == panic_info_did && mutbl == hir::Mutability::Not && !region.is_static()
303             }
304             _ => false,
305         },
306         _ => false,
307     };
308
309     if !arg_is_panic_info {
310         tcx.sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
311     }
312
313     let DefKind::Fn = tcx.def_kind(fn_id) else {
314         let span = tcx.def_span(fn_id);
315         tcx.sess.span_err(span, "should be a function");
316         return;
317     };
318
319     let generic_counts = tcx.generics_of(fn_id).own_counts();
320     if generic_counts.types != 0 {
321         let span = tcx.def_span(fn_id);
322         tcx.sess.span_err(span, "should have no type parameters");
323     }
324     if generic_counts.consts != 0 {
325         let span = tcx.def_span(fn_id);
326         tcx.sess.span_err(span, "should have no const parameters");
327     }
328 }
329
330 fn check_alloc_error_fn(
331     tcx: TyCtxt<'_>,
332     fn_id: LocalDefId,
333     fn_sig: ty::FnSig<'_>,
334     decl: &hir::FnDecl<'_>,
335     declared_ret_ty: Ty<'_>,
336 ) {
337     let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() else {
338         tcx.sess.err("language item required, but not found: `alloc_layout`");
339         return;
340     };
341
342     if *declared_ret_ty.kind() != ty::Never {
343         tcx.sess.span_err(decl.output.span(), "return type should be `!`");
344     }
345
346     let inputs = fn_sig.inputs();
347     if inputs.len() != 1 {
348         tcx.sess.span_err(tcx.def_span(fn_id), "function should have one argument");
349         return;
350     }
351
352     let arg_is_alloc_layout = match inputs[0].kind() {
353         ty::Adt(ref adt, _) => adt.did() == alloc_layout_did,
354         _ => false,
355     };
356
357     if !arg_is_alloc_layout {
358         tcx.sess.span_err(decl.inputs[0].span, "argument should be `Layout`");
359     }
360
361     let DefKind::Fn = tcx.def_kind(fn_id) else {
362         let span = tcx.def_span(fn_id);
363         tcx.sess.span_err(span, "`#[alloc_error_handler]` should be a function");
364         return;
365     };
366
367     let generic_counts = tcx.generics_of(fn_id).own_counts();
368     if generic_counts.types != 0 {
369         let span = tcx.def_span(fn_id);
370         tcx.sess.span_err(span, "`#[alloc_error_handler]` function should have no type parameters");
371     }
372     if generic_counts.consts != 0 {
373         let span = tcx.def_span(fn_id);
374         tcx.sess
375             .span_err(span, "`#[alloc_error_handler]` function should have no const parameters");
376     }
377 }
378
379 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
380     let def = tcx.adt_def(def_id);
381     let span = tcx.def_span(def_id);
382     def.destructor(tcx); // force the destructor to be evaluated
383
384     if def.repr().simd() {
385         check_simd(tcx, span, def_id);
386     }
387
388     check_transparent(tcx, span, def);
389     check_packed(tcx, span, def);
390 }
391
392 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
393     let def = tcx.adt_def(def_id);
394     let span = tcx.def_span(def_id);
395     def.destructor(tcx); // force the destructor to be evaluated
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             "static of uninhabited type",
515             |lint| {
516                 lint
517                 .note("uninhabited statics cannot be initialized, and any access would be an immediate error")
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 fn check_opaque<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
526     let item = tcx.hir().item(id);
527     let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
528         tcx.sess.delay_span_bug(tcx.hir().span(id.hir_id()), "expected opaque item");
529         return;
530     };
531
532     // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
533     // `async-std` (and `pub async fn` in general).
534     // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
535     // See https://github.com/rust-lang/rust/issues/75100
536     if tcx.sess.opts.actually_rustdoc {
537         return;
538     }
539
540     let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id());
541     let span = tcx.def_span(item.def_id.def_id);
542
543     check_opaque_for_inheriting_lifetimes(tcx, item.def_id.def_id, span);
544     if tcx.type_of(item.def_id.def_id).references_error() {
545         return;
546     }
547     if check_opaque_for_cycles(tcx, item.def_id.def_id, substs, span, &origin).is_err() {
548         return;
549     }
550     check_opaque_meets_bounds(tcx, item.def_id.def_id, substs, span, &origin);
551 }
552 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
553 /// in "inheriting lifetimes".
554 #[instrument(level = "debug", skip(tcx, span))]
555 pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
556     tcx: TyCtxt<'tcx>,
557     def_id: LocalDefId,
558     span: Span,
559 ) {
560     let item = tcx.hir().expect_item(def_id);
561     debug!(?item, ?span);
562
563     struct FoundParentLifetime;
564     struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics);
565     impl<'tcx> ty::visit::TypeVisitor<'tcx> for FindParentLifetimeVisitor<'tcx> {
566         type BreakTy = FoundParentLifetime;
567
568         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
569             debug!("FindParentLifetimeVisitor: r={:?}", r);
570             if let ty::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = *r {
571                 if index < self.0.parent_count as u32 {
572                     return ControlFlow::Break(FoundParentLifetime);
573                 } else {
574                     return ControlFlow::CONTINUE;
575                 }
576             }
577
578             r.super_visit_with(self)
579         }
580
581         fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
582             if let ty::ConstKind::Unevaluated(..) = c.kind() {
583                 // FIXME(#72219) We currently don't detect lifetimes within substs
584                 // which would violate this check. Even though the particular substitution is not used
585                 // within the const, this should still be fixed.
586                 return ControlFlow::CONTINUE;
587             }
588             c.super_visit_with(self)
589         }
590     }
591
592     struct ProhibitOpaqueVisitor<'tcx> {
593         tcx: TyCtxt<'tcx>,
594         opaque_identity_ty: Ty<'tcx>,
595         generics: &'tcx ty::Generics,
596         selftys: Vec<(Span, Option<String>)>,
597     }
598
599     impl<'tcx> ty::visit::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
600         type BreakTy = Ty<'tcx>;
601
602         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
603             debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
604             if t == self.opaque_identity_ty {
605                 ControlFlow::CONTINUE
606             } else {
607                 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
608                     .map_break(|FoundParentLifetime| t)
609             }
610         }
611     }
612
613     impl<'tcx> Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
614         type NestedFilter = nested_filter::OnlyBodies;
615
616         fn nested_visit_map(&mut self) -> Self::Map {
617             self.tcx.hir()
618         }
619
620         fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
621             match arg.kind {
622                 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
623                     [PathSegment { res: Res::SelfTyParam { .. }, .. }] => {
624                         let impl_ty_name = None;
625                         self.selftys.push((path.span, impl_ty_name));
626                     }
627                     [PathSegment { res: Res::SelfTyAlias { alias_to: def_id, .. }, .. }] => {
628                         let impl_ty_name = Some(self.tcx.def_path_str(*def_id));
629                         self.selftys.push((path.span, impl_ty_name));
630                     }
631                     _ => {}
632                 },
633                 _ => {}
634             }
635             hir::intravisit::walk_ty(self, arg);
636         }
637     }
638
639     if let ItemKind::OpaqueTy(hir::OpaqueTy {
640         origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
641         ..
642     }) = item.kind
643     {
644         let mut visitor = ProhibitOpaqueVisitor {
645             opaque_identity_ty: tcx.mk_opaque(
646                 def_id.to_def_id(),
647                 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
648             ),
649             generics: tcx.generics_of(def_id),
650             tcx,
651             selftys: vec![],
652         };
653         let prohibit_opaque = tcx
654             .explicit_item_bounds(def_id)
655             .iter()
656             .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
657         debug!(
658             "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
659             prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
660         );
661
662         if let Some(ty) = prohibit_opaque.break_value() {
663             visitor.visit_item(&item);
664             let is_async = match item.kind {
665                 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
666                     matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
667                 }
668                 _ => unreachable!(),
669             };
670
671             let mut err = struct_span_err!(
672                 tcx.sess,
673                 span,
674                 E0760,
675                 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
676                  a parent scope",
677                 if is_async { "async fn" } else { "impl Trait" },
678             );
679
680             for (span, name) in visitor.selftys {
681                 err.span_suggestion(
682                     span,
683                     "consider spelling out the type instead",
684                     name.unwrap_or_else(|| format!("{:?}", ty)),
685                     Applicability::MaybeIncorrect,
686                 );
687             }
688             err.emit();
689         }
690     }
691 }
692
693 /// Checks that an opaque type does not contain cycles.
694 pub(super) fn check_opaque_for_cycles<'tcx>(
695     tcx: TyCtxt<'tcx>,
696     def_id: LocalDefId,
697     substs: SubstsRef<'tcx>,
698     span: Span,
699     origin: &hir::OpaqueTyOrigin,
700 ) -> Result<(), ErrorGuaranteed> {
701     if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() {
702         let reported = match origin {
703             hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span),
704             _ => opaque_type_cycle_error(tcx, def_id, span),
705         };
706         Err(reported)
707     } else {
708         Ok(())
709     }
710 }
711
712 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
713 ///
714 /// This is mostly checked at the places that specify the opaque type, but we
715 /// check those cases in the `param_env` of that function, which may have
716 /// bounds not on this opaque type:
717 ///
718 /// ```ignore (illustrative)
719 /// type X<T> = impl Clone;
720 /// fn f<T: Clone>(t: T) -> X<T> {
721 ///     t
722 /// }
723 /// ```
724 ///
725 /// Without this check the above code is incorrectly accepted: we would ICE if
726 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
727 #[instrument(level = "debug", skip(tcx))]
728 fn check_opaque_meets_bounds<'tcx>(
729     tcx: TyCtxt<'tcx>,
730     def_id: LocalDefId,
731     substs: SubstsRef<'tcx>,
732     span: Span,
733     origin: &hir::OpaqueTyOrigin,
734 ) {
735     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
736     let defining_use_anchor = match *origin {
737         hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
738         hir::OpaqueTyOrigin::TyAlias => def_id,
739     };
740     let param_env = tcx.param_env(defining_use_anchor);
741
742     let infcx = tcx
743         .infer_ctxt()
744         .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
745         .build();
746     let ocx = ObligationCtxt::new(&infcx);
747     let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
748
749     // `ReErased` regions appear in the "parent_substs" of closures/generators.
750     // We're ignoring them here and replacing them with fresh region variables.
751     // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs.
752     //
753     // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
754     // here rather than using ReErased.
755     let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
756     let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() {
757         ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)),
758         _ => re,
759     });
760
761     let misc_cause = traits::ObligationCause::misc(span, hir_id);
762
763     match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_ty) {
764         Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok),
765         Err(ty_err) => {
766             tcx.sess.delay_span_bug(
767                 span,
768                 &format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
769             );
770         }
771     }
772
773     // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
774     // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
775     // hidden type is well formed even without those bounds.
776     let predicate =
777         ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_ty.into())).to_predicate(tcx);
778     ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate));
779
780     // Check that all obligations are satisfied by the implementation's
781     // version.
782     let errors = ocx.select_all_or_error();
783     if !errors.is_empty() {
784         infcx.err_ctxt().report_fulfillment_errors(&errors, None, false);
785     }
786     match origin {
787         // Checked when type checking the function containing them.
788         hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
789         // Can have different predicates to their defining use
790         hir::OpaqueTyOrigin::TyAlias => {
791             let outlives_environment = OutlivesEnvironment::new(param_env);
792             infcx.check_region_obligations_and_report_errors(
793                 defining_use_anchor,
794                 &outlives_environment,
795             );
796         }
797     }
798     // Clean up after ourselves
799     let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
800 }
801
802 fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
803     debug!(
804         "check_item_type(it.def_id={:?}, it.name={})",
805         id.def_id,
806         tcx.def_path_str(id.def_id.to_def_id())
807     );
808     let _indenter = indenter();
809     match tcx.def_kind(id.def_id) {
810         DefKind::Static(..) => {
811             tcx.ensure().typeck(id.def_id.def_id);
812             maybe_check_static_with_link_section(tcx, id.def_id.def_id);
813             check_static_inhabited(tcx, id.def_id.def_id);
814         }
815         DefKind::Const => {
816             tcx.ensure().typeck(id.def_id.def_id);
817         }
818         DefKind::Enum => {
819             let item = tcx.hir().item(id);
820             let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else {
821                 return;
822             };
823             check_enum(tcx, &enum_definition.variants, item.def_id.def_id);
824         }
825         DefKind::Fn => {} // entirely within check_item_body
826         DefKind::Impl => {
827             let it = tcx.hir().item(id);
828             let hir::ItemKind::Impl(ref impl_) = it.kind else {
829                 return;
830             };
831             debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id);
832             if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) {
833                 check_impl_items_against_trait(
834                     tcx,
835                     it.span,
836                     it.def_id.def_id,
837                     impl_trait_ref,
838                     &impl_.items,
839                 );
840                 check_on_unimplemented(tcx, it);
841             }
842         }
843         DefKind::Trait => {
844             let it = tcx.hir().item(id);
845             let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
846                 return;
847             };
848             check_on_unimplemented(tcx, it);
849
850             for item in items.iter() {
851                 let item = tcx.hir().trait_item(item.id);
852                 match item.kind {
853                     hir::TraitItemKind::Fn(ref sig, _) => {
854                         let abi = sig.header.abi;
855                         fn_maybe_err(tcx, item.ident.span, abi);
856                     }
857                     hir::TraitItemKind::Type(.., Some(default)) => {
858                         let assoc_item = tcx.associated_item(item.def_id);
859                         let trait_substs =
860                             InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
861                         let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
862                             tcx,
863                             assoc_item,
864                             assoc_item,
865                             default.span,
866                             ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
867                         );
868                     }
869                     _ => {}
870                 }
871             }
872         }
873         DefKind::Struct => {
874             check_struct(tcx, id.def_id.def_id);
875         }
876         DefKind::Union => {
877             check_union(tcx, id.def_id.def_id);
878         }
879         DefKind::OpaqueTy => {
880             check_opaque(tcx, id);
881         }
882         DefKind::ImplTraitPlaceholder => {
883             let parent = tcx.impl_trait_in_trait_parent(id.def_id.to_def_id());
884             // Only check the validity of this opaque type if the function has a default body
885             if let hir::Node::TraitItem(hir::TraitItem {
886                 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
887                 ..
888             }) = tcx.hir().get_by_def_id(parent.expect_local())
889             {
890                 check_opaque(tcx, id);
891             }
892         }
893         DefKind::TyAlias => {
894             let pty_ty = tcx.type_of(id.def_id);
895             let generics = tcx.generics_of(id.def_id);
896             check_type_params_are_used(tcx, &generics, pty_ty);
897         }
898         DefKind::ForeignMod => {
899             let it = tcx.hir().item(id);
900             let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
901                 return;
902             };
903             check_abi(tcx, it.hir_id(), it.span, abi);
904
905             if abi == Abi::RustIntrinsic {
906                 for item in items {
907                     let item = tcx.hir().foreign_item(item.id);
908                     intrinsic::check_intrinsic_type(tcx, item);
909                 }
910             } else if abi == Abi::PlatformIntrinsic {
911                 for item in items {
912                     let item = tcx.hir().foreign_item(item.id);
913                     intrinsic::check_platform_intrinsic_type(tcx, item);
914                 }
915             } else {
916                 for item in items {
917                     let def_id = item.id.def_id.def_id;
918                     let generics = tcx.generics_of(def_id);
919                     let own_counts = generics.own_counts();
920                     if generics.params.len() - own_counts.lifetimes != 0 {
921                         let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
922                             (_, 0) => ("type", "types", Some("u32")),
923                             // We don't specify an example value, because we can't generate
924                             // a valid value for any type.
925                             (0, _) => ("const", "consts", None),
926                             _ => ("type or const", "types or consts", None),
927                         };
928                         struct_span_err!(
929                             tcx.sess,
930                             item.span,
931                             E0044,
932                             "foreign items may not have {kinds} parameters",
933                         )
934                         .span_label(item.span, &format!("can't have {kinds} parameters"))
935                         .help(
936                             // FIXME: once we start storing spans for type arguments, turn this
937                             // into a suggestion.
938                             &format!(
939                                 "replace the {} parameters with concrete {}{}",
940                                 kinds,
941                                 kinds_pl,
942                                 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
943                             ),
944                         )
945                         .emit();
946                     }
947
948                     let item = tcx.hir().foreign_item(item.id);
949                     match item.kind {
950                         hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
951                             require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
952                         }
953                         hir::ForeignItemKind::Static(..) => {
954                             check_static_inhabited(tcx, def_id);
955                         }
956                         _ => {}
957                     }
958                 }
959             }
960         }
961         DefKind::GlobalAsm => {
962             let it = tcx.hir().item(id);
963             let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
964             InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
965         }
966         _ => {}
967     }
968 }
969
970 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
971     // an error would be reported if this fails.
972     let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
973 }
974
975 pub(super) fn check_specialization_validity<'tcx>(
976     tcx: TyCtxt<'tcx>,
977     trait_def: &ty::TraitDef,
978     trait_item: &ty::AssocItem,
979     impl_id: DefId,
980     impl_item: &hir::ImplItemRef,
981 ) {
982     let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
983     let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
984         if parent.is_from_trait() {
985             None
986         } else {
987             Some((parent, parent.item(tcx, trait_item.def_id)))
988         }
989     });
990
991     let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
992         match parent_item {
993             // Parent impl exists, and contains the parent item we're trying to specialize, but
994             // doesn't mark it `default`.
995             Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
996                 Some(Err(parent_impl.def_id()))
997             }
998
999             // Parent impl contains item and makes it specializable.
1000             Some(_) => Some(Ok(())),
1001
1002             // Parent impl doesn't mention the item. This means it's inherited from the
1003             // grandparent. In that case, if parent is a `default impl`, inherited items use the
1004             // "defaultness" from the grandparent, else they are final.
1005             None => {
1006                 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
1007                     None
1008                 } else {
1009                     Some(Err(parent_impl.def_id()))
1010                 }
1011             }
1012         }
1013     });
1014
1015     // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1016     // item. This is allowed, the item isn't actually getting specialized here.
1017     let result = opt_result.unwrap_or(Ok(()));
1018
1019     if let Err(parent_impl) = result {
1020         report_forbidden_specialization(tcx, impl_item, parent_impl);
1021     }
1022 }
1023
1024 fn check_impl_items_against_trait<'tcx>(
1025     tcx: TyCtxt<'tcx>,
1026     full_impl_span: Span,
1027     impl_id: LocalDefId,
1028     impl_trait_ref: ty::TraitRef<'tcx>,
1029     impl_item_refs: &[hir::ImplItemRef],
1030 ) {
1031     // If the trait reference itself is erroneous (so the compilation is going
1032     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1033     // isn't populated for such impls.
1034     if impl_trait_ref.references_error() {
1035         return;
1036     }
1037
1038     // Negative impls are not expected to have any items
1039     match tcx.impl_polarity(impl_id) {
1040         ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1041         ty::ImplPolarity::Negative => {
1042             if let [first_item_ref, ..] = impl_item_refs {
1043                 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
1044                 struct_span_err!(
1045                     tcx.sess,
1046                     first_item_span,
1047                     E0749,
1048                     "negative impls cannot have any items"
1049                 )
1050                 .emit();
1051             }
1052             return;
1053         }
1054     }
1055
1056     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1057
1058     for impl_item in impl_item_refs {
1059         let ty_impl_item = tcx.associated_item(impl_item.id.def_id);
1060         let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
1061             tcx.associated_item(trait_item_id)
1062         } else {
1063             // Checked in `associated_item`.
1064             tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
1065             continue;
1066         };
1067         let impl_item_full = tcx.hir().impl_item(impl_item.id);
1068         match impl_item_full.kind {
1069             hir::ImplItemKind::Const(..) => {
1070                 let _ = tcx.compare_assoc_const_impl_item_with_trait_item((
1071                     impl_item.id.def_id.def_id,
1072                     ty_impl_item.trait_item_def_id.unwrap(),
1073                 ));
1074             }
1075             hir::ImplItemKind::Fn(..) => {
1076                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1077                 compare_impl_method(
1078                     tcx,
1079                     &ty_impl_item,
1080                     &ty_trait_item,
1081                     impl_trait_ref,
1082                     opt_trait_span,
1083                 );
1084             }
1085             hir::ImplItemKind::Type(impl_ty) => {
1086                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1087                 compare_ty_impl(
1088                     tcx,
1089                     &ty_impl_item,
1090                     impl_ty.span,
1091                     &ty_trait_item,
1092                     impl_trait_ref,
1093                     opt_trait_span,
1094                 );
1095             }
1096         }
1097
1098         check_specialization_validity(
1099             tcx,
1100             trait_def,
1101             &ty_trait_item,
1102             impl_id.to_def_id(),
1103             impl_item,
1104         );
1105     }
1106
1107     if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1108         // Check for missing items from trait
1109         let mut missing_items = Vec::new();
1110
1111         let mut must_implement_one_of: Option<&[Ident]> =
1112             trait_def.must_implement_one_of.as_deref();
1113
1114         for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
1115             let is_implemented = ancestors
1116                 .leaf_def(tcx, trait_item_id)
1117                 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
1118
1119             if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1120                 missing_items.push(tcx.associated_item(trait_item_id));
1121             }
1122
1123             // true if this item is specifically implemented in this impl
1124             let is_implemented_here = ancestors
1125                 .leaf_def(tcx, trait_item_id)
1126                 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1127
1128             if !is_implemented_here {
1129                 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1130                     EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1131                         tcx,
1132                         full_impl_span,
1133                         trait_item_id,
1134                         feature,
1135                         reason,
1136                         issue,
1137                     ),
1138
1139                     // Unmarked default bodies are considered stable (at least for now).
1140                     EvalResult::Allow | EvalResult::Unmarked => {}
1141                 }
1142             }
1143
1144             if let Some(required_items) = &must_implement_one_of {
1145                 if is_implemented_here {
1146                     let trait_item = tcx.associated_item(trait_item_id);
1147                     if required_items.contains(&trait_item.ident(tcx)) {
1148                         must_implement_one_of = None;
1149                     }
1150                 }
1151             }
1152         }
1153
1154         if !missing_items.is_empty() {
1155             missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
1156         }
1157
1158         if let Some(missing_items) = must_implement_one_of {
1159             let attr_span = tcx
1160                 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
1161                 .map(|attr| attr.span);
1162
1163             missing_items_must_implement_one_of_err(
1164                 tcx,
1165                 tcx.def_span(impl_id),
1166                 missing_items,
1167                 attr_span,
1168             );
1169         }
1170     }
1171 }
1172
1173 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1174     let t = tcx.type_of(def_id);
1175     if let ty::Adt(def, substs) = t.kind()
1176         && def.is_struct()
1177     {
1178         let fields = &def.non_enum_variant().fields;
1179         if fields.is_empty() {
1180             struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1181             return;
1182         }
1183         let e = fields[0].ty(tcx, substs);
1184         if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1185             struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1186                 .span_label(sp, "SIMD elements must have the same type")
1187                 .emit();
1188             return;
1189         }
1190
1191         let len = if let ty::Array(_ty, c) = e.kind() {
1192             c.try_eval_usize(tcx, tcx.param_env(def.did()))
1193         } else {
1194             Some(fields.len() as u64)
1195         };
1196         if let Some(len) = len {
1197             if len == 0 {
1198                 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1199                 return;
1200             } else if len > MAX_SIMD_LANES {
1201                 struct_span_err!(
1202                     tcx.sess,
1203                     sp,
1204                     E0075,
1205                     "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1206                 )
1207                 .emit();
1208                 return;
1209             }
1210         }
1211
1212         // Check that we use types valid for use in the lanes of a SIMD "vector register"
1213         // These are scalar types which directly match a "machine" type
1214         // Yes: Integers, floats, "thin" pointers
1215         // No: char, "fat" pointers, compound types
1216         match e.kind() {
1217             ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
1218             ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
1219             ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
1220             ty::Array(t, _clen)
1221                 if matches!(
1222                     t.kind(),
1223                     ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
1224                 ) =>
1225             { /* struct([f32; 4]) is ok */ }
1226             _ => {
1227                 struct_span_err!(
1228                     tcx.sess,
1229                     sp,
1230                     E0077,
1231                     "SIMD vector element type should be a \
1232                         primitive scalar (integer/float/pointer) type"
1233                 )
1234                 .emit();
1235                 return;
1236             }
1237         }
1238     }
1239 }
1240
1241 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1242     let repr = def.repr();
1243     if repr.packed() {
1244         for attr in tcx.get_attrs(def.did(), sym::repr) {
1245             for r in attr::parse_repr_attr(&tcx.sess, attr) {
1246                 if let attr::ReprPacked(pack) = r
1247                 && let Some(repr_pack) = repr.pack
1248                 && pack as u64 != repr_pack.bytes()
1249             {
1250                         struct_span_err!(
1251                             tcx.sess,
1252                             sp,
1253                             E0634,
1254                             "type has conflicting packed representation hints"
1255                         )
1256                         .emit();
1257             }
1258             }
1259         }
1260         if repr.align.is_some() {
1261             struct_span_err!(
1262                 tcx.sess,
1263                 sp,
1264                 E0587,
1265                 "type has conflicting packed and align representation hints"
1266             )
1267             .emit();
1268         } else {
1269             if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1270                 let mut err = struct_span_err!(
1271                     tcx.sess,
1272                     sp,
1273                     E0588,
1274                     "packed type cannot transitively contain a `#[repr(align)]` type"
1275                 );
1276
1277                 err.span_note(
1278                     tcx.def_span(def_spans[0].0),
1279                     &format!(
1280                         "`{}` has a `#[repr(align)]` attribute",
1281                         tcx.item_name(def_spans[0].0)
1282                     ),
1283                 );
1284
1285                 if def_spans.len() > 2 {
1286                     let mut first = true;
1287                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
1288                         let ident = tcx.item_name(*adt_def);
1289                         err.span_note(
1290                             *span,
1291                             &if first {
1292                                 format!(
1293                                     "`{}` contains a field of type `{}`",
1294                                     tcx.type_of(def.did()),
1295                                     ident
1296                                 )
1297                             } else {
1298                                 format!("...which contains a field of type `{ident}`")
1299                             },
1300                         );
1301                         first = false;
1302                     }
1303                 }
1304
1305                 err.emit();
1306             }
1307         }
1308     }
1309 }
1310
1311 pub(super) fn check_packed_inner(
1312     tcx: TyCtxt<'_>,
1313     def_id: DefId,
1314     stack: &mut Vec<DefId>,
1315 ) -> Option<Vec<(DefId, Span)>> {
1316     if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1317         if def.is_struct() || def.is_union() {
1318             if def.repr().align.is_some() {
1319                 return Some(vec![(def.did(), DUMMY_SP)]);
1320             }
1321
1322             stack.push(def_id);
1323             for field in &def.non_enum_variant().fields {
1324                 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1325                     && !stack.contains(&def.did())
1326                     && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1327                 {
1328                     defs.push((def.did(), field.ident(tcx).span));
1329                     return Some(defs);
1330                 }
1331             }
1332             stack.pop();
1333         }
1334     }
1335
1336     None
1337 }
1338
1339 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: ty::AdtDef<'tcx>) {
1340     if !adt.repr().transparent() {
1341         return;
1342     }
1343
1344     if adt.is_union() && !tcx.features().transparent_unions {
1345         feature_err(
1346             &tcx.sess.parse_sess,
1347             sym::transparent_unions,
1348             sp,
1349             "transparent unions are unstable",
1350         )
1351         .emit();
1352     }
1353
1354     if adt.variants().len() != 1 {
1355         bad_variant_count(tcx, adt, sp, adt.did());
1356         if adt.variants().is_empty() {
1357             // Don't bother checking the fields. No variants (and thus no fields) exist.
1358             return;
1359         }
1360     }
1361
1362     // For each field, figure out if it's known to be a ZST and align(1), with "known"
1363     // respecting #[non_exhaustive] attributes.
1364     let field_infos = adt.all_fields().map(|field| {
1365         let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1366         let param_env = tcx.param_env(field.did);
1367         let layout = tcx.layout_of(param_env.and(ty));
1368         // We are currently checking the type this field came from, so it must be local
1369         let span = tcx.hir().span_if_local(field.did).unwrap();
1370         let zst = layout.map_or(false, |layout| layout.is_zst());
1371         let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1372         if !zst {
1373             return (span, zst, align1, None);
1374         }
1375
1376         fn check_non_exhaustive<'tcx>(
1377             tcx: TyCtxt<'tcx>,
1378             t: Ty<'tcx>,
1379         ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1380             match t.kind() {
1381                 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1382                 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1383                 ty::Adt(def, subst) => {
1384                     if !def.did().is_local() {
1385                         let non_exhaustive = def.is_variant_list_non_exhaustive()
1386                             || def
1387                                 .variants()
1388                                 .iter()
1389                                 .any(ty::VariantDef::is_field_list_non_exhaustive);
1390                         let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1391                         if non_exhaustive || has_priv {
1392                             return ControlFlow::Break((
1393                                 def.descr(),
1394                                 def.did(),
1395                                 subst,
1396                                 non_exhaustive,
1397                             ));
1398                         }
1399                     }
1400                     def.all_fields()
1401                         .map(|field| field.ty(tcx, subst))
1402                         .try_for_each(|t| check_non_exhaustive(tcx, t))
1403                 }
1404                 _ => ControlFlow::Continue(()),
1405             }
1406         }
1407
1408         (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1409     });
1410
1411     let non_zst_fields = field_infos
1412         .clone()
1413         .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1414     let non_zst_count = non_zst_fields.clone().count();
1415     if non_zst_count >= 2 {
1416         bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1417     }
1418     let incompatible_zst_fields =
1419         field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1420     let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1421     for (span, zst, align1, non_exhaustive) in field_infos {
1422         if zst && !align1 {
1423             struct_span_err!(
1424                 tcx.sess,
1425                 span,
1426                 E0691,
1427                 "zero-sized field in transparent {} has alignment larger than 1",
1428                 adt.descr(),
1429             )
1430             .span_label(span, "has alignment larger than 1")
1431             .emit();
1432         }
1433         if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1434             tcx.struct_span_lint_hir(
1435                 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1436                 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1437                 span,
1438                 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1439                 |lint| {
1440                     let note = if non_exhaustive {
1441                         "is marked with `#[non_exhaustive]`"
1442                     } else {
1443                         "contains private fields"
1444                     };
1445                     let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1446                     lint
1447                         .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1448                             and makes it not a breaking change to become non-zero-sized in the future."))
1449                 },
1450             )
1451         }
1452     }
1453 }
1454
1455 #[allow(trivial_numeric_casts)]
1456 fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: LocalDefId) {
1457     let def = tcx.adt_def(def_id);
1458     let sp = tcx.def_span(def_id);
1459     def.destructor(tcx); // force the destructor to be evaluated
1460
1461     if vs.is_empty() {
1462         if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1463             struct_span_err!(
1464                 tcx.sess,
1465                 attr.span,
1466                 E0084,
1467                 "unsupported representation for zero-variant enum"
1468             )
1469             .span_label(sp, "zero-variant enum")
1470             .emit();
1471         }
1472     }
1473
1474     let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1475     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1476         if !tcx.features().repr128 {
1477             feature_err(
1478                 &tcx.sess.parse_sess,
1479                 sym::repr128,
1480                 sp,
1481                 "repr with 128-bit type is unstable",
1482             )
1483             .emit();
1484         }
1485     }
1486
1487     for v in vs {
1488         if let Some(ref e) = v.disr_expr {
1489             tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1490         }
1491     }
1492
1493     if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
1494         let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1495
1496         let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1497         let has_non_units = vs.iter().any(|var| !is_unit(var));
1498         let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1499         let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1500
1501         if disr_non_unit || (disr_units && has_non_units) {
1502             let mut err =
1503                 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1504             err.emit();
1505         }
1506     }
1507
1508     detect_discriminant_duplicate(tcx, def.discriminants(tcx).collect(), vs, sp);
1509
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 }