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