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