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