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