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