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