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