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