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