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