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