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