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