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