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