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