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