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