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