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