]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/check.rs
Add tests for #41731
[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::opaque_types::ConstrainOpaqueTypeRegionVisitor;
14 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
15 use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt};
16 use rustc_infer::traits::Obligation;
17 use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
18 use rustc_middle::hir::nested_filter;
19 use rustc_middle::middle::stability::EvalResult;
20 use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
21 use rustc_middle::ty::subst::GenericArgKind;
22 use rustc_middle::ty::util::{Discr, IntTypeExt};
23 use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable};
24 use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
25 use rustc_span::symbol::sym;
26 use rustc_span::{self, Span};
27 use rustc_target::spec::abi::Abi;
28 use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedDirective;
29 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
30 use rustc_trait_selection::traits::{self, ObligationCtxt};
31
32 use std::ops::ControlFlow;
33
34 pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
35     match tcx.sess.target.is_abi_supported(abi) {
36         Some(true) => (),
37         Some(false) => {
38             struct_span_err!(
39                 tcx.sess,
40                 span,
41                 E0570,
42                 "`{abi}` is not a supported ABI for the current target",
43             )
44             .emit();
45         }
46         None => {
47             tcx.struct_span_lint_hir(
48                 UNSUPPORTED_CALLING_CONVENTIONS,
49                 hir_id,
50                 span,
51                 "use of calling convention not supported on this target",
52                 |lint| lint,
53             );
54         }
55     }
56
57     // This ABI is only allowed on function pointers
58     if abi == Abi::CCmseNonSecureCall {
59         struct_span_err!(
60             tcx.sess,
61             span,
62             E0781,
63             "the `\"C-cmse-nonsecure-call\"` ABI is only allowed on function pointers"
64         )
65         .emit();
66     }
67 }
68
69 fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
70     let def = tcx.adt_def(def_id);
71     let span = tcx.def_span(def_id);
72     def.destructor(tcx); // force the destructor to be evaluated
73
74     if def.repr().simd() {
75         check_simd(tcx, span, def_id);
76     }
77
78     check_transparent(tcx, def);
79     check_packed(tcx, span, def);
80 }
81
82 fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
83     let def = tcx.adt_def(def_id);
84     let span = tcx.def_span(def_id);
85     def.destructor(tcx); // force the destructor to be evaluated
86     check_transparent(tcx, def);
87     check_union_fields(tcx, span, def_id);
88     check_packed(tcx, span, def);
89 }
90
91 /// Check that the fields of the `union` do not need dropping.
92 fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
93     let item_type = tcx.type_of(item_def_id);
94     if let ty::Adt(def, substs) = item_type.kind() {
95         assert!(def.is_union());
96
97         fn allowed_union_field<'tcx>(
98             ty: Ty<'tcx>,
99             tcx: TyCtxt<'tcx>,
100             param_env: ty::ParamEnv<'tcx>,
101             span: Span,
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, span))
109                 }
110                 ty::Array(elem, _len) => {
111                     // Like `Copy`, we do *not* special-case length 0.
112                     allowed_union_field(*elem, tcx, param_env, span)
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 = field.ty(tcx, substs);
125
126             if !allowed_union_field(field_ty, tcx, param_env, span) {
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>(tcx: TyCtxt<'tcx>, 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>(tcx: TyCtxt<'tcx>, 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<'tcx>(
249     tcx: TyCtxt<'tcx>,
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 hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
416     let defining_use_anchor = match *origin {
417         hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,
418         hir::OpaqueTyOrigin::TyAlias => def_id,
419     };
420     let param_env = tcx.param_env(defining_use_anchor);
421
422     let infcx = tcx
423         .infer_ctxt()
424         .with_opaque_type_inference(DefiningAnchor::Bind(defining_use_anchor))
425         .build();
426     let ocx = ObligationCtxt::new(&infcx);
427     let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
428
429     // `ReErased` regions appear in the "parent_substs" of closures/generators.
430     // We're ignoring them here and replacing them with fresh region variables.
431     // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs.
432     //
433     // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
434     // here rather than using ReErased.
435     let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs);
436     let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() {
437         ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)),
438         _ => re,
439     });
440
441     let misc_cause = traits::ObligationCause::misc(span, hir_id);
442
443     match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
444         Ok(()) => {}
445         Err(ty_err) => {
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             infcx.check_region_obligations_and_report_errors(
472                 defining_use_anchor,
473                 &outlives_environment,
474             );
475         }
476     }
477     // Clean up after ourselves
478     let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
479 }
480
481 fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) {
482     debug!(
483         "check_item_type(it.def_id={:?}, it.name={})",
484         id.owner_id,
485         tcx.def_path_str(id.owner_id.to_def_id())
486     );
487     let _indenter = indenter();
488     match tcx.def_kind(id.owner_id) {
489         DefKind::Static(..) => {
490             tcx.ensure().typeck(id.owner_id.def_id);
491             maybe_check_static_with_link_section(tcx, id.owner_id.def_id);
492             check_static_inhabited(tcx, id.owner_id.def_id);
493         }
494         DefKind::Const => {
495             tcx.ensure().typeck(id.owner_id.def_id);
496         }
497         DefKind::Enum => {
498             check_enum(tcx, id.owner_id.def_id);
499         }
500         DefKind::Fn => {} // entirely within check_item_body
501         DefKind::Impl => {
502             let it = tcx.hir().item(id);
503             let hir::ItemKind::Impl(ref impl_) = it.kind else {
504                 return;
505             };
506             debug!("ItemKind::Impl {} with id {:?}", it.ident, it.owner_id);
507             if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.owner_id) {
508                 check_impl_items_against_trait(
509                     tcx,
510                     it.span,
511                     it.owner_id.def_id,
512                     impl_trait_ref,
513                     &impl_.items,
514                 );
515                 check_on_unimplemented(tcx, it);
516             }
517         }
518         DefKind::Trait => {
519             let it = tcx.hir().item(id);
520             let hir::ItemKind::Trait(_, _, _, _, ref items) = it.kind else {
521                 return;
522             };
523             check_on_unimplemented(tcx, it);
524
525             for item in items.iter() {
526                 let item = tcx.hir().trait_item(item.id);
527                 match item.kind {
528                     hir::TraitItemKind::Fn(ref sig, _) => {
529                         let abi = sig.header.abi;
530                         fn_maybe_err(tcx, item.ident.span, abi);
531                     }
532                     hir::TraitItemKind::Type(.., Some(default)) => {
533                         let assoc_item = tcx.associated_item(item.owner_id);
534                         let trait_substs =
535                             InternalSubsts::identity_for_item(tcx, it.owner_id.to_def_id());
536                         let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
537                             tcx,
538                             assoc_item,
539                             assoc_item,
540                             default.span,
541                             ty::TraitRef { def_id: it.owner_id.to_def_id(), substs: trait_substs },
542                         );
543                     }
544                     _ => {}
545                 }
546             }
547         }
548         DefKind::Struct => {
549             check_struct(tcx, id.owner_id.def_id);
550         }
551         DefKind::Union => {
552             check_union(tcx, id.owner_id.def_id);
553         }
554         DefKind::OpaqueTy => {
555             check_opaque(tcx, id);
556         }
557         DefKind::ImplTraitPlaceholder => {
558             let parent = tcx.impl_trait_in_trait_parent(id.owner_id.to_def_id());
559             // Only check the validity of this opaque type if the function has a default body
560             if let hir::Node::TraitItem(hir::TraitItem {
561                 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
562                 ..
563             }) = tcx.hir().get_by_def_id(parent.expect_local())
564             {
565                 check_opaque(tcx, id);
566             }
567         }
568         DefKind::TyAlias => {
569             let pty_ty = tcx.type_of(id.owner_id);
570             let generics = tcx.generics_of(id.owner_id);
571             check_type_params_are_used(tcx, &generics, pty_ty);
572         }
573         DefKind::ForeignMod => {
574             let it = tcx.hir().item(id);
575             let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
576                 return;
577             };
578             check_abi(tcx, it.hir_id(), it.span, abi);
579
580             if abi == Abi::RustIntrinsic {
581                 for item in items {
582                     let item = tcx.hir().foreign_item(item.id);
583                     intrinsic::check_intrinsic_type(tcx, item);
584                 }
585             } else if abi == Abi::PlatformIntrinsic {
586                 for item in items {
587                     let item = tcx.hir().foreign_item(item.id);
588                     intrinsic::check_platform_intrinsic_type(tcx, item);
589                 }
590             } else {
591                 for item in items {
592                     let def_id = item.id.owner_id.def_id;
593                     let generics = tcx.generics_of(def_id);
594                     let own_counts = generics.own_counts();
595                     if generics.params.len() - own_counts.lifetimes != 0 {
596                         let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
597                             (_, 0) => ("type", "types", Some("u32")),
598                             // We don't specify an example value, because we can't generate
599                             // a valid value for any type.
600                             (0, _) => ("const", "consts", None),
601                             _ => ("type or const", "types or consts", None),
602                         };
603                         struct_span_err!(
604                             tcx.sess,
605                             item.span,
606                             E0044,
607                             "foreign items may not have {kinds} parameters",
608                         )
609                         .span_label(item.span, &format!("can't have {kinds} parameters"))
610                         .help(
611                             // FIXME: once we start storing spans for type arguments, turn this
612                             // into a suggestion.
613                             &format!(
614                                 "replace the {} parameters with concrete {}{}",
615                                 kinds,
616                                 kinds_pl,
617                                 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
618                             ),
619                         )
620                         .emit();
621                     }
622
623                     let item = tcx.hir().foreign_item(item.id);
624                     match item.kind {
625                         hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
626                             require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
627                         }
628                         hir::ForeignItemKind::Static(..) => {
629                             check_static_inhabited(tcx, def_id);
630                         }
631                         _ => {}
632                     }
633                 }
634             }
635         }
636         DefKind::GlobalAsm => {
637             let it = tcx.hir().item(id);
638             let hir::ItemKind::GlobalAsm(asm) = it.kind else { span_bug!(it.span, "DefKind::GlobalAsm but got {:#?}", it) };
639             InlineAsmCtxt::new_global_asm(tcx).check_asm(asm, id.hir_id());
640         }
641         _ => {}
642     }
643 }
644
645 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
646     // an error would be reported if this fails.
647     let _ = OnUnimplementedDirective::of_item(tcx, item.owner_id.to_def_id());
648 }
649
650 pub(super) fn check_specialization_validity<'tcx>(
651     tcx: TyCtxt<'tcx>,
652     trait_def: &ty::TraitDef,
653     trait_item: &ty::AssocItem,
654     impl_id: DefId,
655     impl_item: &hir::ImplItemRef,
656 ) {
657     let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
658     let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
659         if parent.is_from_trait() {
660             None
661         } else {
662             Some((parent, parent.item(tcx, trait_item.def_id)))
663         }
664     });
665
666     let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
667         match parent_item {
668             // Parent impl exists, and contains the parent item we're trying to specialize, but
669             // doesn't mark it `default`.
670             Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
671                 Some(Err(parent_impl.def_id()))
672             }
673
674             // Parent impl contains item and makes it specializable.
675             Some(_) => Some(Ok(())),
676
677             // Parent impl doesn't mention the item. This means it's inherited from the
678             // grandparent. In that case, if parent is a `default impl`, inherited items use the
679             // "defaultness" from the grandparent, else they are final.
680             None => {
681                 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
682                     None
683                 } else {
684                     Some(Err(parent_impl.def_id()))
685                 }
686             }
687         }
688     });
689
690     // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
691     // item. This is allowed, the item isn't actually getting specialized here.
692     let result = opt_result.unwrap_or(Ok(()));
693
694     if let Err(parent_impl) = result {
695         report_forbidden_specialization(tcx, impl_item, parent_impl);
696     }
697 }
698
699 fn check_impl_items_against_trait<'tcx>(
700     tcx: TyCtxt<'tcx>,
701     full_impl_span: Span,
702     impl_id: LocalDefId,
703     impl_trait_ref: ty::TraitRef<'tcx>,
704     impl_item_refs: &[hir::ImplItemRef],
705 ) {
706     // If the trait reference itself is erroneous (so the compilation is going
707     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
708     // isn't populated for such impls.
709     if impl_trait_ref.references_error() {
710         return;
711     }
712
713     // Negative impls are not expected to have any items
714     match tcx.impl_polarity(impl_id) {
715         ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
716         ty::ImplPolarity::Negative => {
717             if let [first_item_ref, ..] = impl_item_refs {
718                 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
719                 struct_span_err!(
720                     tcx.sess,
721                     first_item_span,
722                     E0749,
723                     "negative impls cannot have any items"
724                 )
725                 .emit();
726             }
727             return;
728         }
729     }
730
731     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
732
733     for impl_item in impl_item_refs {
734         let ty_impl_item = tcx.associated_item(impl_item.id.owner_id);
735         let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
736             tcx.associated_item(trait_item_id)
737         } else {
738             // Checked in `associated_item`.
739             tcx.sess.delay_span_bug(impl_item.span, "missing associated item in trait");
740             continue;
741         };
742         let impl_item_full = tcx.hir().impl_item(impl_item.id);
743         match impl_item_full.kind {
744             hir::ImplItemKind::Const(..) => {
745                 let _ = tcx.compare_assoc_const_impl_item_with_trait_item((
746                     impl_item.id.owner_id.def_id,
747                     ty_impl_item.trait_item_def_id.unwrap(),
748                 ));
749             }
750             hir::ImplItemKind::Fn(..) => {
751                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
752                 compare_impl_method(
753                     tcx,
754                     &ty_impl_item,
755                     &ty_trait_item,
756                     impl_trait_ref,
757                     opt_trait_span,
758                 );
759             }
760             hir::ImplItemKind::Type(impl_ty) => {
761                 let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
762                 compare_ty_impl(
763                     tcx,
764                     &ty_impl_item,
765                     impl_ty.span,
766                     &ty_trait_item,
767                     impl_trait_ref,
768                     opt_trait_span,
769                 );
770             }
771         }
772
773         check_specialization_validity(
774             tcx,
775             trait_def,
776             &ty_trait_item,
777             impl_id.to_def_id(),
778             impl_item,
779         );
780     }
781
782     if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
783         // Check for missing items from trait
784         let mut missing_items = Vec::new();
785
786         let mut must_implement_one_of: Option<&[Ident]> =
787             trait_def.must_implement_one_of.as_deref();
788
789         for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
790             let is_implemented = ancestors
791                 .leaf_def(tcx, trait_item_id)
792                 .map_or(false, |node_item| node_item.item.defaultness(tcx).has_value());
793
794             if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
795                 missing_items.push(tcx.associated_item(trait_item_id));
796             }
797
798             // true if this item is specifically implemented in this impl
799             let is_implemented_here = ancestors
800                 .leaf_def(tcx, trait_item_id)
801                 .map_or(false, |node_item| !node_item.defining_node.is_from_trait());
802
803             if !is_implemented_here {
804                 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
805                     EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
806                         tcx,
807                         full_impl_span,
808                         trait_item_id,
809                         feature,
810                         reason,
811                         issue,
812                     ),
813
814                     // Unmarked default bodies are considered stable (at least for now).
815                     EvalResult::Allow | EvalResult::Unmarked => {}
816                 }
817             }
818
819             if let Some(required_items) = &must_implement_one_of {
820                 if is_implemented_here {
821                     let trait_item = tcx.associated_item(trait_item_id);
822                     if required_items.contains(&trait_item.ident(tcx)) {
823                         must_implement_one_of = None;
824                     }
825                 }
826             }
827         }
828
829         if !missing_items.is_empty() {
830             missing_items_err(tcx, tcx.def_span(impl_id), &missing_items, full_impl_span);
831         }
832
833         if let Some(missing_items) = must_implement_one_of {
834             let attr_span = tcx
835                 .get_attr(impl_trait_ref.def_id, sym::rustc_must_implement_one_of)
836                 .map(|attr| attr.span);
837
838             missing_items_must_implement_one_of_err(
839                 tcx,
840                 tcx.def_span(impl_id),
841                 missing_items,
842                 attr_span,
843             );
844         }
845     }
846 }
847
848 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
849     let t = tcx.type_of(def_id);
850     if let ty::Adt(def, substs) = t.kind()
851         && def.is_struct()
852     {
853         let fields = &def.non_enum_variant().fields;
854         if fields.is_empty() {
855             struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
856             return;
857         }
858         let e = fields[0].ty(tcx, substs);
859         if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
860             struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
861                 .span_label(sp, "SIMD elements must have the same type")
862                 .emit();
863             return;
864         }
865
866         let len = if let ty::Array(_ty, c) = e.kind() {
867             c.try_eval_usize(tcx, tcx.param_env(def.did()))
868         } else {
869             Some(fields.len() as u64)
870         };
871         if let Some(len) = len {
872             if len == 0 {
873                 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
874                 return;
875             } else if len > MAX_SIMD_LANES {
876                 struct_span_err!(
877                     tcx.sess,
878                     sp,
879                     E0075,
880                     "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
881                 )
882                 .emit();
883                 return;
884             }
885         }
886
887         // Check that we use types valid for use in the lanes of a SIMD "vector register"
888         // These are scalar types which directly match a "machine" type
889         // Yes: Integers, floats, "thin" pointers
890         // No: char, "fat" pointers, compound types
891         match e.kind() {
892             ty::Param(_) => (), // pass struct<T>(T, T, T, T) through, let monomorphization catch errors
893             ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_) => (), // struct(u8, u8, u8, u8) is ok
894             ty::Array(t, _) if matches!(t.kind(), ty::Param(_)) => (), // pass struct<T>([T; N]) through, let monomorphization catch errors
895             ty::Array(t, _clen)
896                 if matches!(
897                     t.kind(),
898                     ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_)
899                 ) =>
900             { /* struct([f32; 4]) is ok */ }
901             _ => {
902                 struct_span_err!(
903                     tcx.sess,
904                     sp,
905                     E0077,
906                     "SIMD vector element type should be a \
907                         primitive scalar (integer/float/pointer) type"
908                 )
909                 .emit();
910                 return;
911             }
912         }
913     }
914 }
915
916 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
917     let repr = def.repr();
918     if repr.packed() {
919         for attr in tcx.get_attrs(def.did(), sym::repr) {
920             for r in attr::parse_repr_attr(&tcx.sess, attr) {
921                 if let attr::ReprPacked(pack) = r
922                 && let Some(repr_pack) = repr.pack
923                 && pack as u64 != repr_pack.bytes()
924             {
925                         struct_span_err!(
926                             tcx.sess,
927                             sp,
928                             E0634,
929                             "type has conflicting packed representation hints"
930                         )
931                         .emit();
932             }
933             }
934         }
935         if repr.align.is_some() {
936             struct_span_err!(
937                 tcx.sess,
938                 sp,
939                 E0587,
940                 "type has conflicting packed and align representation hints"
941             )
942             .emit();
943         } else {
944             if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
945                 let mut err = struct_span_err!(
946                     tcx.sess,
947                     sp,
948                     E0588,
949                     "packed type cannot transitively contain a `#[repr(align)]` type"
950                 );
951
952                 err.span_note(
953                     tcx.def_span(def_spans[0].0),
954                     &format!(
955                         "`{}` has a `#[repr(align)]` attribute",
956                         tcx.item_name(def_spans[0].0)
957                     ),
958                 );
959
960                 if def_spans.len() > 2 {
961                     let mut first = true;
962                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
963                         let ident = tcx.item_name(*adt_def);
964                         err.span_note(
965                             *span,
966                             &if first {
967                                 format!(
968                                     "`{}` contains a field of type `{}`",
969                                     tcx.type_of(def.did()),
970                                     ident
971                                 )
972                             } else {
973                                 format!("...which contains a field of type `{ident}`")
974                             },
975                         );
976                         first = false;
977                     }
978                 }
979
980                 err.emit();
981             }
982         }
983     }
984 }
985
986 pub(super) fn check_packed_inner(
987     tcx: TyCtxt<'_>,
988     def_id: DefId,
989     stack: &mut Vec<DefId>,
990 ) -> Option<Vec<(DefId, Span)>> {
991     if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
992         if def.is_struct() || def.is_union() {
993             if def.repr().align.is_some() {
994                 return Some(vec![(def.did(), DUMMY_SP)]);
995             }
996
997             stack.push(def_id);
998             for field in &def.non_enum_variant().fields {
999                 if let ty::Adt(def, _) = field.ty(tcx, substs).kind()
1000                     && !stack.contains(&def.did())
1001                     && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1002                 {
1003                     defs.push((def.did(), field.ident(tcx).span));
1004                     return Some(defs);
1005                 }
1006             }
1007             stack.pop();
1008         }
1009     }
1010
1011     None
1012 }
1013
1014 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1015     if !adt.repr().transparent() {
1016         return;
1017     }
1018
1019     if adt.is_union() && !tcx.features().transparent_unions {
1020         feature_err(
1021             &tcx.sess.parse_sess,
1022             sym::transparent_unions,
1023             tcx.def_span(adt.did()),
1024             "transparent unions are unstable",
1025         )
1026         .emit();
1027     }
1028
1029     if adt.variants().len() != 1 {
1030         bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1031         if adt.variants().is_empty() {
1032             // Don't bother checking the fields. No variants (and thus no fields) exist.
1033             return;
1034         }
1035     }
1036
1037     // For each field, figure out if it's known to be a ZST and align(1), with "known"
1038     // respecting #[non_exhaustive] attributes.
1039     let field_infos = adt.all_fields().map(|field| {
1040         let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1041         let param_env = tcx.param_env(field.did);
1042         let layout = tcx.layout_of(param_env.and(ty));
1043         // We are currently checking the type this field came from, so it must be local
1044         let span = tcx.hir().span_if_local(field.did).unwrap();
1045         let zst = layout.map_or(false, |layout| layout.is_zst());
1046         let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1047         if !zst {
1048             return (span, zst, align1, None);
1049         }
1050
1051         fn check_non_exhaustive<'tcx>(
1052             tcx: TyCtxt<'tcx>,
1053             t: Ty<'tcx>,
1054         ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> {
1055             match t.kind() {
1056                 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1057                 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1058                 ty::Adt(def, subst) => {
1059                     if !def.did().is_local() {
1060                         let non_exhaustive = def.is_variant_list_non_exhaustive()
1061                             || def
1062                                 .variants()
1063                                 .iter()
1064                                 .any(ty::VariantDef::is_field_list_non_exhaustive);
1065                         let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1066                         if non_exhaustive || has_priv {
1067                             return ControlFlow::Break((
1068                                 def.descr(),
1069                                 def.did(),
1070                                 subst,
1071                                 non_exhaustive,
1072                             ));
1073                         }
1074                     }
1075                     def.all_fields()
1076                         .map(|field| field.ty(tcx, subst))
1077                         .try_for_each(|t| check_non_exhaustive(tcx, t))
1078                 }
1079                 _ => ControlFlow::Continue(()),
1080             }
1081         }
1082
1083         (span, zst, align1, check_non_exhaustive(tcx, ty).break_value())
1084     });
1085
1086     let non_zst_fields = field_infos
1087         .clone()
1088         .filter_map(|(span, zst, _align1, _non_exhaustive)| if !zst { Some(span) } else { None });
1089     let non_zst_count = non_zst_fields.clone().count();
1090     if non_zst_count >= 2 {
1091         bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, tcx.def_span(adt.did()));
1092     }
1093     let incompatible_zst_fields =
1094         field_infos.clone().filter(|(_, _, _, opt)| opt.is_some()).count();
1095     let incompat = incompatible_zst_fields + non_zst_count >= 2 && non_zst_count < 2;
1096     for (span, zst, align1, non_exhaustive) in field_infos {
1097         if zst && !align1 {
1098             struct_span_err!(
1099                 tcx.sess,
1100                 span,
1101                 E0691,
1102                 "zero-sized field in transparent {} has alignment larger than 1",
1103                 adt.descr(),
1104             )
1105             .span_label(span, "has alignment larger than 1")
1106             .emit();
1107         }
1108         if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive {
1109             tcx.struct_span_lint_hir(
1110                 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1111                 tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()),
1112                 span,
1113                 "zero-sized fields in `repr(transparent)` cannot contain external non-exhaustive types",
1114                 |lint| {
1115                     let note = if non_exhaustive {
1116                         "is marked with `#[non_exhaustive]`"
1117                     } else {
1118                         "contains private fields"
1119                     };
1120                     let field_ty = tcx.def_path_str_with_substs(def_id, substs);
1121                     lint
1122                         .note(format!("this {descr} contains `{field_ty}`, which {note}, \
1123                             and makes it not a breaking change to become non-zero-sized in the future."))
1124                 },
1125             )
1126         }
1127     }
1128 }
1129
1130 #[allow(trivial_numeric_casts)]
1131 fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1132     let def = tcx.adt_def(def_id);
1133     def.destructor(tcx); // force the destructor to be evaluated
1134
1135     if def.variants().is_empty() {
1136         if let Some(attr) = tcx.get_attrs(def_id.to_def_id(), sym::repr).next() {
1137             struct_span_err!(
1138                 tcx.sess,
1139                 attr.span,
1140                 E0084,
1141                 "unsupported representation for zero-variant enum"
1142             )
1143             .span_label(tcx.def_span(def_id), "zero-variant enum")
1144             .emit();
1145         }
1146     }
1147
1148     let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1149     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1150         if !tcx.features().repr128 {
1151             feature_err(
1152                 &tcx.sess.parse_sess,
1153                 sym::repr128,
1154                 tcx.def_span(def_id),
1155                 "repr with 128-bit type is unstable",
1156             )
1157             .emit();
1158         }
1159     }
1160
1161     for v in def.variants() {
1162         if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1163             tcx.ensure().typeck(discr_def_id.expect_local());
1164         }
1165     }
1166
1167     if def.repr().int.is_none() {
1168         let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1169         let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1170
1171         let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1172         let disr_units = def.variants().iter().any(|var| is_unit(&var) && has_disr(&var));
1173         let disr_non_unit = def.variants().iter().any(|var| !is_unit(&var) && has_disr(&var));
1174
1175         if disr_non_unit || (disr_units && has_non_units) {
1176             let mut err = struct_span_err!(
1177                 tcx.sess,
1178                 tcx.def_span(def_id),
1179                 E0732,
1180                 "`#[repr(inttype)]` must be specified"
1181             );
1182             err.emit();
1183         }
1184     }
1185
1186     detect_discriminant_duplicate(tcx, def);
1187     check_transparent(tcx, def);
1188 }
1189
1190 /// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1191 fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1192     // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1193     // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1194     let report = |dis: Discr<'tcx>, idx, err: &mut Diagnostic| {
1195         let var = adt.variant(idx); // HIR for the duplicate discriminant
1196         let (span, display_discr) = match var.discr {
1197             ty::VariantDiscr::Explicit(discr_def_id) => {
1198                 // In the case the discriminant is both a duplicate and overflowed, let the user know
1199                 if let hir::Node::AnonConst(expr) = tcx.hir().get_by_def_id(discr_def_id.expect_local())
1200                     && let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1201                     && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1202                     && *lit_value != dis.val
1203                 {
1204                     (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1205                 } else {
1206                     // Otherwise, format the value as-is
1207                     (tcx.def_span(discr_def_id), format!("`{dis}`"))
1208                 }
1209             }
1210             // This should not happen.
1211             ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1212             ty::VariantDiscr::Relative(distance_to_explicit) => {
1213                 // At this point we know this discriminant is a duplicate, and was not explicitly
1214                 // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1215                 // explicitly assigned discriminant, and letting the user know that this was the
1216                 // increment startpoint, and how many steps from there leading to the duplicate
1217                 if let Some(explicit_idx) =
1218                     idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1219                 {
1220                     let explicit_variant = adt.variant(explicit_idx);
1221                     let ve_ident = var.name;
1222                     let ex_ident = explicit_variant.name;
1223                     let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1224
1225                     err.span_label(
1226                         tcx.def_span(explicit_variant.def_id),
1227                         format!(
1228                             "discriminant for `{ve_ident}` incremented from this startpoint \
1229                             (`{ex_ident}` + {distance_to_explicit} {sp} later \
1230                              => `{ve_ident}` = {dis})"
1231                         ),
1232                     );
1233                 }
1234
1235                 (tcx.def_span(var.def_id), format!("`{dis}`"))
1236             }
1237         };
1238
1239         err.span_label(span, format!("{display_discr} assigned here"));
1240     };
1241
1242     let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1243
1244     // Here we loop through the discriminants, comparing each discriminant to another.
1245     // When a duplicate is detected, we instantiate an error and point to both
1246     // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1247     // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1248     // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1249     // style as we are mutating `discrs` on the fly).
1250     let mut i = 0;
1251     while i < discrs.len() {
1252         let var_i_idx = discrs[i].0;
1253         let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1254
1255         let mut o = i + 1;
1256         while o < discrs.len() {
1257             let var_o_idx = discrs[o].0;
1258
1259             if discrs[i].1.val == discrs[o].1.val {
1260                 let err = error.get_or_insert_with(|| {
1261                     let mut ret = struct_span_err!(
1262                         tcx.sess,
1263                         tcx.def_span(adt.did()),
1264                         E0081,
1265                         "discriminant value `{}` assigned more than once",
1266                         discrs[i].1,
1267                     );
1268
1269                     report(discrs[i].1, var_i_idx, &mut ret);
1270
1271                     ret
1272                 });
1273
1274                 report(discrs[o].1, var_o_idx, err);
1275
1276                 // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1277                 discrs[o] = *discrs.last().unwrap();
1278                 discrs.pop();
1279             } else {
1280                 o += 1;
1281             }
1282         }
1283
1284         if let Some(mut e) = error {
1285             e.emit();
1286         }
1287
1288         i += 1;
1289     }
1290 }
1291
1292 pub(super) fn check_type_params_are_used<'tcx>(
1293     tcx: TyCtxt<'tcx>,
1294     generics: &ty::Generics,
1295     ty: Ty<'tcx>,
1296 ) {
1297     debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1298
1299     assert_eq!(generics.parent, None);
1300
1301     if generics.own_counts().types == 0 {
1302         return;
1303     }
1304
1305     let mut params_used = BitSet::new_empty(generics.params.len());
1306
1307     if ty.references_error() {
1308         // If there is already another error, do not emit
1309         // an error for not using a type parameter.
1310         assert!(tcx.sess.has_errors().is_some());
1311         return;
1312     }
1313
1314     for leaf in ty.walk() {
1315         if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1316             && let ty::Param(param) = leaf_ty.kind()
1317         {
1318             debug!("found use of ty param {:?}", param);
1319             params_used.insert(param.index);
1320         }
1321     }
1322
1323     for param in &generics.params {
1324         if !params_used.contains(param.index)
1325             && let ty::GenericParamDefKind::Type { .. } = param.kind
1326         {
1327             let span = tcx.def_span(param.def_id);
1328             struct_span_err!(
1329                 tcx.sess,
1330                 span,
1331                 E0091,
1332                 "type parameter `{}` is unused",
1333                 param.name,
1334             )
1335             .span_label(span, "unused type parameter")
1336             .emit();
1337         }
1338     }
1339 }
1340
1341 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1342     let module = tcx.hir_module_items(module_def_id);
1343     for id in module.items() {
1344         check_item_type(tcx, id);
1345     }
1346 }
1347
1348 fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed {
1349     struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1350         .span_label(span, "recursive `async fn`")
1351         .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1352         .note(
1353             "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1354         )
1355         .emit()
1356 }
1357
1358 /// Emit an error for recursive opaque types.
1359 ///
1360 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1361 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1362 /// `impl Trait`.
1363 ///
1364 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1365 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1366 fn opaque_type_cycle_error(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> ErrorGuaranteed {
1367     let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1368
1369     let mut label = false;
1370     if let Some((def_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1371         let typeck_results = tcx.typeck(def_id);
1372         if visitor
1373             .returns
1374             .iter()
1375             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1376             .all(|ty| matches!(ty.kind(), ty::Never))
1377         {
1378             let spans = visitor
1379                 .returns
1380                 .iter()
1381                 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1382                 .map(|expr| expr.span)
1383                 .collect::<Vec<Span>>();
1384             let span_len = spans.len();
1385             if span_len == 1 {
1386                 err.span_label(spans[0], "this returned value is of `!` type");
1387             } else {
1388                 let mut multispan: MultiSpan = spans.clone().into();
1389                 for span in spans {
1390                     multispan.push_span_label(span, "this returned value is of `!` type");
1391                 }
1392                 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1393             }
1394             err.help("this error will resolve once the item's body returns a concrete type");
1395         } else {
1396             let mut seen = FxHashSet::default();
1397             seen.insert(span);
1398             err.span_label(span, "recursive opaque type");
1399             label = true;
1400             for (sp, ty) in visitor
1401                 .returns
1402                 .iter()
1403                 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1404                 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1405             {
1406                 struct OpaqueTypeCollector(Vec<DefId>);
1407                 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypeCollector {
1408                     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1409                         match *t.kind() {
1410                             ty::Opaque(def, _) => {
1411                                 self.0.push(def);
1412                                 ControlFlow::CONTINUE
1413                             }
1414                             _ => t.super_visit_with(self),
1415                         }
1416                     }
1417                 }
1418                 let mut visitor = OpaqueTypeCollector(vec![]);
1419                 ty.visit_with(&mut visitor);
1420                 for def_id in visitor.0 {
1421                     let ty_span = tcx.def_span(def_id);
1422                     if !seen.contains(&ty_span) {
1423                         err.span_label(ty_span, &format!("returning this opaque type `{ty}`"));
1424                         seen.insert(ty_span);
1425                     }
1426                     err.span_label(sp, &format!("returning here with type `{ty}`"));
1427                 }
1428             }
1429         }
1430     }
1431     if !label {
1432         err.span_label(span, "cannot resolve opaque type");
1433     }
1434     err.emit()
1435 }