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