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