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