]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/check.rs
spell the real selftype
[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::{def::Res, ItemKind, Node, PathSegment};
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     struct ProhibitOpaqueVisitor<'tcx> {
520         opaque_identity_ty: Ty<'tcx>,
521         generics: &'tcx ty::Generics,
522         tcx: TyCtxt<'tcx>,
523         selftys: Vec<(Span, Option<String>)>,
524     }
525
526     impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
527         type BreakTy = Ty<'tcx>;
528
529         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
530             debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t);
531             if t == self.opaque_identity_ty {
532                 ControlFlow::CONTINUE
533             } else {
534                 t.super_visit_with(&mut FindParentLifetimeVisitor(self.generics))
535                     .map_break(|FoundParentLifetime| t)
536             }
537         }
538     }
539
540     impl Visitor<'tcx> for ProhibitOpaqueVisitor<'tcx> {
541         type Map = rustc_middle::hir::map::Map<'tcx>;
542
543         fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
544             hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
545         }
546
547         fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
548             match arg.kind {
549                 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
550                     [PathSegment { res: Some(Res::SelfTy(_, impl_ref)), .. }] => {
551                         let impl_ty_name =
552                             impl_ref.map(|(def_id, _)| self.tcx.def_path_str(def_id));
553                         self.selftys.push((path.span, impl_ty_name));
554                     }
555                     _ => {}
556                 },
557                 _ => {}
558             }
559             hir::intravisit::walk_ty(self, arg);
560         }
561     }
562
563     if let ItemKind::OpaqueTy(hir::OpaqueTy {
564         origin: hir::OpaqueTyOrigin::AsyncFn | hir::OpaqueTyOrigin::FnReturn,
565         ..
566     }) = item.kind
567     {
568         let mut visitor = ProhibitOpaqueVisitor {
569             opaque_identity_ty: tcx.mk_opaque(
570                 def_id.to_def_id(),
571                 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
572             ),
573             generics: tcx.generics_of(def_id),
574             tcx,
575             selftys: vec![],
576         };
577         let prohibit_opaque = tcx
578             .explicit_item_bounds(def_id)
579             .iter()
580             .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor));
581         debug!(
582             "check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}, visitor.opaque_identity_ty={:?}, visitor.generics={:?}",
583             prohibit_opaque, visitor.opaque_identity_ty, visitor.generics
584         );
585
586         if let Some(ty) = prohibit_opaque.break_value() {
587             visitor.visit_item(&item);
588             let is_async = match item.kind {
589                 ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
590                     matches!(origin, hir::OpaqueTyOrigin::AsyncFn)
591                 }
592                 _ => unreachable!(),
593             };
594
595             let mut err = struct_span_err!(
596                 tcx.sess,
597                 span,
598                 E0760,
599                 "`{}` return type cannot contain a projection or `Self` that references lifetimes from \
600                  a parent scope",
601                 if is_async { "async fn" } else { "impl Trait" },
602             );
603
604             for (span, name) in visitor.selftys {
605                 err.span_suggestion(
606                     span,
607                     "consider spelling out the type instead",
608                     name.unwrap_or_else(|| format!("{:?}", ty)),
609                     Applicability::MaybeIncorrect,
610                 );
611             }
612             err.emit();
613         }
614     }
615 }
616
617 /// Checks that an opaque type does not contain cycles.
618 pub(super) fn check_opaque_for_cycles<'tcx>(
619     tcx: TyCtxt<'tcx>,
620     def_id: LocalDefId,
621     substs: SubstsRef<'tcx>,
622     span: Span,
623     origin: &hir::OpaqueTyOrigin,
624 ) -> Result<(), ErrorReported> {
625     if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs)
626     {
627         match origin {
628             hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span),
629             hir::OpaqueTyOrigin::Binding => {
630                 binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type)
631             }
632             _ => opaque_type_cycle_error(tcx, def_id, span),
633         }
634         Err(ErrorReported)
635     } else {
636         Ok(())
637     }
638 }
639
640 /// Check that the concrete type behind `impl Trait` actually implements `Trait`.
641 ///
642 /// This is mostly checked at the places that specify the opaque type, but we
643 /// check those cases in the `param_env` of that function, which may have
644 /// bounds not on this opaque type:
645 ///
646 /// type X<T> = impl Clone
647 /// fn f<T: Clone>(t: T) -> X<T> {
648 ///     t
649 /// }
650 ///
651 /// Without this check the above code is incorrectly accepted: we would ICE if
652 /// some tried, for example, to clone an `Option<X<&mut ()>>`.
653 fn check_opaque_meets_bounds<'tcx>(
654     tcx: TyCtxt<'tcx>,
655     def_id: LocalDefId,
656     substs: SubstsRef<'tcx>,
657     span: Span,
658     origin: &hir::OpaqueTyOrigin,
659 ) {
660     match origin {
661         // Checked when type checking the function containing them.
662         hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => return,
663         // Can have different predicates to their defining use
664         hir::OpaqueTyOrigin::Binding | hir::OpaqueTyOrigin::Misc => {}
665     }
666
667     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
668     let param_env = tcx.param_env(def_id);
669
670     tcx.infer_ctxt().enter(move |infcx| {
671         let inh = Inherited::new(infcx, def_id);
672         let infcx = &inh.infcx;
673         let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs);
674
675         let misc_cause = traits::ObligationCause::misc(span, hir_id);
676
677         let (_, opaque_type_map) = inh.register_infer_ok_obligations(
678             infcx.instantiate_opaque_types(def_id, hir_id, param_env, opaque_ty, span),
679         );
680
681         for (def_id, opaque_defn) in opaque_type_map {
682             match infcx
683                 .at(&misc_cause, param_env)
684                 .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, opaque_defn.substs))
685             {
686                 Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok),
687                 Err(ty_err) => tcx.sess.delay_span_bug(
688                     opaque_defn.definition_span,
689                     &format!(
690                         "could not unify `{}` with revealed type:\n{}",
691                         opaque_defn.concrete_ty, ty_err,
692                     ),
693                 ),
694             }
695         }
696
697         // Check that all obligations are satisfied by the implementation's
698         // version.
699         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
700             infcx.report_fulfillment_errors(errors, None, false);
701         }
702
703         // Finally, resolve all regions. This catches wily misuses of
704         // lifetime parameters.
705         let fcx = FnCtxt::new(&inh, param_env, hir_id);
706         fcx.regionck_item(hir_id, span, &[]);
707     });
708 }
709
710 pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
711     debug!(
712         "check_item_type(it.hir_id={}, it.name={})",
713         it.hir_id,
714         tcx.def_path_str(tcx.hir().local_def_id(it.hir_id).to_def_id())
715     );
716     let _indenter = indenter();
717     match it.kind {
718         // Consts can play a role in type-checking, so they are included here.
719         hir::ItemKind::Static(..) => {
720             let def_id = tcx.hir().local_def_id(it.hir_id);
721             tcx.ensure().typeck(def_id);
722             maybe_check_static_with_link_section(tcx, def_id, it.span);
723             check_static_inhabited(tcx, def_id, it.span);
724         }
725         hir::ItemKind::Const(..) => {
726             tcx.ensure().typeck(tcx.hir().local_def_id(it.hir_id));
727         }
728         hir::ItemKind::Enum(ref enum_definition, _) => {
729             check_enum(tcx, it.span, &enum_definition.variants, it.hir_id);
730         }
731         hir::ItemKind::Fn(..) => {} // entirely within check_item_body
732         hir::ItemKind::Impl(ref impl_) => {
733             debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id);
734             let impl_def_id = tcx.hir().local_def_id(it.hir_id);
735             if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
736                 check_impl_items_against_trait(
737                     tcx,
738                     it.span,
739                     impl_def_id,
740                     impl_trait_ref,
741                     &impl_.items,
742                 );
743                 let trait_def_id = impl_trait_ref.def_id;
744                 check_on_unimplemented(tcx, trait_def_id, it);
745             }
746         }
747         hir::ItemKind::Trait(_, _, _, _, ref items) => {
748             let def_id = tcx.hir().local_def_id(it.hir_id);
749             check_on_unimplemented(tcx, def_id.to_def_id(), it);
750
751             for item in items.iter() {
752                 let item = tcx.hir().trait_item(item.id);
753                 match item.kind {
754                     hir::TraitItemKind::Fn(ref sig, _) => {
755                         let abi = sig.header.abi;
756                         fn_maybe_err(tcx, item.ident.span, abi);
757                     }
758                     hir::TraitItemKind::Type(.., Some(_default)) => {
759                         let item_def_id = tcx.hir().local_def_id(item.hir_id).to_def_id();
760                         let assoc_item = tcx.associated_item(item_def_id);
761                         let trait_substs =
762                             InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
763                         let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
764                             tcx,
765                             assoc_item,
766                             assoc_item,
767                             item.span,
768                             ty::TraitRef { def_id: def_id.to_def_id(), substs: trait_substs },
769                         );
770                     }
771                     _ => {}
772                 }
773             }
774         }
775         hir::ItemKind::Struct(..) => {
776             check_struct(tcx, it.hir_id, it.span);
777         }
778         hir::ItemKind::Union(..) => {
779             check_union(tcx, it.hir_id, it.span);
780         }
781         hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
782             // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
783             // `async-std` (and `pub async fn` in general).
784             // Since rustdoc doesn't care about the concrete type behind `impl Trait`, just don't look at it!
785             // See https://github.com/rust-lang/rust/issues/75100
786             if !tcx.sess.opts.actually_rustdoc {
787                 let def_id = tcx.hir().local_def_id(it.hir_id);
788
789                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
790                 check_opaque(tcx, def_id, substs, it.span, &origin);
791             }
792         }
793         hir::ItemKind::TyAlias(..) => {
794             let def_id = tcx.hir().local_def_id(it.hir_id);
795             let pty_ty = tcx.type_of(def_id);
796             let generics = tcx.generics_of(def_id);
797             check_type_params_are_used(tcx, &generics, pty_ty);
798         }
799         hir::ItemKind::ForeignMod { abi, items } => {
800             check_abi(tcx, it.span, abi);
801
802             if abi == Abi::RustIntrinsic {
803                 for item in items {
804                     let item = tcx.hir().foreign_item(item.id);
805                     intrinsic::check_intrinsic_type(tcx, item);
806                 }
807             } else if abi == Abi::PlatformIntrinsic {
808                 for item in items {
809                     let item = tcx.hir().foreign_item(item.id);
810                     intrinsic::check_platform_intrinsic_type(tcx, item);
811                 }
812             } else {
813                 for item in items {
814                     let def_id = tcx.hir().local_def_id(item.id.hir_id);
815                     let generics = tcx.generics_of(def_id);
816                     let own_counts = generics.own_counts();
817                     if generics.params.len() - own_counts.lifetimes != 0 {
818                         let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
819                             (_, 0) => ("type", "types", Some("u32")),
820                             // We don't specify an example value, because we can't generate
821                             // a valid value for any type.
822                             (0, _) => ("const", "consts", None),
823                             _ => ("type or const", "types or consts", None),
824                         };
825                         struct_span_err!(
826                             tcx.sess,
827                             item.span,
828                             E0044,
829                             "foreign items may not have {} parameters",
830                             kinds,
831                         )
832                         .span_label(item.span, &format!("can't have {} parameters", kinds))
833                         .help(
834                             // FIXME: once we start storing spans for type arguments, turn this
835                             // into a suggestion.
836                             &format!(
837                                 "replace the {} parameters with concrete {}{}",
838                                 kinds,
839                                 kinds_pl,
840                                 egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
841                             ),
842                         )
843                         .emit();
844                     }
845
846                     let item = tcx.hir().foreign_item(item.id);
847                     match item.kind {
848                         hir::ForeignItemKind::Fn(ref fn_decl, _, _) => {
849                             require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span);
850                         }
851                         hir::ForeignItemKind::Static(..) => {
852                             check_static_inhabited(tcx, def_id, item.span);
853                         }
854                         _ => {}
855                     }
856                 }
857             }
858         }
859         _ => { /* nothing to do */ }
860     }
861 }
862
863 pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
864     let item_def_id = tcx.hir().local_def_id(item.hir_id);
865     // an error would be reported if this fails.
866     let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id.to_def_id());
867 }
868
869 pub(super) fn check_specialization_validity<'tcx>(
870     tcx: TyCtxt<'tcx>,
871     trait_def: &ty::TraitDef,
872     trait_item: &ty::AssocItem,
873     impl_id: DefId,
874     impl_item: &hir::ImplItem<'_>,
875 ) {
876     let kind = match impl_item.kind {
877         hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
878         hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
879         hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
880     };
881
882     let ancestors = match trait_def.ancestors(tcx, impl_id) {
883         Ok(ancestors) => ancestors,
884         Err(_) => return,
885     };
886     let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
887         if parent.is_from_trait() {
888             None
889         } else {
890             Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
891         }
892     });
893
894     let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
895         match parent_item {
896             // Parent impl exists, and contains the parent item we're trying to specialize, but
897             // doesn't mark it `default`.
898             Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
899                 Some(Err(parent_impl.def_id()))
900             }
901
902             // Parent impl contains item and makes it specializable.
903             Some(_) => Some(Ok(())),
904
905             // Parent impl doesn't mention the item. This means it's inherited from the
906             // grandparent. In that case, if parent is a `default impl`, inherited items use the
907             // "defaultness" from the grandparent, else they are final.
908             None => {
909                 if tcx.impl_defaultness(parent_impl.def_id()).is_default() {
910                     None
911                 } else {
912                     Some(Err(parent_impl.def_id()))
913                 }
914             }
915         }
916     });
917
918     // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
919     // item. This is allowed, the item isn't actually getting specialized here.
920     let result = opt_result.unwrap_or(Ok(()));
921
922     if let Err(parent_impl) = result {
923         report_forbidden_specialization(tcx, impl_item, parent_impl);
924     }
925 }
926
927 pub(super) fn check_impl_items_against_trait<'tcx>(
928     tcx: TyCtxt<'tcx>,
929     full_impl_span: Span,
930     impl_id: LocalDefId,
931     impl_trait_ref: ty::TraitRef<'tcx>,
932     impl_item_refs: &[hir::ImplItemRef<'_>],
933 ) {
934     // If the trait reference itself is erroneous (so the compilation is going
935     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
936     // isn't populated for such impls.
937     if impl_trait_ref.references_error() {
938         return;
939     }
940
941     // Negative impls are not expected to have any items
942     match tcx.impl_polarity(impl_id) {
943         ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
944         ty::ImplPolarity::Negative => {
945             if let [first_item_ref, ..] = impl_item_refs {
946                 let first_item_span = tcx.hir().impl_item(first_item_ref.id).span;
947                 struct_span_err!(
948                     tcx.sess,
949                     first_item_span,
950                     E0749,
951                     "negative impls cannot have any items"
952                 )
953                 .emit();
954             }
955             return;
956         }
957     }
958
959     // Locate trait definition and items
960     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
961     let impl_items = impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id));
962     let associated_items = tcx.associated_items(impl_trait_ref.def_id);
963
964     // Check existing impl methods to see if they are both present in trait
965     // and compatible with trait signature
966     for impl_item in impl_items {
967         let ty_impl_item = tcx.associated_item(tcx.hir().local_def_id(impl_item.hir_id));
968
969         let mut items =
970             associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id);
971
972         let (compatible_kind, ty_trait_item) = if let Some(ty_trait_item) = items.next() {
973             let is_compatible = |ty: &&ty::AssocItem| match (ty.kind, &impl_item.kind) {
974                 (ty::AssocKind::Const, hir::ImplItemKind::Const(..)) => true,
975                 (ty::AssocKind::Fn, hir::ImplItemKind::Fn(..)) => true,
976                 (ty::AssocKind::Type, hir::ImplItemKind::TyAlias(..)) => true,
977                 _ => false,
978             };
979
980             // If we don't have a compatible item, we'll use the first one whose name matches
981             // to report an error.
982             let mut compatible_kind = is_compatible(&ty_trait_item);
983             let mut trait_item = ty_trait_item;
984
985             if !compatible_kind {
986                 if let Some(ty_trait_item) = items.find(is_compatible) {
987                     compatible_kind = true;
988                     trait_item = ty_trait_item;
989                 }
990             }
991
992             (compatible_kind, trait_item)
993         } else {
994             continue;
995         };
996
997         if compatible_kind {
998             match impl_item.kind {
999                 hir::ImplItemKind::Const(..) => {
1000                     // Find associated const definition.
1001                     compare_const_impl(
1002                         tcx,
1003                         &ty_impl_item,
1004                         impl_item.span,
1005                         &ty_trait_item,
1006                         impl_trait_ref,
1007                     );
1008                 }
1009                 hir::ImplItemKind::Fn(..) => {
1010                     let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1011                     compare_impl_method(
1012                         tcx,
1013                         &ty_impl_item,
1014                         impl_item.span,
1015                         &ty_trait_item,
1016                         impl_trait_ref,
1017                         opt_trait_span,
1018                     );
1019                 }
1020                 hir::ImplItemKind::TyAlias(_) => {
1021                     let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
1022                     compare_ty_impl(
1023                         tcx,
1024                         &ty_impl_item,
1025                         impl_item.span,
1026                         &ty_trait_item,
1027                         impl_trait_ref,
1028                         opt_trait_span,
1029                     );
1030                 }
1031             }
1032
1033             check_specialization_validity(
1034                 tcx,
1035                 trait_def,
1036                 &ty_trait_item,
1037                 impl_id.to_def_id(),
1038                 impl_item,
1039             );
1040         } else {
1041             report_mismatch_error(
1042                 tcx,
1043                 ty_trait_item.def_id,
1044                 impl_trait_ref,
1045                 impl_item,
1046                 &ty_impl_item,
1047             );
1048         }
1049     }
1050
1051     if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1052         let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1053
1054         // Check for missing items from trait
1055         let mut missing_items = Vec::new();
1056         for trait_item in tcx.associated_items(impl_trait_ref.def_id).in_definition_order() {
1057             let is_implemented = ancestors
1058                 .leaf_def(tcx, trait_item.ident, trait_item.kind)
1059                 .map(|node_item| !node_item.defining_node.is_from_trait())
1060                 .unwrap_or(false);
1061
1062             if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
1063                 if !trait_item.defaultness.has_value() {
1064                     missing_items.push(*trait_item);
1065                 }
1066             }
1067         }
1068
1069         if !missing_items.is_empty() {
1070             missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
1071         }
1072     }
1073 }
1074
1075 #[inline(never)]
1076 #[cold]
1077 fn report_mismatch_error<'tcx>(
1078     tcx: TyCtxt<'tcx>,
1079     trait_item_def_id: DefId,
1080     impl_trait_ref: ty::TraitRef<'tcx>,
1081     impl_item: &hir::ImplItem<'_>,
1082     ty_impl_item: &ty::AssocItem,
1083 ) {
1084     let mut err = match impl_item.kind {
1085         hir::ImplItemKind::Const(..) => {
1086             // Find associated const definition.
1087             struct_span_err!(
1088                 tcx.sess,
1089                 impl_item.span,
1090                 E0323,
1091                 "item `{}` is an associated const, which doesn't match its trait `{}`",
1092                 ty_impl_item.ident,
1093                 impl_trait_ref.print_only_trait_path()
1094             )
1095         }
1096
1097         hir::ImplItemKind::Fn(..) => {
1098             struct_span_err!(
1099                 tcx.sess,
1100                 impl_item.span,
1101                 E0324,
1102                 "item `{}` is an associated method, which doesn't match its trait `{}`",
1103                 ty_impl_item.ident,
1104                 impl_trait_ref.print_only_trait_path()
1105             )
1106         }
1107
1108         hir::ImplItemKind::TyAlias(_) => {
1109             struct_span_err!(
1110                 tcx.sess,
1111                 impl_item.span,
1112                 E0325,
1113                 "item `{}` is an associated type, which doesn't match its trait `{}`",
1114                 ty_impl_item.ident,
1115                 impl_trait_ref.print_only_trait_path()
1116             )
1117         }
1118     };
1119
1120     err.span_label(impl_item.span, "does not match trait");
1121     if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) {
1122         err.span_label(trait_span, "item in trait");
1123     }
1124     err.emit();
1125 }
1126
1127 /// Checks whether a type can be represented in memory. In particular, it
1128 /// identifies types that contain themselves without indirection through a
1129 /// pointer, which would mean their size is unbounded.
1130 pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool {
1131     let rty = tcx.type_of(item_def_id);
1132
1133     // Check that it is possible to represent this type. This call identifies
1134     // (1) types that contain themselves and (2) types that contain a different
1135     // recursive type. It is only necessary to throw an error on those that
1136     // contain themselves. For case 2, there must be an inner type that will be
1137     // caught by case 1.
1138     match rty.is_representable(tcx, sp) {
1139         Representability::SelfRecursive(spans) => {
1140             recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans);
1141             return false;
1142         }
1143         Representability::Representable | Representability::ContainsRecursive => (),
1144     }
1145     true
1146 }
1147
1148 pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1149     let t = tcx.type_of(def_id);
1150     if let ty::Adt(def, substs) = t.kind() {
1151         if def.is_struct() {
1152             let fields = &def.non_enum_variant().fields;
1153             if fields.is_empty() {
1154                 struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1155                 return;
1156             }
1157             let e = fields[0].ty(tcx, substs);
1158             if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1159                 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1160                     .span_label(sp, "SIMD elements must have the same type")
1161                     .emit();
1162                 return;
1163             }
1164
1165             let len = if let ty::Array(_ty, c) = e.kind() {
1166                 c.try_eval_usize(tcx, tcx.param_env(def.did))
1167             } else {
1168                 Some(fields.len() as u64)
1169             };
1170             if let Some(len) = len {
1171                 if len == 0 {
1172                     struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit();
1173                     return;
1174                 } else if !len.is_power_of_two() {
1175                     struct_span_err!(
1176                         tcx.sess,
1177                         sp,
1178                         E0075,
1179                         "SIMD vector length must be a power of two"
1180                     )
1181                     .emit();
1182                     return;
1183                 } else if len > MAX_SIMD_LANES {
1184                     struct_span_err!(
1185                         tcx.sess,
1186                         sp,
1187                         E0075,
1188                         "SIMD vector cannot have more than {} elements",
1189                         MAX_SIMD_LANES,
1190                     )
1191                     .emit();
1192                     return;
1193                 }
1194             }
1195
1196             match e.kind() {
1197                 ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ }
1198                 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1199                 ty::Array(ty, _c) if ty.is_machine() => { /* struct([f32; 4]) */ }
1200                 _ => {
1201                     struct_span_err!(
1202                         tcx.sess,
1203                         sp,
1204                         E0077,
1205                         "SIMD vector element type should be a \
1206                          primitive scalar (integer/float/pointer) type"
1207                     )
1208                     .emit();
1209                     return;
1210                 }
1211             }
1212         }
1213     }
1214 }
1215
1216 pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
1217     let repr = def.repr;
1218     if repr.packed() {
1219         for attr in tcx.get_attrs(def.did).iter() {
1220             for r in attr::find_repr_attrs(&tcx.sess, attr) {
1221                 if let attr::ReprPacked(pack) = r {
1222                     if let Some(repr_pack) = repr.pack {
1223                         if pack as u64 != repr_pack.bytes() {
1224                             struct_span_err!(
1225                                 tcx.sess,
1226                                 sp,
1227                                 E0634,
1228                                 "type has conflicting packed representation hints"
1229                             )
1230                             .emit();
1231                         }
1232                     }
1233                 }
1234             }
1235         }
1236         if repr.align.is_some() {
1237             struct_span_err!(
1238                 tcx.sess,
1239                 sp,
1240                 E0587,
1241                 "type has conflicting packed and align representation hints"
1242             )
1243             .emit();
1244         } else {
1245             if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) {
1246                 let mut err = struct_span_err!(
1247                     tcx.sess,
1248                     sp,
1249                     E0588,
1250                     "packed type cannot transitively contain a `#[repr(align)]` type"
1251                 );
1252
1253                 err.span_note(
1254                     tcx.def_span(def_spans[0].0),
1255                     &format!(
1256                         "`{}` has a `#[repr(align)]` attribute",
1257                         tcx.item_name(def_spans[0].0)
1258                     ),
1259                 );
1260
1261                 if def_spans.len() > 2 {
1262                     let mut first = true;
1263                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
1264                         let ident = tcx.item_name(*adt_def);
1265                         err.span_note(
1266                             *span,
1267                             &if first {
1268                                 format!(
1269                                     "`{}` contains a field of type `{}`",
1270                                     tcx.type_of(def.did),
1271                                     ident
1272                                 )
1273                             } else {
1274                                 format!("...which contains a field of type `{}`", ident)
1275                             },
1276                         );
1277                         first = false;
1278                     }
1279                 }
1280
1281                 err.emit();
1282             }
1283         }
1284     }
1285 }
1286
1287 pub(super) fn check_packed_inner(
1288     tcx: TyCtxt<'_>,
1289     def_id: DefId,
1290     stack: &mut Vec<DefId>,
1291 ) -> Option<Vec<(DefId, Span)>> {
1292     if let ty::Adt(def, substs) = tcx.type_of(def_id).kind() {
1293         if def.is_struct() || def.is_union() {
1294             if def.repr.align.is_some() {
1295                 return Some(vec![(def.did, DUMMY_SP)]);
1296             }
1297
1298             stack.push(def_id);
1299             for field in &def.non_enum_variant().fields {
1300                 if let ty::Adt(def, _) = field.ty(tcx, substs).kind() {
1301                     if !stack.contains(&def.did) {
1302                         if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) {
1303                             defs.push((def.did, field.ident.span));
1304                             return Some(defs);
1305                         }
1306                     }
1307                 }
1308             }
1309             stack.pop();
1310         }
1311     }
1312
1313     None
1314 }
1315
1316 pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) {
1317     if !adt.repr.transparent() {
1318         return;
1319     }
1320     let sp = tcx.sess.source_map().guess_head_span(sp);
1321
1322     if adt.is_union() && !tcx.features().transparent_unions {
1323         feature_err(
1324             &tcx.sess.parse_sess,
1325             sym::transparent_unions,
1326             sp,
1327             "transparent unions are unstable",
1328         )
1329         .emit();
1330     }
1331
1332     if adt.variants.len() != 1 {
1333         bad_variant_count(tcx, adt, sp, adt.did);
1334         if adt.variants.is_empty() {
1335             // Don't bother checking the fields. No variants (and thus no fields) exist.
1336             return;
1337         }
1338     }
1339
1340     // For each field, figure out if it's known to be a ZST and align(1)
1341     let field_infos = adt.all_fields().map(|field| {
1342         let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did));
1343         let param_env = tcx.param_env(field.did);
1344         let layout = tcx.layout_of(param_env.and(ty));
1345         // We are currently checking the type this field came from, so it must be local
1346         let span = tcx.hir().span_if_local(field.did).unwrap();
1347         let zst = layout.map_or(false, |layout| layout.is_zst());
1348         let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1);
1349         (span, zst, align1)
1350     });
1351
1352     let non_zst_fields =
1353         field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None });
1354     let non_zst_count = non_zst_fields.clone().count();
1355     if non_zst_count != 1 {
1356         bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp);
1357     }
1358     for (span, zst, align1) in field_infos {
1359         if zst && !align1 {
1360             struct_span_err!(
1361                 tcx.sess,
1362                 span,
1363                 E0691,
1364                 "zero-sized field in transparent {} has alignment larger than 1",
1365                 adt.descr(),
1366             )
1367             .span_label(span, "has alignment larger than 1")
1368             .emit();
1369         }
1370     }
1371 }
1372
1373 #[allow(trivial_numeric_casts)]
1374 pub fn check_enum<'tcx>(
1375     tcx: TyCtxt<'tcx>,
1376     sp: Span,
1377     vs: &'tcx [hir::Variant<'tcx>],
1378     id: hir::HirId,
1379 ) {
1380     let def_id = tcx.hir().local_def_id(id);
1381     let def = tcx.adt_def(def_id);
1382     def.destructor(tcx); // force the destructor to be evaluated
1383
1384     if vs.is_empty() {
1385         let attributes = tcx.get_attrs(def_id.to_def_id());
1386         if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) {
1387             struct_span_err!(
1388                 tcx.sess,
1389                 attr.span,
1390                 E0084,
1391                 "unsupported representation for zero-variant enum"
1392             )
1393             .span_label(sp, "zero-variant enum")
1394             .emit();
1395         }
1396     }
1397
1398     let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1399     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1400         if !tcx.features().repr128 {
1401             feature_err(
1402                 &tcx.sess.parse_sess,
1403                 sym::repr128,
1404                 sp,
1405                 "repr with 128-bit type is unstable",
1406             )
1407             .emit();
1408         }
1409     }
1410
1411     for v in vs {
1412         if let Some(ref e) = v.disr_expr {
1413             tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id));
1414         }
1415     }
1416
1417     if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant {
1418         let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));
1419
1420         let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
1421         let has_non_units = vs.iter().any(|var| !is_unit(var));
1422         let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var));
1423         let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var));
1424
1425         if disr_non_unit || (disr_units && has_non_units) {
1426             let mut err =
1427                 struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified");
1428             err.emit();
1429         }
1430     }
1431
1432     let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1433     for ((_, discr), v) in def.discriminants(tcx).zip(vs) {
1434         // Check for duplicate discriminant values
1435         if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1436             let variant_did = def.variants[VariantIdx::new(i)].def_id;
1437             let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1438             let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1439             let i_span = match variant_i.disr_expr {
1440                 Some(ref expr) => tcx.hir().span(expr.hir_id),
1441                 None => tcx.hir().span(variant_i_hir_id),
1442             };
1443             let span = match v.disr_expr {
1444                 Some(ref expr) => tcx.hir().span(expr.hir_id),
1445                 None => v.span,
1446             };
1447             struct_span_err!(
1448                 tcx.sess,
1449                 span,
1450                 E0081,
1451                 "discriminant value `{}` already exists",
1452                 disr_vals[i]
1453             )
1454             .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1455             .span_label(span, format!("enum already has `{}`", disr_vals[i]))
1456             .emit();
1457         }
1458         disr_vals.push(discr);
1459     }
1460
1461     check_representable(tcx, sp, def_id);
1462     check_transparent(tcx, sp, def);
1463 }
1464
1465 pub(super) fn check_type_params_are_used<'tcx>(
1466     tcx: TyCtxt<'tcx>,
1467     generics: &ty::Generics,
1468     ty: Ty<'tcx>,
1469 ) {
1470     debug!("check_type_params_are_used(generics={:?}, ty={:?})", generics, ty);
1471
1472     assert_eq!(generics.parent, None);
1473
1474     if generics.own_counts().types == 0 {
1475         return;
1476     }
1477
1478     let mut params_used = BitSet::new_empty(generics.params.len());
1479
1480     if ty.references_error() {
1481         // If there is already another error, do not emit
1482         // an error for not using a type parameter.
1483         assert!(tcx.sess.has_errors());
1484         return;
1485     }
1486
1487     for leaf in ty.walk() {
1488         if let GenericArgKind::Type(leaf_ty) = leaf.unpack() {
1489             if let ty::Param(param) = leaf_ty.kind() {
1490                 debug!("found use of ty param {:?}", param);
1491                 params_used.insert(param.index);
1492             }
1493         }
1494     }
1495
1496     for param in &generics.params {
1497         if !params_used.contains(param.index) {
1498             if let ty::GenericParamDefKind::Type { .. } = param.kind {
1499                 let span = tcx.def_span(param.def_id);
1500                 struct_span_err!(
1501                     tcx.sess,
1502                     span,
1503                     E0091,
1504                     "type parameter `{}` is unused",
1505                     param.name,
1506                 )
1507                 .span_label(span, "unused type parameter")
1508                 .emit();
1509             }
1510         }
1511     }
1512 }
1513
1514 pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1515     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx });
1516 }
1517
1518 pub(super) fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1519     wfcheck::check_item_well_formed(tcx, def_id);
1520 }
1521
1522 pub(super) fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1523     wfcheck::check_trait_item(tcx, def_id);
1524 }
1525
1526 pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1527     wfcheck::check_impl_item(tcx, def_id);
1528 }
1529
1530 fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) {
1531     struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing")
1532         .span_label(span, "recursive `async fn`")
1533         .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`")
1534         .note(
1535             "consider using the `async_recursion` crate: https://crates.io/crates/async_recursion",
1536         )
1537         .emit();
1538 }
1539
1540 /// Emit an error for recursive opaque types.
1541 ///
1542 /// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1543 /// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1544 /// `impl Trait`.
1545 ///
1546 /// If all the return expressions evaluate to `!`, then we explain that the error will go away
1547 /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1548 fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
1549     let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type");
1550
1551     let mut label = false;
1552     if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) {
1553         let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id));
1554         if visitor
1555             .returns
1556             .iter()
1557             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1558             .all(|ty| matches!(ty.kind(), ty::Never))
1559         {
1560             let spans = visitor
1561                 .returns
1562                 .iter()
1563                 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1564                 .map(|expr| expr.span)
1565                 .collect::<Vec<Span>>();
1566             let span_len = spans.len();
1567             if span_len == 1 {
1568                 err.span_label(spans[0], "this returned value is of `!` type");
1569             } else {
1570                 let mut multispan: MultiSpan = spans.clone().into();
1571                 for span in spans {
1572                     multispan
1573                         .push_span_label(span, "this returned value is of `!` type".to_string());
1574                 }
1575                 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1576             }
1577             err.help("this error will resolve once the item's body returns a concrete type");
1578         } else {
1579             let mut seen = FxHashSet::default();
1580             seen.insert(span);
1581             err.span_label(span, "recursive opaque type");
1582             label = true;
1583             for (sp, ty) in visitor
1584                 .returns
1585                 .iter()
1586                 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1587                 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1588             {
1589                 struct VisitTypes(Vec<DefId>);
1590                 impl<'tcx> ty::fold::TypeVisitor<'tcx> for VisitTypes {
1591                     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1592                         match *t.kind() {
1593                             ty::Opaque(def, _) => {
1594                                 self.0.push(def);
1595                                 ControlFlow::CONTINUE
1596                             }
1597                             _ => t.super_visit_with(self),
1598                         }
1599                     }
1600                 }
1601                 let mut visitor = VisitTypes(vec![]);
1602                 ty.visit_with(&mut visitor);
1603                 for def_id in visitor.0 {
1604                     let ty_span = tcx.def_span(def_id);
1605                     if !seen.contains(&ty_span) {
1606                         err.span_label(ty_span, &format!("returning this opaque type `{}`", ty));
1607                         seen.insert(ty_span);
1608                     }
1609                     err.span_label(sp, &format!("returning here with type `{}`", ty));
1610                 }
1611             }
1612         }
1613     }
1614     if !label {
1615         err.span_label(span, "cannot resolve opaque type");
1616     }
1617     err.emit();
1618 }