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