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