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